Search code examples
androidmultithreadingnfcsmartcard-readerhce

Android multithreading in HostApduService (NFC)


I use the processCommandApdu() method in a subclass of HostApduService to react on NFC commands. This method gets called on the Android main thread. These commands should be processed and sent over the NFC channel sequentially. Therefore, I want to process them synchronously.

Is there any good way to enforce sequential order without blocking inside of the processCommandApdu() method?


Solution

  • There is no need for you to synchronize command processing. Sequencing is inherent to the ISO/IEC 14443 protocol: A command exchange always consists of a command sent by the reader to the card (HCE device) and a response sent by the card (HCE) device to the reader. A reader won't issue a new command before the response to the previous command was received. If a command times out before a response is received by the reader, the reader will interpret this as if the connection to the card was lost.

    Therefore, unless the reader resets/drops the connection, you won't receive a new command before you sent a response to the previous command (either through returning no-null from processCommandApdu()) or by calling sendResponseApdu()).