NFC卡片读写功能调试完成。

This commit is contained in:
2026-03-14 14:10:45 +08:00
parent 94bfb3e878
commit 890ec9587c
5 changed files with 121 additions and 174 deletions

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle #Created by .winboll/winboll_app_build.gradle
#Sat Mar 14 05:50:51 GMT 2026 #Sat Mar 14 06:09:03 GMT 2026
stageCount=0 stageCount=0
libraryProject= libraryProject=
baseVersion=15.11 baseVersion=15.11
publishVersion=15.0.0 publishVersion=15.0.0
buildCount=4 buildCount=6
baseBetaVersion=15.0.1 baseBetaVersion=15.0.1

View File

@@ -14,35 +14,16 @@ import android.nfc.tech.NdefFormatable;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import java.io.IOException;
import java.nio.charset.Charset;
import cc.winboll.studio.autonfc.R; import cc.winboll.studio.autonfc.R;
import java.nio.charset.Charset;
/** /**
* @Author 豆包&ZhanGSKen<zhangsken@qq.com> * @Author 豆包&ZhanGSKen<zhangsken@qq.com>
* @Date 2026/03/14 13:35 * @Date 2026/03/14 13:35
*/ */
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.nio.charset.Charset;
public class NFCInterfaceActivity extends Activity { public class NFCInterfaceActivity extends Activity {
private NfcAdapter mNfcAdapter; private NfcAdapter mNfcAdapter;
@@ -50,16 +31,13 @@ public class NFCInterfaceActivity extends Activity {
private IntentFilter[] mIntentFilters; private IntentFilter[] mIntentFilters;
private String[][] mTechLists; private String[][] mTechLists;
// 调试UI
private TextView tvStatus; private TextView tvStatus;
private TextView tvData; private TextView tvData;
private Button btnWrite; private EditText etWriteContent;
private Button btnReadNfc; // 新增:主动读取按钮 private Button btnReadNfc;
private Button btnWriteNfc;
// 当前标签
private Tag mCurrentTag; private Tag mCurrentTag;
// 标记是否等待NFC读取
private boolean mIsWaitForRead = false; private boolean mIsWaitForRead = false;
@Override @Override
@@ -69,43 +47,34 @@ public class NFCInterfaceActivity extends Activity {
tvStatus = findViewById(R.id.tv_nfc_status); tvStatus = findViewById(R.id.tv_nfc_status);
tvData = findViewById(R.id.tv_nfc_data); tvData = findViewById(R.id.tv_nfc_data);
btnWrite = findViewById(R.id.btn_write_nfc); etWriteContent = findViewById(R.id.et_write_content);
btnReadNfc = findViewById(R.id.btn_read_nfc); // 绑定 btnReadNfc = findViewById(R.id.btn_read_nfc);
btnWriteNfc = findViewById(R.id.btn_write_nfc);
initNfc(); initNFC();
// 写入按钮
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
writeNfc("Test NFC Data Java7");
}
});
// ========== 新增:主动读取按钮点击 ==========
btnReadNfc.setOnClickListener(new View.OnClickListener() { btnReadNfc.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
startWaitForNfcRead(); startWaitForRead();
}
});
btnWriteNfc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = etWriteContent.getText().toString().trim();
writeNfc(content);
} }
}); });
} }
/** private void initNFC() {
* 开始等待NFC卡片靠近测试用
*/
public void startWaitForNfcRead() {
mIsWaitForRead = true;
updateUiStatus("请靠近NFC卡片即将自动读取...");
showToast("请靠近NFC卡片");
}
private void initNfc() {
NfcManager manager = (NfcManager) getSystemService(NFC_SERVICE); NfcManager manager = (NfcManager) getSystemService(NFC_SERVICE);
mNfcAdapter = manager.getDefaultAdapter(); mNfcAdapter = manager.getDefaultAdapter();
if (mNfcAdapter == null) { if (mNfcAdapter == null) {
showToast("设备不支持NFC"); updateStatus("设备不支持NFC");
return; return;
} }
@@ -121,29 +90,28 @@ public class NFCInterfaceActivity extends Activity {
mIntentFilters = new IntentFilter[]{filter}; mIntentFilters = new IntentFilter[]{filter};
mTechLists = new String[][]{{Ndef.class.getName()}, {NdefFormatable.class.getName()}}; mTechLists = new String[][]{{Ndef.class.getName()}, {NdefFormatable.class.getName()}};
updateStatus("NFC初始化完成");
}
public void startWaitForRead() {
mIsWaitForRead = true;
updateStatus("请靠近NFC卡片进行读取");
showToast("请靠近卡片");
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
NfcStateMonitor.startMonitor(); NfcStateMonitor.startMonitor();
enableForeground(); if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mTechLists);
}
} }
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
NfcStateMonitor.stopMonitor(); NfcStateMonitor.stopMonitor();
disableForeground();
}
private void enableForeground() {
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mTechLists);
}
}
private void disableForeground() {
if (mNfcAdapter != null) { if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this); mNfcAdapter.disableForegroundDispatch(this);
} }
@@ -159,22 +127,19 @@ public class NFCInterfaceActivity extends Activity {
|| NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
NfcStateMonitor.notifyNfcConnected(); NfcStateMonitor.notifyNfcConnected();
updateUiStatus("NFC卡片已靠近"); updateStatus("卡片已靠近");
mCurrentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); mCurrentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// ========== 新增:如果是等待读取,则自动读取 ==========
if (mIsWaitForRead) { if (mIsWaitForRead) {
mIsWaitForRead = false; mIsWaitForRead = false;
readNfc(intent); readNfcData(intent);
} }
} }
} }
// 公开读取方法 public void readNfcData(Intent intent) {
public void readNfc(Intent intent) {
if (intent == null) { if (intent == null) {
NfcStateMonitor.notifyReadFail("Intent 为空"); NfcStateMonitor.notifyReadFail("Intent为空");
return; return;
} }
@@ -186,7 +151,7 @@ public class NFCInterfaceActivity extends Activity {
Ndef ndef = Ndef.get(tag); Ndef ndef = Ndef.get(tag);
if (ndef == null) { if (ndef == null) {
NfcStateMonitor.notifyReadFail("不支持NDEF格式"); NfcStateMonitor.notifyReadFail("不支持NDEF");
return; return;
} }
@@ -194,33 +159,54 @@ public class NFCInterfaceActivity extends Activity {
ndef.connect(); ndef.connect();
NdefMessage msg = ndef.getNdefMessage(); NdefMessage msg = ndef.getNdefMessage();
if (msg == null) { if (msg == null) {
NfcStateMonitor.notifyReadFail("标签为空数据"); NfcStateMonitor.notifyReadFail("标签");
ndef.close(); ndef.close();
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(); // String data = new String(payload, 1, payload.length - 1, Charset.forName("UTF-8"));
String data = new String(payload, 1, payload.length - 1, Charset.forName("UTF-8")); // updateData(data);
// updateStatus("读取成功");
// NfcStateMonitor.notifyReadSuccess(data);
byte[] payload = records[0].getPayload();
if (payload.length > 0) {
int langCodeLength = payload[0] & 0x3F; // 标准NDEF Text格式语言码长度存在第0字节的低6位
int textStartIndex = 1 + langCodeLength;
if (textStartIndex < payload.length) {
String data = new String(payload, textStartIndex, payload.length - textStartIndex, Charset.forName("UTF-8"));
updateData(data);
updateStatus("读取成功");
NfcStateMonitor.notifyReadSuccess(data);
} else {
NfcStateMonitor.notifyReadFail("标签数据为空");
updateStatus("标签数据为空");
}
} else {
NfcStateMonitor.notifyReadFail("标签 payload 为空");
updateStatus("标签 payload 为空");
}
updateUiData(data);
updateUiStatus("读取成功");
NfcStateMonitor.notifyReadSuccess(data);
} }
ndef.close(); ndef.close();
} catch (Exception e) { } catch (Exception e) {
NfcStateMonitor.notifyReadFail(e.getMessage()); NfcStateMonitor.notifyReadFail(e.getMessage());
updateUiStatus("读取失败:" + e.getMessage()); updateStatus("读取失败:" + e.getMessage());
} }
} }
// 公开写入方法
public boolean writeNfc(String text) { public boolean writeNfc(String text) {
if (mCurrentTag == null) { if (mCurrentTag == null) {
NfcStateMonitor.notifyWriteFail("未检测到标签"); NfcStateMonitor.notifyWriteFail("未检测到卡片");
updateUiStatus("请先靠近卡片"); updateStatus("请先靠近卡片");
return false;
}
if (text.isEmpty()) {
NfcStateMonitor.notifyWriteFail("输入内容不能为空");
updateStatus("请输入写入内容");
return false; return false;
} }
@@ -234,40 +220,40 @@ public class NFCInterfaceActivity extends Activity {
if (ndef.isWritable()) { if (ndef.isWritable()) {
ndef.writeNdefMessage(msg); ndef.writeNdefMessage(msg);
ndef.close(); ndef.close();
updateStatus("写入成功");
updateData(text);
NfcStateMonitor.notifyWriteSuccess(); NfcStateMonitor.notifyWriteSuccess();
updateUiStatus("写入成功");
updateUiData(text);
return true; return true;
} }
} else { } else {
NdefFormatable f = NdefFormatable.get(mCurrentTag); NdefFormatable formatable = NdefFormatable.get(mCurrentTag);
if (f != null) { if (formatable != null) {
f.connect(); formatable.connect();
f.format(msg); formatable.format(msg);
f.close(); formatable.close();
updateStatus("格式化并写入成功");
NfcStateMonitor.notifyWriteSuccess(); NfcStateMonitor.notifyWriteSuccess();
updateUiStatus("格式化并写入成功");
return true; return true;
} }
} }
} catch (Exception e) { } catch (Exception e) {
NfcStateMonitor.notifyWriteFail(e.getMessage()); NfcStateMonitor.notifyWriteFail(e.getMessage());
updateUiStatus("写入失败:" + e.getMessage()); updateStatus("写入失败:" + e.getMessage());
} }
return false; return false;
} }
private NdefRecord createTextRecord(String text) { private NdefRecord createTextRecord(String text) {
byte[] lang = "en".getBytes(Charset.forName("UTF-8")); byte[] langBytes = "en".getBytes(Charset.forName("UTF-8"));
byte[] txt = text.getBytes(Charset.forName("UTF-8")); byte[] textBytes = text.getBytes(Charset.forName("UTF-8"));
byte[] payload = new byte[1 + lang.length + txt.length]; byte[] payload = new byte[1 + langBytes.length + textBytes.length];
payload[0] = (byte) lang.length; payload[0] = (byte) langBytes.length;
System.arraycopy(lang, 0, payload, 1, lang.length); System.arraycopy(langBytes, 0, payload, 1, langBytes.length);
System.arraycopy(txt, 0, payload, 1 + lang.length, txt.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); return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
} }
private void updateUiStatus(final String s) { private void updateStatus(final String s) {
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
@@ -276,11 +262,11 @@ public class NFCInterfaceActivity extends Activity {
}); });
} }
private void updateUiData(final String s) { private void updateData(final String s) {
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
tvData.setText("读取数据\n" + s); tvData.setText("读取/写入内容\n" + s);
} }
}); });
} }

