重新设计NFC卡片处理方式,改为主窗口监听。

This commit is contained in:
2026-03-16 11:41:35 +08:00
parent a18057e095
commit 0d2394c842
9 changed files with 469 additions and 319 deletions

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle #Created by .winboll/winboll_app_build.gradle
#Mon Mar 16 02:31:00 GMT 2026 #Mon Mar 16 03:39:59 GMT 2026
stageCount=0 stageCount=0
libraryProject= libraryProject=
baseVersion=15.11 baseVersion=15.11
publishVersion=15.0.0 publishVersion=15.0.0
buildCount=12 buildCount=27
baseBetaVersion=15.0.1 baseBetaVersion=15.0.1

View File

@@ -8,8 +8,12 @@
<!-- 拥有完全的网络访问权限 --> <!-- 拥有完全的网络访问权限 -->
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <!-- 开机启动 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- 运行前台服务 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-feature <uses-feature
android:name="android.hardware.nfc" android:name="android.hardware.nfc"
@@ -54,21 +58,33 @@
</activity> </activity>
<service <!-- 新增NFC 透明代理 Activity -->
android:name=".nfc.AutoNFCService" <activity
android:name=".nfc.NfcProxyActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:excludeFromRecents="true"
android:exported="false" /> android:exported="false" />
<receiver <service
android:name=".nfc.AutoNFCBootReceiver" android:name=".nfc.AutoNFCService"
android:exported="true"> android:exported="false"/>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" /> <receiver
</intent-filter> android:name=".nfc.AutoNFCBootReceiver"
</receiver> android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<meta-data <meta-data
android:name="android.max_aspect" android:name="android.max_aspect"
android:value="4.0"/> android:value="4.0"/>
</application> </application>
</manifest> </manifest>

View File

@@ -1,6 +1,9 @@
package cc.winboll.studio.autonfc; package cc.winboll.studio.autonfc;
import android.app.PendingIntent;
import android.content.Intent; import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle; import android.os.Bundle;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
@@ -10,10 +13,15 @@ import androidx.appcompat.widget.Toolbar;
import cc.winboll.studio.autonfc.nfc.AutoNFCService; import cc.winboll.studio.autonfc.nfc.AutoNFCService;
import cc.winboll.studio.autonfc.nfc.NFCInterfaceActivity; import cc.winboll.studio.autonfc.nfc.NFCInterfaceActivity;
import cc.winboll.studio.libappbase.LogActivity; import cc.winboll.studio.libappbase.LogActivity;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils; import cc.winboll.studio.libappbase.ToastUtils;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@@ -23,35 +31,69 @@ public class MainActivity extends AppCompatActivity {
Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
// 初始化 NFC
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
Intent nfcIntent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
mPendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
LogUtils.d(TAG, "onCreate() -> NFC 监听已绑定到 MainActivity");
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
LogUtils.d(TAG, "onResume() -> 开启 NFC 前台分发");
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
LogUtils.d(TAG, "onPause() -> 关闭 NFC 前台分发");
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
// NFC 卡片靠近唯一入口
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
LogUtils.d(TAG, "onNewIntent() -> 检测到 NFC 卡片");
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag == null) {
LogUtils.e(TAG, "onNewIntent() -> Tag 为空");
return;
}
// 转发给服务处理
Intent serviceIntent = new Intent(this, AutoNFCService.class);
serviceIntent.putExtras(intent);
startService(serviceIntent);
} }
// 加载菜单
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu); getMenuInflater().inflate(R.menu.main_menu, menu);
return true; return true;
} }
// 菜单点击
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); int id = item.getItemId();
if (id == R.id.menu_start_service) { if (id == R.id.menu_start_service) {
startService(new Intent(this, AutoNFCService.class)); startService(new Intent(this, AutoNFCService.class));
ToastUtils.show("NFC服务已启动"); ToastUtils.show("NFC 服务已启动");
return true; return true;
} }
if (id == R.id.menu_stop_service) { if (id == R.id.menu_stop_service) {
stopService(new Intent(this, AutoNFCService.class)); stopService(new Intent(this, AutoNFCService.class));
ToastUtils.show("NFC服务已停止"); ToastUtils.show("NFC 服务已停止");
return true; return true;
} }

