Ionic Angular模拟Mifare NFC标签:HCE回调未触发求助
解决HCE模拟Mifare Ultralight卡时registerCommandCallback未触发的问题
以下是几个关键排查方向:
核对AID与读卡器的指令逻辑
你当前代码用的是F222222222这类测试AID,但Mifare Ultralight属于ISO 14443A标准的标签,和HCE模拟的ISO 7816-4智能卡逻辑不同。读卡器可能在尝试读取Ultralight的UID、执行Mifare专属指令,而非发送SELECT APDU。需要确认读卡器是否支持ISO 7816-4的HCE卡,或者调整代码响应Ultralight的特定指令(比如读取UID的00B0000004指令)。验证HCE服务的注册配置
确保Cordova项目的Android配置正确:- 在
AndroidManifest.xml中添加HCE服务的元数据配置:
<service android:name="com.chariotsolutions.nfc.plugin.HceService" android:exported="true" android:permission="android.permission.BIND_NFC_SERVICE"> <intent-filter> <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/> </intent-filter> <meta-data android:name="android.nfc.cardemulation.host_apdu_service" android:resource="@xml/apduservice"/> </service>- 在
res/xml/apduservice.xml中声明要模拟的AID:
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android" android:requireDeviceUnlock="false"> <aid-group android:category="other"> <aid-filter android:name="F222222222"/> <!-- 如果需要模拟Ultralight相关指令,可能需要添加对应AID或调整逻辑 --> </aid-group> </host-apdu-service>AID未正确注册的话,系统不会将读卡器指令转发给应用。
- 在
确认设备HCE兼容性与状态
确保设备运行Android 4.4(API 19)及以上版本,NFC功能已开启。部分设备需要在系统设置中指定你的应用为对应AID的默认HCE处理服务,或者要求应用处于前台才能接收指令。调整代码响应Mifare指令
如果读卡器发送的是Mifare Ultralight指令,当前代码不会触发匹配。可以修改回调逻辑,比如响应读取UID的指令:hce.registerCommandCallback((command) => { const commandAsBytes = new Uint8Array(command); const commandAsString = hce.util.byteArrayToHexString(commandAsBytes).toLowerCase(); // 响应Mifare Ultralight读取UID的指令 const READ_UID_CMD = '00b0000004'; const SELECT_OK_SW = '9000'; if (commandAsString === READ_UID_CMD) { // 替换为你需要的指定ID(比如16进制的UID) const targetUid = 'A1B2C3D4'; const uidBytes = hce.util.hexStringToByteArray(targetUid); const response = hce.util.concatenateBuffers(uidBytes, hce.util.hexStringToByteArray(SELECT_OK_SW)); hce.sendResponse(response); } else { hce.sendResponse(hce.util.hexStringToByteArray('9000')); } });检查应用权限
确保AndroidManifest.xml中已添加NFC权限:<uses-permission android:name="android.permission.NFC"/> <uses-feature android:name="android.hardware.nfc" android:required="true"/>
内容的提问来源于stack exchange,提问作者Baumi
相关产品推荐
相关产品推荐

