Skip to content
Muhammed Ali
Kocabey

Why NFC Reads Fail on Android (and How to Recover)

Most NFC read failures on Android don't come from parsing bugs. They come from the radio link: the chip and the phone's antenna have to stay coupled for the whole exchange, and when the coupling breaks in the middle of a command, that command fails and Android usually reports TagLostException. Once you accept that, many "works on my phone, fails on theirs" reports make more sense, and the fix is usually better recovery and better guidance rather than a new reading strategy.

This post builds on reading an eID chip on Android, which covers the full read and verification flow. Here I focus on the part that goes wrong: why reads fail, and how to recover without breaking the secure channel.

Where a read can fail

A read can fail at three different points, and it pays to keep them apart in your code and your logs:

  • Discovery and connect. The tag is detected, but IsoDep.get(tag) returns null (the card isn't ISO-DEP) or connect() throws before you send anything. The phone never coupled properly with the chip.
  • Mid-read. Access control is done, files are coming in, and a transceive call throws. The phone coupled and then lost the chip.
  • Access control or verification. The link held, but the chip rejected the access data (wrong MRZ or CAN), or everything was read and a verification step such as Passive Authentication failed.

These need different messages and different fixes, so I model them explicitly instead of returning one "read failed" boolean:

sealed interface ReadFailure {
    data object NotIsoDep : ReadFailure          // IsoDep.get() returned null
    data object ConnectFailed : ReadFailure      // connect() threw
    data object CardLost : ReadFailure           // TagLostException during the read
    data object IoError : ReadFailure            // other IOException: cancel, link error
    data object AccessDenied : ReadFailure       // BAC/PACE rejected the MRZ or CAN
    data object VerificationFailed : ReadFailure // data read, but PA/AA/CA check failed
}

Access control has failure modes of its own; I go through the BAC and PACE handshakes in understanding eID access control.

Why the field drops

When the same card and the same phone fail intermittently, the cause is usually physical:

  • The antenna is somewhere different on every phone. Near the top of the back, around the camera, or lower down. Users don't know where it is, so they hold the card over the wrong spot and get weak coupling or none.
  • Cases and distance weaken the field. A thick case, a wallet case with metal in it, or a card held a few millimetres too far away can be enough. At near-field distances, a small gap costs a lot of signal.
  • The chip runs on the field. A contactless chip has no battery; it draws power from the reader's field. Cryptographic operations need more power and take longer, so a marginal field is more likely to fail during access control or Chip Authentication than during a simple file read.
  • Users move. They lift the phone to look at the screen, shift the card when a spinner appears, or can't hold still for the few seconds a full read takes. DG2 (the face image) is usually the largest file, so its read stays exposed to movement the longest.

Logical failures exist too: a wrong key, an unsupported command, a bug in your parser. They tend to fail the same way at the same step every time. So intermittent failures are a good reason to look at the field first, though on their own they don't prove it.

Reader mode instead of foreground dispatch

With foreground dispatch, the platform discovers the tag, runs its usual dispatch (including an NDEF check), plays the discovery sound, and hands you an intent. Card emulation stays active in the meantime. enableReaderMode puts the NFC controller in reader-only mode while your activity is in the foreground: card emulation is off, and you get the Tag directly in a callback. For an eID read, that is the better fit.

import android.app.Activity
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Bundle

class EidReaderMode(
    private val activity: Activity,
    private val onTag: (Tag) -> Unit,
) {
    private val adapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(activity)

    // Call from onResume(); reader mode is tied to the foreground activity.
    fun enable() {
        val options = Bundle().apply {
            putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250)
        }
        adapter?.enableReaderMode(
            activity,
            { tag -> onTag(tag) },
            NfcAdapter.FLAG_READER_NFC_A or
                NfcAdapter.FLAG_READER_NFC_B or
                NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK or
                NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
            options,
        )
    }

    // Call from onPause().
    fun disable() {
        adapter?.disableReaderMode(activity)
    }
}

What the flags do:

  • FLAG_READER_NFC_A and FLAG_READER_NFC_B limit polling to the two technologies identity documents use, so the controller doesn't spend time polling for others.
  • FLAG_READER_SKIP_NDEF_CHECK stops the platform from probing the card for NDEF. An eID chip has nothing to offer there, and skipping the probe means no extra commands reach the chip before yours.
  • FLAG_READER_NO_PLATFORM_SOUNDS turns off the discovery beep. This one is about UX: the beep plays when the card is detected, not when the read is done, and many users take it as a signal to pull the card away. Play your own sound or vibration when the read actually finishes.

EXTRA_READER_PRESENCE_CHECK_DELAY sets how often the platform checks that an idle tag is still there. The reference doesn't state a unit; AOSP treats the value as milliseconds and uses 125 when you don't set it. A longer delay means fewer presence-check frames between your commands, which some chip and controller combinations handle better. Too long, and you notice a removed card later. Treat 250 as a starting point and measure on your target devices.

