Android Studio扫描带AAR的NFC标签获取NDEF标签UID的intent-filter配置问题
解决方案
方案1:仅调整NDEF_DISCOVERED过滤规则
如果你使用的NFC卡片上已经写入了对应应用包名的AAR记录,不需要额外添加Text记录,仅删除原有intent-filter中限定text/plain类型的<data>节点即可,配置如下:
<intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
该配置会匹配所有携带你应用AAR的NDEF格式标签,无需额外的Text类型记录即可触发应用拉起,原有读取UID的逻辑不用修改即可正常运行。
方案2:兼容无NDEF记录的NFC卡片
如果你的卡片不需要写入任何NDEF内容(仅保留AAR即可),可以使用TECH_DISCOVERED过滤规则,配置步骤如下:
- 在AndroidManifest.xml的对应Activity节点下添加intent-filter和元数据配置:
<intent-filter> <action android:name="android.nfc.action.TECH_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/nfc_tech_filter" />
- 在项目的
res/xml目录下新建nfc_tech_filter.xml文件,添加常见NFC卡片技术类型的匹配规则:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <tech-list> <tech>android.nfc.tech.NfcA</tech> </tech-list> <tech-list> <tech>android.nfc.tech.NfcB</tech> </tech-list> <tech-list> <tech>android.nfc.tech.NfcF</tech> </tech-list> <tech-list> <tech>android.nfc.tech.NfcV</tech> </tech-list> </resources>
- 调整主Activity的UID读取逻辑,同时兼容两种触发动作:
override fun onResume() { super.onResume() intent?.let { currentIntent -> UIDLabel.text = currentIntent.action.orEmpty() val action = currentIntent.action if (NfcAdapter.ACTION_NDEF_DISCOVERED == action || NfcAdapter.ACTION_TECH_DISCOVERED == action) { val tag = currentIntent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG) tag?.let { UIDLabel.text = ByteUtils.bytesToHex(it.id) } } } }
前置检查
确保AndroidManifest.xml中已经添加了必要的NFC权限:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="false" />
内容的提问来源于stack exchange,提问作者Joseph Lewis
相关产品推荐
相关产品推荐