View File

@@ -10,101 +10,62 @@ import java.util.Map;
*/ */
public class NfcStateMonitor { public class NfcStateMonitor {
// 保存所有监听实例 private static Map<String, OnNfcStateListener> sListenerMap;
private static Map<String, OnNfcStateListener> sListenerMap = new HashMap<>();
// 全局 NFC 状态标记
private static boolean sIsRunning = false; private static boolean sIsRunning = false;
// ============= 公开静态:启动监听 =============
public static void startMonitor() { public static void startMonitor() {
if (sIsRunning) return; if (sIsRunning) return;
// 初始化 Map
sListenerMap = new HashMap<>(); sListenerMap = new HashMap<>();
sIsRunning = true; sIsRunning = true;
// 回调所有监听器:监控已启动
notifyMonitorStarted();
} }
// ============= 公开静态:停止监听 =============
public static void stopMonitor() { public static void stopMonitor() {
if (!sIsRunning) return; if (!sIsRunning) return;
sIsRunning = false; sIsRunning = false;
// 清空所有监听器
if (sListenerMap != null) { if (sListenerMap != null) {
sListenerMap.clear(); sListenerMap.clear();
sListenerMap = null; sListenerMap = null;
} }
} }
// ============= 公开静态:注册监听 =============
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);
} }
// ============= 公开静态:移除监听 =============
public static void unregisterListener(String key) { public static void unregisterListener(String key) {
if (!sIsRunning || key == null) return; if (!sIsRunning || key == null) return;
sListenerMap.remove(key); sListenerMap.remove(key);
} }
// ============= 下面是内部回调分发 =============
public static void notifyNfcConnected() { public static void notifyNfcConnected() {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) { for (OnNfcStateListener l : sListenerMap.values()) l.onNfcConnected();
l.onNfcConnected();
}
} }
public static void notifyNfcDisconnected() { public static void notifyNfcDisconnected() {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) { for (OnNfcStateListener l : sListenerMap.values()) l.onNfcDisconnected();
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()) { for (OnNfcStateListener l : sListenerMap.values()) l.onNfcReadSuccess(data);
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()) { for (OnNfcStateListener l : sListenerMap.values()) l.onNfcReadFail(error);
l.onNfcReadFail(error);
}
} }
public static void notifyWriteSuccess() { public static void notifyWriteSuccess() {
if (!sIsRunning) return; if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) { for (OnNfcStateListener l : sListenerMap.values()) l.onNfcWriteSuccess();
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()) { for (OnNfcStateListener l : sListenerMap.values()) l.onNfcWriteFail(error);
l.onNfcWriteFail(error);
}
}
private static void notifyMonitorStarted() {
if (!sIsRunning) return;
for (OnNfcStateListener l : sListenerMap.values()) {
l.onNfcConnected(); // 仅示意启动
}
}
public static boolean isMonitorRunning() {
return sIsRunning;
} }
} }