The reference doesn't say which thread the callback runs on. In AOSP it arrives on a binder thread, not the main thread, so you can run the read there or hand it to a background dispatcher. Either way, connect() and transceive() block and must never run on the main thread.

IsoDep: timeout and APDU size

import android.nfc.Tag
import android.nfc.tech.IsoDep
import android.util.Log

const val ISO_DEP_TIMEOUT_MS = 5_000

fun openIsoDep(tag: Tag): IsoDep? {
    val isoDep = IsoDep.get(tag) ?: return null
    isoDep.connect()
    // On-chip crypto (PACE, Chip Authentication, Active Authentication) can be slow.
    isoDep.timeout = ISO_DEP_TIMEOUT_MS
    Log.d(
        "EidReader",
        "maxTransceiveLength=${isoDep.maxTransceiveLength}, " +
            "extendedLength=${isoDep.isExtendedLengthApduSupported}",
    )
    return isoDep
}

setTimeout sets the transceive timeout in milliseconds, and close() resets it to the default. So set it after every connect(), not once per app run. Also note what an expired timeout looks like: in AOSP's NCI stack, a response that doesn't arrive in time is reported as a lost tag, so you get TagLostException. A timeout that is too short for on-chip crypto therefore looks exactly like a user who moved the card. If CardLost keeps showing up at the same step, for example during Chip Authentication, check the timeout first.

For APDU size, don't hard-code a frame length. A short APDU carries at most 255 bytes of command data (261 bytes in total). Extended-length APDUs allow far more, but only if the phone and the chip both support them. isExtendedLengthApduSupported covers the phone side and maxTransceiveLength tells you the most you can send in one transceive. You don't need to split frames yourself; the platform fragments at the ISO-DEP layer. With Secure Messaging, the response also carries padding and a MAC, so readers usually ask for blocks a bit smaller than the raw maximum when they use READ BINARY.

What TagLostException tells you

TagLostException is a subclass of IOException. transceive throws it when the tag leaves the field. Three practical consequences:

  1. The old Tag is finished. The IsoDep reference says a SecurityException can be thrown if the tag object is reused after the tag has left the field. When the card comes back, reader mode delivers a new Tag through the callback, and that is the one you work with.
  2. Assume the chip has reset. A card that left the field lost power. The selected application, the Secure Messaging keys and the send sequence counter (SSC) are gone.
  3. Don't depend on the exact exception type. Depending on the device and the moment the card leaves, removal can also surface as a plain IOException, and as noted above, a timeout can surface as TagLostException. Your recovery should handle both.

This rules out the tempting "catch, reconnect, resend the same APDU" loop. Inside a BAC or PACE session, a resent command has no session left to belong to: it was encrypted and MACed with session keys and an SSC value that the reset chip no longer has. ICAO Doc 9303 Part 11, §9.8 also requires the chip to abort Secure Messaging and delete the session keys on any Secure Messaging error, and on any plain APDU sent mid-session. One stray unprotected "is the card still there?" command ends the session as well.

Retrying a single command on the same connection only makes sense for unprotected traffic, such as the application SELECT before access control, and only when the tag wasn't lost.

Recover at the session level

The safe unit of retry is the whole session, not the APDU. Keep reader mode on after a failure, wait for the next Tag, open a new connection, authenticate again, and continue with the files you haven't finished. In the code below, AccessKey, DataGroup, openSecureChannel, readFile and EidAuthException stand in for your own BAC/PACE and file-reading code:

import android.nfc.Tag
import android.nfc.TagLostException
import android.nfc.tech.IsoDep
import java.io.IOException

sealed interface SessionResult {
    data class Done(val files: Map<DataGroup, ByteArray>) : SessionResult
    data class TryAgain(val failure: ReadFailure) : SessionResult
    data class GiveUp(val failure: ReadFailure) : SessionResult
}

