简体   繁体   中英

Listen for HCE (Host-based Card Emulation) event

I have the need to launch my app every time the user begins an NFC transaction using Host-based Card Emulation (HCE).

I don't need to manage the interaction. I don't need any kind of data from the reader or the NFC emulator. I have no control on the apps that use the service. I just need to know if the phone came close to an NFC reader.

Is there an easy way like listen for a generic system event or notification without interfering with other apps?

No, Android does not send any notification like "hey, there is some app that has just been activated over HCE". Thus, you can't get such an event in your app. And specifically, it's not possibly to monitor if any existing HCE app (that's not under your control) on your device has been activated through HCE.

What you can do is to create your own HCE service (registered for your specific application AIDs). This HCE service could then launch an activity if it receives a transaction (also see How can I send message from HostApduService to an activity? ):

public class MyHostApduService extends HostApduService {
    @Override
    public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
        if ((apdu[1] == (byte)0xA4) && (apdu[2] == (byte)0x04)) {
            // SELECT by AID
            Intent intent = new Intent(this, MyActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            return new byte[]{ (byte)0x90, (byte)0x00 }
        } else {
            return new byte[]{ (byte)0x6D, (byte)0x00 }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM