NfcApduService

abstract class NfcApduService

Base class for NFC APDU services orchestrated by NfcApduRouter.

Incoming CommandApdus and NfcDeactivationReason events received via receiveCommandApdu and deactivate are sequentially dispatched on an internal coroutine running on Dispatchers.Default to processCommandApdu and processDeactivated.

Subclasses are expected to override:

  • processCommandApdu: to handle each incoming CommandApdu and return the corresponding ResponseApdu. Note that NfcApduRouter forwards the initial SELECT APPLICATION command itself to the matched service, so implementations are expected to check CommandApdu.isApplicationSelect in processCommandApdu (both to return the SELECT APPLICATION response and to reset per-tap state if a new SELECT APPLICATION arrives mid-field).

  • processDeactivated: to clean up per-tap engagement or session state when the NFC link is deactivated or another application is selected.

  • start / stop (optional): to perform service lifecycle setup or teardown (subclasses must call super.start() / super.stop()). Note that applications must not make assumptions about when start and stop are called relative to NFC taps: on Android, the system's HostEmulationManager may bind the underlying HostApduService eagerly (for example when CardEmulation.setPreferredService() is called by a foreground activity or for a default payment service) and keep a single instance alive across zero, one, or many NFC taps, or it may bind on-demand when a SELECT AID APDU arrives and unbind (onDestroy() ->stop) immediately upon NFC link loss while a BLE or multi-tap presentment transaction is still in progress. Per-tap state should therefore be managed via processCommandApdu and processDeactivated rather than start and stop.

Inheritors

Constructors

Link copied to clipboard
constructor()

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard
protected val serviceScope: CoroutineScope

CoroutineScope tied to the lifecycle of this service (cancelled in stop).

Functions

Link copied to clipboard

Signals that the NFC link has been deactivated.

Link copied to clipboard
protected abstract suspend fun processCommandApdu(commandApdu: CommandApdu): ResponseApdu

Processes a CommandApdu sequentially on the service's background coroutine.

Link copied to clipboard
protected open suspend fun processDeactivated(reason: NfcDeactivationReason)

Processes a deactivation event sequentially on the service's background coroutine.

Link copied to clipboard

Enqueues an incoming CommandApdu for sequential processing by processCommandApdu.

Link copied to clipboard
open fun start()

Starts the service and its internal APDU dispatch coroutine.

Link copied to clipboard
open fun stop()

Stops the service and cancels its internal APDU dispatch coroutine.