View File

@@ -7,85 +7,57 @@ import android.app.PendingIntent;
import android.app.Service; import android.app.Service;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.nfc.NdefMessage; import android.nfc.NdefMessage;
import android.nfc.NdefRecord; import android.nfc.NdefRecord;
import android.nfc.NfcAdapter; import android.nfc.NfcAdapter;
import android.nfc.Tag; import android.nfc.Tag;
import android.nfc.tech.Ndef; import android.nfc.tech.Ndef;
import android.widget.Toast; import android.os.Build;
import android.os.IBinder;
import cc.winboll.studio.autonfc.MainActivity;
import cc.winboll.studio.autonfc.R; import cc.winboll.studio.autonfc.R;
import cc.winboll.studio.libappbase.LogUtils; import cc.winboll.studio.libappbase.LogUtils;
import java.nio.charset.Charset; import java.nio.charset.Charset;
/* /*
* 源码说明与描述: * 源码说明与描述:
* NFC 后台监听服务(正规保活版) * NFC 后台服务,仅处理 NFC 数据解析与业务逻辑,不负责监听
* 保活方式:前台服务 + START_STICKY + 任务销毁重启 + 开机自启
* *
* 作者:豆包&ZhanGSKen<zhangsken@qq.com> * 作者:豆包&ZhanGSKen<zhangsken@qq.com>
* 创建时间2026-03-16 16:10:00 * 创建时间2026-03-17 00:00:00
* 最后编辑时间2026-03-16 18:20:00 * 最后编辑时间2026-03-17 19:40:00
*/ */
public class AutoNFCService extends Service { public class AutoNFCService extends Service {
public static final String TAG = "AutoNFCService"; public static final String TAG = "AutoNFCService";
private static final int NOTIFICATION_ID = 0x1001; private static final int NOTIFICATION_ID = 0x1001;
private static final String CHANNEL_ID = "AUTO_NFC_SERVICE_CHANNEL"; private static final String CHANNEL_ID = "NFC_SERVICE_CHANNEL";
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
LogUtils.d(TAG, "onCreate"); LogUtils.d(TAG, "onCreate() -> 服务创建");
startForeground(NOTIFICATION_ID, buildNotification()); startForeground(NOTIFICATION_ID, buildNotification());
} }
private Notification buildNotification() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"AutoNFC 后台监听",
NotificationManager.IMPORTANCE_LOW
);
channel.setSound(null, null);
channel.setVibrationPattern(null);
nm.createNotificationChannel(channel);
}
Intent intent = new Intent(this, NFCInterfaceActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return new Notification.Builder(this)
.setChannelId(CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("AutoNFC 运行中")
.setContentText("NFC 卡片监听已启动")
.setContentIntent(pi)
.setSound(null)
.setVibrate(null)
.build();
}
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
LogUtils.d(TAG, "onStartCommand"); LogUtils.d(TAG, "onStartCommand() -> 服务运行");
if (intent != null) { if (intent != null) {
handleNfcIntent(intent); handleNfcIntent(intent);
} }
return START_STICKY; return START_STICKY;
} }
public void handleNfcIntent(Intent intent) { // 处理 MainActivity 转发的 NFC 数据
private void handleNfcIntent(Intent intent) {
String action = intent.getAction(); String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
LogUtils.d(TAG, "NFC 卡片已靠近"); LogUtils.d(TAG, "handleNfcIntent() -> 收到 NFC 卡片");
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
parseNdefData(tag); parseNdefData(tag);
} }
@@ -93,13 +65,13 @@ public class AutoNFCService extends Service {
private void parseNdefData(Tag tag) { private void parseNdefData(Tag tag) {
if (tag == null) { if (tag == null) {
showToast("标签为空"); LogUtils.e(TAG, "parseNdefData() -> tag is null");
return; return;
} }
Ndef ndef = Ndef.get(tag); Ndef ndef = Ndef.get(tag);
if (ndef == null) { if (ndef == null) {
showToast("不支持NDEF格式"); LogUtils.e(TAG, "parseNdefData() -> 不支持 NDEF");
return; return;
} }
@@ -107,51 +79,58 @@ public class AutoNFCService extends Service {
ndef.connect(); ndef.connect();
NdefMessage msg = ndef.getNdefMessage(); NdefMessage msg = ndef.getNdefMessage();
if (msg == null) { if (msg == null) {
LogUtils.w(TAG, "parseNdefData() -> 卡片无数据");
ndef.close(); ndef.close();
showToast("未读取到NDEF数据");
return; return;
} }
NdefRecord[] records = msg.getRecords(); NdefRecord[] records = msg.getRecords();
if (records != null && records.length > 0) { if (records != null && records.length > 0) {
byte[] payload = records[0].getPayload(); byte[] payload = records[0].getPayload();
if (payload.length > 0) { int langLen = payload[0] & 0x3F;
int langLen = payload[0] & 0x3F; int start = 1 + langLen;
int start = 1 + langLen;
if (start < payload.length) { if (start < payload.length) {
String data = new String(payload, start, payload.length - start, Charset.forName("UTF-8")); String data = new String(payload, start, payload.length - start, Charset.forName("UTF-8"));
LogUtils.d(TAG, "读取数据" + data); LogUtils.d(TAG, "parseNdefData() -> 读卡成功" + data);
// 只弹出Toast显示内容
showToast("NFC数据" + data);
}
} }
} }
ndef.close(); ndef.close();
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "解析失败", e); LogUtils.e(TAG, "parseNdefData() -> 读取失败", e);
showToast("读取失败:" + e.getMessage());
} }
} }
/** private Notification buildNotification() {
* 弹出Toast NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
*/
private void showToast(final String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
@Override if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
public void onTaskRemoved(Intent rootIntent) { NotificationChannel channel = new NotificationChannel(
super.onTaskRemoved(rootIntent); CHANNEL_ID,
LogUtils.d(TAG, "任务被移除,重启服务"); "NFC 后台服务",
Intent intent = new Intent(getApplicationContext(), AutoNFCService.class); NotificationManager.IMPORTANCE_LOW
startService(intent); );
channel.setSound(null, null);
channel.setVibrationPattern(null);
nm.createNotificationChannel(channel);
}
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return new Notification.Builder(this)
.setChannelId(CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("NFC 服务运行中")
.setContentText("正在监听卡片")
.setContentIntent(pi)
.build();
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
super.onDestroy(); super.onDestroy();
LogUtils.d(TAG, "onDestroy"); LogUtils.d(TAG, "onDestroy() -> 服务已停止");
} }
@Override @Override

