I am working with NFC smart card. Typically it is 2-8 commands in a row to get some data, perform some actions and get result.
.
So I call NFC activity from fragment using registerForActivityResult() In this NFC Activity I am calling nfcAdapter.enableReaderMode() in onResume() and nfcAdapter.disableReaderMode() in onPause
So after sending a bunch of commands Activity return result to fragment through setResult().
.
Problem is: Sometimes happens that NFC stops discovering tag.
.
Flow is next:
Fragment -> NFCActivity -> tap card to phone -> TAG discovered -> send 5 APDU commands to card and get result -> return result to Fragment to handle
-> then Fragment opens NFCActivity again to send another commands list -> tap card to phone -> NFC TAG is not discovering for 5-20 seconds. (So I need to wait like 10 seconds and tap card again.
.
What can be the problem? Maybe I use tag / isoDep in wrong way? Or maybe NFC can't be used to many times for short period of time?
Thank you!
Code:
// in activity onResume()
fun enableReaderMode(activity: NFCCryptoHandlerActivity) {
nfcAdapter!!.enableReaderMode(
activity,
activity,
NfcAdapter.FLAG_READER_NFC_A or
NfcAdapter.FLAG_READER_NFC_B or
NfcAdapter.FLAG_READER_NFC_F or
NfcAdapter.FLAG_READER_NFC_V or
NfcAdapter.FLAG_READER_NFC_BARCODE or
NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK or
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
Bundle()
)
}
// in activity onPause()
fun disableReaderMode(activity: NFCCryptoHandlerActivity) {
nfcAdapter?.disableReaderMode(activity)
}
override fun onTagDiscovered(tag: Tag?) {
[email protected] = tag
isoDep = IsoDep.get(tag)
isoDep?.timeout = 200000
}
private fun sendCommandArray(apduCommands: List<ApduCommand>) {
thread {
try {
isoDep = IsoDep.get(tag)
isoDep?.connect()
if (isoDep!!.isConnected) {
apduCommands.forEach { apduCommand ->
val result = isoDep?.transceive(apduCommand.bytes)
runOnUiThread {
// post result in UI
}
}
}
} catch (e: Exception) { }
finally {
try {
isoDep?.close();
} catch (e: Exception) { }
}
}
}
Bundle
to the enable command, add option to control the frequency of "presence" checks yourself (something likebundle.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
in Java for a 250ms time between "presence" checks) – PamperoonTagDiscovered
callisoDep?.close()
as your long timeout might be blocking new Tag detection. – Pampero