View File

@@ -5,21 +5,11 @@ package cc.winboll.studio.autonfc.nfc;
* @Date 2026/03/14 13:33 * @Date 2026/03/14 13:33
*/ */
public interface OnNfcStateListener { public interface OnNfcStateListener {
// NFC 已连接(卡片靠近)
void onNfcConnected(); void onNfcConnected();
// NFC 已断开(卡片移开)
void onNfcDisconnected(); void onNfcDisconnected();
// 读取成功
void onNfcReadSuccess(String data); void onNfcReadSuccess(String data);
// 读取失败
void onNfcReadFail(String error); void onNfcReadFail(String error);
// 写入成功
void onNfcWriteSuccess(); void onNfcWriteSuccess();
// 写入失败
void onNfcWriteFail(String error); void onNfcWriteFail(String error);
} }

View File

@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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="16dp"
android:gravity="top">
<TextView <TextView
android:id="@+id/tv_nfc_status" android:id="@+id/tv_nfc_status"
@@ -13,28 +13,38 @@
android:textSize="16sp" android:textSize="16sp"
android:text="状态:未启动"/> android:text="状态:未启动"/>
<!-- 输入要写入的内容 -->
<EditText
android:id="@+id/et_write_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="请输入要写入NFC的文本"
android:textSize="14sp"/>
<Button
android:id="@+id/btn_read_nfc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="点击后靠近卡片读取数据"/>
<Button <Button
android:id="@+id/btn_write_nfc" android:id="@+id/btn_write_nfc"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="写入测试数据"/> android:layout_marginTop="10dp"
android:text="将输入框内容写入NFC"/>
<!-- 新增主动读取NFC按钮 -->
<Button
android:id="@+id/btn_read_nfc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击后靠近NFC卡片读取数据"/>
<TextView <TextView
android:id="@+id/tv_nfc_data" 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:background="#f0f0f0" android:background="#f0f0f0"
android:padding="10dp" android:padding="10dp"
android:layout_marginTop="10dp" android:textSize="14sp"
android:text="数据"/> android:text="数据显示区域"/>
</LinearLayout> </LinearLayout>