View File

@@ -1,233 +1,250 @@
/*
- 源码说明与描述:
- NFC 调试界面负责前台分发、UI 交互、写入控制
- 作者:豆包&ZhanGSKenzhangsken@qq.com
- 创建时间2026-03-16 10:00:00
- 最后编辑时间2026-03-16 18:59:00
*/
package cc.winboll.studio.autonfc.nfc; package cc.winboll.studio.autonfc.nfc;
import android.app.Activity; import android.app.Activity;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage; import android.nfc.NdefMessage;
import android.nfc.NdefRecord; import android.nfc.NdefRecord;
import android.nfc.NfcAdapter; import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag; import android.nfc.Tag;
import android.nfc.tech.Ndef; import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle; import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import android.view.View;
import cc.winboll.studio.autonfc.R; import cc.winboll.studio.autonfc.R;
import cc.winboll.studio.libappbase.LogUtils; import cc.winboll.studio.libappbase.LogUtils;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/*
* 源码说明与描述:
* NFC 操作界面(自主读卡 + 显示内容与时间 + 写入数据)
* 不再接收 AutoNFCService 消息
*
* 作者:豆包&ZhanGSKen<zhangsken@qq.com>
* 创建时间2026-03-16 16:10:00
* 最后编辑时间2026-03-17 10:45:00
*/
public class NFCInterfaceActivity extends Activity { public class NFCInterfaceActivity extends Activity {
// ========================= 常量定义 ========================= private static final String TAG = "NFCInterfaceActivity";
private static final String TAG = "NFCInterfaceActivity";
// ========================= 成员属性 ========================= private EditText etInput;
private NfcAdapter mNfcAdapter; private TextView tvResult;
private PendingIntent mPendingIntent; private TextView tvStatus;
private IntentFilter[] mIntentFilters;
private String[][] mTechLists;
private TextView tvStatus; private NfcAdapter mNfcAdapter;
private TextView tvData; private PendingIntent mNfcPendingIntent;
private EditText etWriteContent; private Tag mCurrentTag;
private Button btnReadNfc;
private Button btnWriteNfc;
private Tag mCurrentTag; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtils.d(TAG, "onCreate()");
setContentView(R.layout.activity_nfc_interface);
// ========================= 生命周期 ========================= initView();
@Override initNfc();
protected void onCreate(Bundle savedInstanceState) { }
super.onCreate(savedInstanceState);
LogUtils.d(TAG, "onCreate() 调用savedInstanceState: " + (savedInstanceState != null ? "非空" : ""));
setContentView(R.layout.activity_nfc_interface);
tvStatus = (TextView) findViewById(R.id.tv_nfc_status); private void initView() {
tvData = (TextView) findViewById(R.id.tv_nfc_data); LogUtils.d(TAG, "initView()");
etWriteContent = (EditText) findViewById(R.id.et_write_content); etInput = findViewById(R.id.et_input);
btnReadNfc = (Button) findViewById(R.id.btn_read_nfc); tvResult = findViewById(R.id.tv_result);
btnWriteNfc = (Button) findViewById(R.id.btn_write_nfc); tvStatus = findViewById(R.id.tv_status);
}
initNFC(); private void initNfc() {
startAutoNFCService(); LogUtils.d(TAG, "initNfc()");
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
btnReadNfc.setOnClickListener(new View.OnClickListener() { if (mNfcAdapter == null) {
@Override tvStatus.setText("设备不支持NFC");
public void onClick(View v) { return;
LogUtils.d(TAG, "btnReadNfc 点击,进入等待读卡模式"); }
updateStatus("等待卡片靠近..."); if (!mNfcAdapter.isEnabled()) {
} tvStatus.setText("请在设置中开启NFC");
}); return;
}
btnWriteNfc.setOnClickListener(new View.OnClickListener() { mNfcPendingIntent = PendingIntent.getActivity(
@Override this, 0,
public void onClick(View v) { new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
String content = etWriteContent.getText().toString().trim(); PendingIntent.FLAG_UPDATE_CURRENT
LogUtils.d(TAG, "btnWriteNfc 点击,待写入内容: " + content); );
writeNfc(content);
}
});
}
// ========================= 初始化 ========================= tvStatus.setText("NFC已启动等待卡片靠近");
private void initNFC() { }
LogUtils.d(TAG, "initNFC() 开始初始化 NFC 配置");
NfcManager manager = (NfcManager) getSystemService(NFC_SERVICE);
mNfcAdapter = manager.getDefaultAdapter();
if (mNfcAdapter == null) { @Override
LogUtils.e(TAG, "initNFC() 设备不支持 NFC"); protected void onResume() {
updateStatus("设备不支持NFC"); super.onResume();
return; LogUtils.d(TAG, "onResume() -> 启用前台读卡");
} enableForegroundDispatch();
}
Intent intent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); @Override
mPendingIntent = PendingIntent.getActivity(this, 0, intent, 0); protected void onPause() {
super.onPause();
LogUtils.d(TAG, "onPause() -> 停止前台读卡");
disableForegroundDispatch();
mCurrentTag = null;
}
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); private void enableForegroundDispatch() {
try { if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
filter.addDataType("/"); mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, null, null);
} catch (IntentFilter.MalformedMimeTypeException e) { }
LogUtils.e(TAG, "initNFC() 过滤器异常: " + e.getMessage(), e); }
}
mIntentFilters = new IntentFilter[] { filter }; private void disableForegroundDispatch() {
mTechLists = new String[][] { if (mNfcAdapter != null) {
{ Ndef.class.getName() }, mNfcAdapter.disableForegroundDispatch(this);
{ NdefFormatable.class.getName() } }
}; }
LogUtils.d(TAG, "initNFC() 完成 NFC 前台分发配置");
updateStatus("NFC 初始化完成");
}
private void startAutoNFCService() { @Override
LogUtils.d(TAG, "startAutoNFCService() 启动后台监听服务"); protected void onNewIntent(Intent intent) {
Intent service = new Intent(this, AutoNFCService.class); super.onNewIntent(intent);
startService(service); LogUtils.d(TAG, "onNewIntent() -> 卡片已靠近");
}
// ========================= 生命周期回调 ========================= mCurrentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
@Override tvStatus.setText("卡片已连接");
protected void onResume() {
super.onResume();
LogUtils.d(TAG, "onResume() 启用前台分发");
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mTechLists);
}
}
@Override // 自动读取旧数据
protected void onPause() { readOldNfcData(mCurrentTag);
super.onPause(); }
LogUtils.d(TAG, "onPause() 关闭前台分发");
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
@Override /**
protected void onNewIntent(Intent intent) { * 读取卡片原有数据并显示(带时间)
super.onNewIntent(intent); */
LogUtils.d(TAG, "onNewIntent() 收到 NFC 卡片意图: " + intent.getAction()); private void readOldNfcData(Tag tag) {
mCurrentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); LogUtils.d(TAG, "readOldNfcData(tag=" + tag + ")");
Intent serviceIntent = new Intent(this, AutoNFCService.class); if (tag == null) {
serviceIntent.putExtras(intent); showToast("标签为空");
startService(serviceIntent); return;
}
updateStatus("卡片已靠近,数据解析中..."); Ndef ndef = Ndef.get(tag);
} if (ndef == null) {
showToast("不支持NDEF");
return;
}
// ========================= 写入逻辑 ========================= try {
public boolean writeNfc(String text) { ndef.connect();
LogUtils.d(TAG, "writeNfc() 写入文本: " + text); NdefMessage msg = ndef.getNdefMessage();
if (mCurrentTag == null) { if (msg == null) {
LogUtils.w(TAG, "writeNfc() 未检测到卡片,无法写入"); tvResult.setText("无旧数据");
updateStatus("请先靠近卡片"); ndef.close();
return false; return;
} }
if (text.isEmpty()) {
LogUtils.w(TAG, "writeNfc() 写入内容为空");
updateStatus("输入内容不能为空");
return false;
}
NdefRecord record = createTextRecord(text); NdefRecord[] records = msg.getRecords();
NdefMessage msg = new NdefMessage(new NdefRecord[] { record }); if (records != null && records.length > 0) {
byte[] payload = records[0].getPayload();
int langLen = payload[0] & 0x3F;
int start = 1 + langLen;
try { String content = new String(
Ndef ndef = Ndef.get(mCurrentTag); payload, start, payload.length - start,
if (ndef != null) { Charset.forName("UTF-8")
ndef.connect(); );
if (ndef.isWritable()) {
ndef.writeNdefMessage(msg);
ndef.close();
LogUtils.i(TAG, "writeNfc() 写入成功");
updateStatus("写入成功");
updateData(text);
NfcStateMonitor.notifyWriteSuccess();
return true;
}
} else {
NdefFormatable f = NdefFormatable.get(mCurrentTag);
if (f != null) {
f.connect();
f.format(msg);
f.close();
LogUtils.i(TAG, "writeNfc() 格式化并写入成功");
updateStatus("格式化并写入成功");
NfcStateMonitor.notifyWriteSuccess();
return true;
}
}
} catch (Exception e) {
LogUtils.e(TAG, "writeNfc() 写入异常: " + e.getMessage(), e);
updateStatus("写入失败:" + e.getMessage());
NfcStateMonitor.notifyWriteFail(e.getMessage());
}
return false;
}
// ========================= NDEF 构造 ========================= // 附加时间
private NdefRecord createTextRecord(String text) { String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date());
LogUtils.d(TAG, "createTextRecord() 构造 NDEF 文本记录"); String show = "读取时间:" + time + "\n\n内容\n" + content;
byte[] langBytes = "en".getBytes(Charset.forName("UTF-8")); tvResult.setText(show);
byte[] textBytes = text.getBytes(Charset.forName("UTF-8"));
byte[] payload = new byte[1 + langBytes.length + textBytes.length];
payload[0] = (byte) langBytes.length;
System.arraycopy(langBytes, 0, payload, 1, langBytes.length);
System.arraycopy(textBytes, 0, payload, 1 + langBytes.length, textBytes.length);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
}
// ========================= UI 更新 ========================= showToast("读取成功");
private void updateStatus(final String s) { }
runOnUiThread(new Runnable() { ndef.close();
@Override } catch (Exception e) {
public void run() { LogUtils.e(TAG, "读取失败", e);
tvStatus.setText("状态" + s); tvResult.setText("读取失败" + e.getMessage());
} showToast("读取失败");
}); }
} }
/**
* 写入按钮点击
*/
public void onWriteClick(View view) {
LogUtils.d(TAG, "onWriteClick()");
String text = etInput.getText().toString().trim();
if (text.isEmpty()) {
showToast("请输入内容");
return;
}
if (mCurrentTag == null) {
showToast("请先靠近卡片");
return;
}
writeNfc(mCurrentTag, text);
}
/**
* 写入NDEF
*/
private void writeNfc(Tag tag, String text) {
LogUtils.d(TAG, "writeNfc(text=" + text + ")");
tvStatus.setText("正在写入...");
try {
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
showToast("不支持NDEF");
tvStatus.setText("不支持NDEF");
return;
}
ndef.connect();
NdefRecord record = createTextRecord(text, true);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
ndef.writeNdefMessage(msg);
ndef.close();
tvStatus.setText("写入成功!");
showToast("写入成功");
// 写入后重新读取
readOldNfcData(tag);
} catch (Exception e) {
LogUtils.e(TAG, "写入失败", e);
tvStatus.setText("写入失败");
showToast("写入失败");
}
}
/**
* 创建文本记录
*/
private NdefRecord createTextRecord(String text, boolean isUtf8) {
byte[] langBytes = "en".getBytes(Charset.forName("US-ASCII"));
byte[] textBytes = text.getBytes(Charset.forName(isUtf8 ? "UTF-8" : "UTF-16"));
int status = isUtf8 ? 0 : 0x80;
status |= langBytes.length & 0x3F;
byte[] data = new byte[1 + langBytes.length + textBytes.length];
data[0] = (byte) status;
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void updateData(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvData.setText("内容:\n" + s);
}
});
}
} }

