As I know when an Android phone gets an NFC tag touched, it will send an event (NDEF_DISCOVERED intent), but Android doesn't seem to care whether this tag is staying in place. My solution is to lock the screen and then unlock it. If the tag is still there, I can read it again. This is obviously a silly way. Is there any smarter way to do it?
Asked
Active
Viewed 4,482 times
2 Answers
4
As part of the NFC intent received by your activity, you will also receive a tag-handle (Tag
object) in an intent extra:
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Depending on the type of tag, you can then get an instance of the specific tag technology. For instance, if it's an NDEF tag, you can get:
Ndef ndefTag = Ndef.get(tag);
Then you can connect to the tag using the connect() method:
ndefTag.connect();
After that you can check if the tag is still "connected" to the device by periodically trying to read from the tag:
try {
ndefTag.getNdefMessage();
} catch (IOException e) {
// if you receive an IOException, contact to the tag has been lost
}
Note that this will only work if your activity is in the foreground all the time and the screen remains on.

Michael Roland
- 39,663
- 10
- 99
- 206
-
Haven’t tried this yet, but the docs specify a `TagLostException`. Wouldn’t the latter fire if the tag moves out of range, with the former handling any other kind of I/O issues? – user149408 Feb 26 '17 at 14:11
-
@user149408 `TagLostException` *is* a specific type of IO exception. So, yes, on most devices, the `IOException e` will be an instance of `TagLostException`. – Michael Roland Feb 26 '17 at 17:40
0
There is a function that checks to see if the card is still connected called isConnected()
. Can be used like this:
try {
ndef.connect();
while(ndef.isConnected()){
//Your code here
}
} catch (IOException e) {
//Error
}

Philipp Panik
- 254
- 1
- 4
- 15
-
2isConnected() does not tell you if the tag is still in range it only tells you if you did a successful connect(). You can be 50 meters away from you tag isConnected() will still return true... – Stéphane Dec 07 '18 at 17:09