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
#Sat Mar 14 05:50:51 GMT 2026
#Sat Mar 14 06:09:03 GMT 2026
stageCount=0
libraryProject=
baseVersion=15.11
publishVersion=15.0.0
buildCount=4
buildCount=6
baseBetaVersion=15.0.1

View File

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

View File

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

View File

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

View File

@@ -1,10 +1,10 @@
<?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_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
android:padding="16dp"
android:gravity="top">
<TextView
android:id="@+id/tv_nfc_status"
@@ -13,28 +13,38 @@
android:textSize="16sp"
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
android:id="@+id/btn_write_nfc"
android:layout_width="match_parent"
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
android:id="@+id/tv_nfc_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#f0f0f0"
android:padding="10dp"
android:layout_marginTop="10dp"
android:text="数据"/>
android:textSize="14sp"
android:text="数据显示区域"/>
</LinearLayout>