View File

@@ -0,0 +1,97 @@
package cc.winboll.studio.autonfc.nfc;
/*
* 源码说明与描述:
* NFC 透明代理 Activity用于在后台捕获 NFC 卡片事件并转发给 AutoNFCService
* 界面为 1 像素透明,不影响用户操作
*
* 作者:豆包&ZhanGSKen<zhangsken@qq.com>
* 创建时间2026-03-17 14:00:00
* 最后编辑时间2026-03-17 18:30:00
*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import cc.winboll.studio.libappbase.LogUtils;
public class NfcProxyActivity extends Activity {
private static final String TAG = "NfcProxyActivity";
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtils.d(TAG, "onCreate() -> 启动 NFC 透明代理");
// 设置为 1 像素透明窗口,用户不可见
Window window = getWindow();
window.setLayout(1, 1);
window.setBackgroundDrawableResource(android.R.color.transparent);
window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
);
// 初始化 NFC
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
Intent intent = new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
mPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
}
@Override
protected void onResume() {
super.onResume();
LogUtils.d(TAG, "onResume() -> 启用前台分发");
// 强制获取焦点,确保 enableForegroundDispatch 生效
getWindow().getDecorView().requestFocus();
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
0 // 临时允许获取焦点
);
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
// 恢复为不可聚焦,避免拦截用户操作
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
);
}
@Override
protected void onPause() {
super.onPause();
LogUtils.d(TAG, "onPause() -> 关闭前台分发");
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
LogUtils.d(TAG, "onNewIntent() -> 捕获到 NFC 卡片事件");
// 转发给 AutoNFCService 处理
Intent serviceIntent = new Intent(this, AutoNFCService.class);
serviceIntent.putExtras(intent);
startService(serviceIntent);
}
}

View File

@@ -1,16 +1,10 @@
package cc.winboll.studio.autonfc.nfc; package cc.winboll.studio.autonfc.nfc;
import android.nfc.NfcAdapter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/**
* @Author 豆包&ZhanGSKen<zhangsken@qq.com>
* @Date 2026/03/14 13:34
*/
public class NfcStateMonitor { public class NfcStateMonitor {
private static Map<String, OnNfcStateListener> sListenerMap = new HashMap<>();
private static Map<String, OnNfcStateListener> sListenerMap;
private static boolean sIsRunning = false; private static boolean sIsRunning = false;
public static void startMonitor() { public static void startMonitor() {
@@ -28,6 +22,7 @@ public class NfcStateMonitor {
} }
} }
// 你原来的方法名registerListener
public static void registerListener(String key, OnNfcStateListener listener) { public static void registerListener(String key, OnNfcStateListener listener) {
if (!sIsRunning || listener == null) return; if (!sIsRunning || listener == null) return;
sListenerMap.put(key, listener); sListenerMap.put(key, listener);
@@ -40,32 +35,44 @@ public class NfcStateMonitor {
public static void notifyNfcConnected() { public static void notifyNfcConnected() {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) l.onNfcConnected(); for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcConnected();
}
} }
public static void notifyNfcDisconnected() { public static void notifyNfcDisconnected() {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) l.onNfcDisconnected(); for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcDisconnected();
}
} }
public static void notifyReadSuccess(String data) { public static void notifyReadSuccess(String data) {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) l.onNfcReadSuccess(data); for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcReadSuccess(data);
}
} }
public static void notifyReadFail(String error) { public static void notifyReadFail(String error) {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) l.onNfcReadFail(error); for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcReadFail(error);
}
} }
public static void notifyWriteSuccess() { public static void notifyWriteSuccess() {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) l.onNfcWriteSuccess(); for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcWriteSuccess();
}
} }
public static void notifyWriteFail(String error) { public static void notifyWriteFail(String error) {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) l.onNfcWriteFail(error); for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcWriteFail(error);
}
} }
} }

