You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android屏幕熄灭时HCE的processCommandApdu无法触发问题

HCE配置问题及代码示例

Manifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc.hce" android:required="true"/>

<application
    android:allowBackup="true"
    android:dataExtractionRules="@xml/data_extraction_rules"
    android:fullBackupContent="@xml/backup_rules"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.NFCHCE"
    tools:targetApi="33">
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:theme="@style/Theme.NFCHCE">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".MyHostApduService"
        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>
</application>
</manifest>

apduservice.xml

<?xml version="1.0" encoding="utf-8"?>
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/app_name"
    android:requireDeviceUnlock="false">
    <aid-group android:description="@string/app_name"
        android:category="payment">
        <aid-filter android:name="A0000000041010"/>
    </aid-group>
</host-apdu-service>

MyHostApduService.kt

class MyHostApduService : HostApduService() {
    override fun processCommandApdu(commandApdu: ByteArray?, extras: Bundle?): ByteArray {
        Log.d("commandApdu Test", "commandApdu - $commandApdu")
        commandApdu?.forEach {
            Log.d("commandApdu Test", "connected - $it")
        }
        return byteArrayOf(0x90.toByte(), 0x00.toByte())
    }


    override fun onDeactivated(reason: Int) {
        Log.d("commandApdu Test", "onDeactivated reason: $reason")
    }
}

问题描述

根据Android官方文档,配置HCE时若设置android:requireDeviceUnlock="false",设备触碰NFC读卡器时应触发processCommandApdu方法。但实际测试发现该功能无法正常工作,仅当屏幕点亮时才能触发,不过应用从后台清除后仍可正常运行。测试设备为三星A32(Android 13)、小米12 Lite(Android 14)。

内容的提问来源于stack exchange,提问作者Bekzod Yusupov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:02:03