class EidReadSession(
    private val accessKey: AccessKey, // derived from the MRZ or the CAN
    private val groups: List<DataGroup>,
    private val maxAttempts: Int = 3,
) {
    private val completed = linkedMapOf<DataGroup, ByteArray>()
    private var attempts = 0

    // Call for every Tag that reader mode delivers, one at a time, off the main thread.
    fun run(tag: Tag): SessionResult {
        attempts++
        val isoDep = IsoDep.get(tag)
            ?: return SessionResult.GiveUp(ReadFailure.NotIsoDep)
        var connected = false
        try {
            isoDep.connect()
            connected = true
            isoDep.timeout = ISO_DEP_TIMEOUT_MS
            // New Tag, new chip session: authenticate from scratch
            // (BAC or PACE, then Chip Authentication if you use it).
            val channel = openSecureChannel(isoDep, accessKey)
            for (group in groups) {
                if (group !in completed) {
                    // A partially read file is dropped and read again in full.
                    completed[group] = channel.readFile(group)
                }
            }
            return SessionResult.Done(completed.toMap())
        } catch (e: EidAuthException) {
            // A wrong MRZ or CAN won't get better by retrying.
            return SessionResult.GiveUp(ReadFailure.AccessDenied)
        } catch (e: TagLostException) {
            return retryOrGiveUp(ReadFailure.CardLost)
        } catch (e: IOException) {
            return retryOrGiveUp(
                if (connected) ReadFailure.IoError else ReadFailure.ConnectFailed,
            )
        } finally {
            runCatching { isoDep.close() }
        }
    }

    private fun retryOrGiveUp(failure: ReadFailure): SessionResult =
        if (attempts < maxAttempts) {
            SessionResult.TryAgain(failure)
        } else {
            SessionResult.GiveUp(failure)
        }
}

A few details that matter here:

  • No sleep, no busy loop. The next attempt starts when the user brings the card back and reader mode delivers a new Tag. On TryAgain you update the UI and wait.
  • Finished files are kept. Each one was read whole, with every response MAC-checked under Secure Messaging. You still verify every data group hash against the SOD during Passive Authentication, so a corrupted file would be caught there anyway. Picking up an interrupted file at its last offset is possible, because the file contents don't change, but restarting that one file is simpler and costs little.
  • A different card can't slip in. The BAC/PACE key is derived from this document's MRZ or CAN. If the user presents another card on the retry, authentication fails instead of that card's data mixing with yours.
  • The attempt limit is there for the user. After a few lost connections another retry rarely helps; show clearer instructions instead.
  • Cancellation is built in. If the user taps "Cancel" during a read, call close() from another thread. A blocked transceive then returns with an IOException.

Guiding the user

Code can't fix a card held over the wrong spot, so the screen has to do part of the work:

  • Tell them where to hold the card, and to keep it still. If you know the antenna position for common devices, show it. On Android 14 (API 34) and later, NfcAdapter.getNfcAntennaInfo() can report antenna positions, but it may return null, so treat it as a hint. Otherwise, ask the user to slide the card slowly over the back of the phone and hold it once the read starts.
  • Show progress while reading. "Reading, keep holding" with a progress indicator per data group stops people from lifting the phone to check.
  • Signal the end yourself. With platform sounds off, a sound or vibration when the read completes tells the user when it's safe to move.
  • Explain failures in plain words. "Connection lost. Hold the card still in the same spot" is actionable; "Read failed" isn't.
  • Check that NFC is on before you start. If NfcAdapter.isEnabled() is false, send the user to Settings.ACTION_NFC_SETTINGS instead of waiting for a tag that will never arrive.

Each failure type maps to its own message:

fun ReadFailure.userMessage(): String = when (this) {
    ReadFailure.NotIsoDep -> "This card can't be read. Use your ID card or passport."
    ReadFailure.ConnectFailed -> "Couldn't reach the chip. Slide the card slowly over the back of the phone."
    ReadFailure.CardLost -> "Connection lost. Hold the card still in the same spot until the read finishes."
    ReadFailure.IoError -> "The chip stopped responding. Take the card away and hold it again."
    ReadFailure.AccessDenied -> "The chip rejected the access data. Check the details you entered."
    ReadFailure.VerificationFailed -> "The document was read but couldn't be verified."
}

In production these strings go in resources, of course. The idea is the same one behind SecureCheck: a result that says why something failed is more useful than a single pass/fail flag.

Frequently asked questions

Why do NFC reads fail on Android?
Mostly for physical reasons: the antenna is in a different spot on every phone, cases and distance weaken the field, the chip runs on power drawn from that field, and users move the phone mid-read. Long reads such as the DG2 face image are the most exposed to movement.
What does TagLostException mean and how should I recover from it?
It is an IOException subclass that transceive throws when the tag leaves the field. Treat the old Tag as unusable and assume the chip has reset. Keep reader mode on, wait for a new Tag, open a new session, keep the files you already finished and stop after a few attempts.
Why do I have to set the IsoDep timeout on every connection?
close() resets the timeout to its default, and every new Tag gives you a new IsoDep object. The default can be too short for on-chip crypto, and on AOSP's NCI stack an expired timeout is reported as TagLostException, so it looks just like a card that was moved away.
Can I resend a BAC or PACE protected APDU after the field drops?
No. The session keys and the send sequence counter belong to the session, and a chip that lost power has forgotten them. Discard the channel, wait for the card again, and run BAC or PACE (and Chip Authentication, if you use it) from the start.

WORK TOGETHER

Let’s start with a good problem.

Looking for an Android engineer for your team, or someone to think through a technical problem with? Let’s talk.

Book a 30-minute conversation[email protected]All contact and podcast links