Home > Net >  Android: enableReaderMode - ReaderCallback not invoked
Android: enableReaderMode - ReaderCallback not invoked

Time:06-16

I've a problem with the NFC reader mode in android. I can enable the reader mode, but the onTagDiscovered callback is never invoked. The phone recognizes the tag, it vibrates shortly.

Here my code:

try {

    val nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    if (nfcAdapter == null) {
        Toast.makeText(this, "No NFC module :-(", Toast.LENGTH_SHORT).show();

    } else if (!nfcAdapter.isEnabled) {
        Toast.makeText(this, "NFC not enabled :-(", Toast.LENGTH_SHORT).show();

    } else {
        val options = Bundle()
        options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 5000)

        nfcAdapter.enableReaderMode(
            this,
            NfcAdapter.ReaderCallback() {
                fun onTagDiscovered(tag: Tag) {
                    Log.println(Log.DEBUG, null, "Discovered!");
                }
            },
            NfcAdapter.FLAG_READER_NFC_A or NfcAdapter.FLAG_READER_NFC_B or NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
            options
        );

        Log.println(Log.DEBUG, null, "Reader Mode");

    }
} catch (e: Exception) {
    Log.println(Log.ERROR, null, e.toString());
}

Thanks for your help!

CodePudding user response:

Updated

The problem is with scope of the callback

I've not tried to invoke the callback it in this manner I normally implement it in the Activity scope, I don't know if that is causing a problem also

This has been tested now and defining the Callback method as part of the call to nfcAdapter.enableReaderMode does not work, the Interface should be implemented in the Activity scope

e.g.

class MainActivity : NfcAdapter.ReaderCallback, AppCompatActivity() {
  override fun onTagDiscovered(tag: Tag) {
                    Log.println(Log.DEBUG, null, "Discovered!");
                }

then

nfcAdapter.enableReaderMode(
            this,
            this,
            NfcAdapter.FLAG_READER_NFC_A or 
            NfcAdapter.FLAG_READER_NFC_B or 
            NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
            options
        );
  • Related