Search code examples
androidkotlinnfc

NFC getNdefMessage returns null after tag writing on Android 13


I'm trying to write an app that writes a message/command to NFC tag and read NdefMessage back without disconnecting the field.

It works perfectly on all phones and Android OS version I have tried, except it doesn't work on any of the Android 13 phones, where reading NdefMessage after write returns null.

I will not post the whole code, it basically comes down to these few lines:

var message = NdefMessage(NdefRecord.createTextRecord("en", command))

ndef.connect()
ndef.writeNdefMessage(message)

val ndefMessage = ndef.getNdefMessage() --> returns null on Android 13, ndefMessage on all other OS versions

Would appreciate all the help I can get.

I have tried using foreground dispatch, reader mode with various EXTRA_READER_PRESENCE_CHECK_DELAY values, tried sleeping the thread, reading message in a loop with some sleep until it will maybe finally read it, using separate background thread for the whole operation, disabling other NFC apps, payment apps... nothing works.

It's obviously some kind of change with Android 13, because I tried also on a phone with Android 12, it worked as expected, upgraded the phone to Android 13, and doesn't work after that.

Note that tag is definitely correctly written, because it reads correctly if I add close/connect in between and read the tag with re-entering the field, or just writing the message and reading the tag in other NFC apps.


Solution

  • Resolved.

    Between write and subsequent read, it's necessary to close, get ndef again, and connect again:

    ndef.connect()
    ndef.writeNdefMessage(message)
    
    ndef.close()
    ndef = Ndef.get(tag)
    ndef.connect()
    
    val ndefMessage = ndef.getNdefMessage()