NFC应用nfcAdapter.setNdefPushMessage消息收发失败问题排查求助
NFC消息收发问题排查与修复
一、代码中遗漏的关键配置与逻辑
1. 发送端Manifest缺失NFC权限与功能声明
发送端应用需声明NFC权限才能正常调用NFC接口,在<manifest>标签内添加:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="true" />
2. 接收端Manifest缺少NFC Intent Filter
系统需要通过Intent Filter识别接收端可处理NFC NDEF消息,在接收端MainActivity的<activity>标签内添加匹配文本类型的过滤规则:
<intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter>
3. 接收端未处理启动时的NFC Intent
若接收端是被NFC消息触发启动的,onCreate中需处理初始Intent。修改接收端MainActivity,统一Intent处理逻辑:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handleNfcIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleNfcIntent(intent); } private void handleNfcIntent(Intent intent) { TextView messageView = findViewById(R.id.messageView); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMessages != null && rawMessages.length > 0) { NdefMessage ndefMessage = (NdefMessage) rawMessages[0]; NdefRecord record = ndefMessage.getRecords()[0]; try { // 解析文本记录:payload第一个字节为状态位,后续为UTF-8文本 String textContent = new String(record.getPayload(), 1, record.getPayload().length - 1, "UTF-8"); messageView.setText(textContent); } catch (UnsupportedEncodingException e) { messageView.setText("消息解析失败"); e.printStackTrace(); } } } }
4. 接收端NDEF消息解析逻辑错误
原代码直接调用NdefMessage.toString()无法获取实际文本内容,需解析NdefRecord的payload结构,如上述代码中处理文本类型记录的方式。
二、调试方法
- 检查设备NFC状态:确保两台设备均开启NFC功能,Android 10及以上需启用「附近共享」(替代旧版Android Beam)。
- 系统日志排查:使用
adb logcat -s NfcService查看NFC服务日志,确认系统是否检测到NFC交互,以及Intent是否正确发送到接收端应用。 - 验证发送端消息:在发送端
sendMessage方法中添加日志,确认NDEF消息创建正常:Log.d("NFCSender", "创建的NDEF消息:" + ndefMessage); - 模拟Intent测试:用adb命令模拟发送NDEF Intent,验证接收端是否响应:
adb shell am start -n com.joyride.nfc_customer/.MainActivity -a android.nfc.action.NDEF_DISCOVERED -t text/plain
内容的提问来源于stack exchange,提问作者Yoav
相关产品推荐
相关产品推荐