View File

@@ -1,11 +1,7 @@
package cc.winboll.studio.autonfc.nfc; package cc.winboll.studio.autonfc.nfc;
/**
* @Author 豆包&ZhanGSKen<zhangsken@qq.com>
* @Date 2026/03/14 13:33
*/
public interface OnNfcStateListener { public interface OnNfcStateListener {
void onNfcConnected(); void onNfcConnected(); // 无参数!
void onNfcDisconnected(); void onNfcDisconnected();
void onNfcReadSuccess(String data); void onNfcReadSuccess(String data);
void onNfcReadFail(String error); void onNfcReadFail(String error);

View File

@@ -1,50 +1,46 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:orientation="vertical" android:orientation="vertical"
android:padding="16dp" android:padding="20dp">
android:gravity="top">
<!-- 状态显示 -->
<TextView <TextView
android:id="@+id/tv_nfc_status" android:id="@+id/tv_status"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="等待NFC卡片..."
android:textSize="16sp" android:textSize="16sp"
android:text="状态:未启动"/> android:textColor="#FF666666"/>
<!-- 输入要写入的内容 -->
<EditText <EditText
android:id="@+id/et_write_content" android:id="@+id/et_input"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:hint="输入要写入的NFC文本"
android:hint="请输入要写入NFC的文本" android:minHeight="50dp"
android:textSize="14sp"/> android:layout_marginTop="10dp"/>
<Button <Button
android:id="@+id/btn_read_nfc"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:text="写入NFC"
android:text="点击后靠近卡片读取数据"/> android:onClick="onWriteClick"/>
<Button
android:id="@+id/btn_write_nfc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="将输入框内容写入NFC"/>
<TextView <TextView
android:id="@+id/tv_nfc_data"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:layout_marginTop="20dp"
android:background="#f0f0f0" android:text="读取结果"/>
android:padding="10dp"
android:textSize="14sp" <TextView
android:text="数据显示区域"/> android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#f5f5f5"
android:gravity="center"/>
</LinearLayout> </LinearLayout>