I develop an Android app to read/write on contactless smart cards through NFC. I need to detect when the card is pulled out of range. I tried to use
NFCAdapter.OnTagRemovedListener{
card_connected2.visibility = View.VISIBLE
card_connectedgreen.visibility = View.GONE
Toast.makeText(this@InquiryActivity, "card is disconnected", Toast.LENGTH_LONG).show()
}
but this seems wrong and does not work. I also read about NfcAdapter.ignore(), but I can't find any example about how to use it. How can I get the above callback to work?
The OnTagRemovedListener interface is used to specify the callback for the NfcAdapter.ignore() method. Consequently, you need to call ignore() with the desired callback. E.g., if you want to execute the code above, with a debounce timeout of 1000 ms, you could use something like this:
// nfcAdapter: your instance of the NfcAdapter
// tag: the tag handle that you obtained from the NFC intent or the onTagDetected() callback
nfcAdapter.ignore(tag, 1000, NfcAdapter.OnTagRemovedListener {
card_connected2.visibility = View.VISIBLE
card_connectedgreen.visibility = View.GONE
Toast.makeText(this@InquiryActivity, "card is disconnected", Toast.LENGTH_LONG).show()
}, Handler(Looper.getMainLooper()))
Note that nfcAdapter and tag need to be defined accordingly. The callback function will be invoked on the main (UI) thread.