walsli walsli - 3 months ago 25
Android Question

How to confirm whether there is a NFC tag exists in Android now?

As I know when an Android phone gets a NFC tag touched,it will send a event to NDEF,but Android don't 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 silly way.Is there any smarter way to do it?


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:


After that you can check if the tag is still "connected" to the device by periodically trying to read from the tag:

try {
} exception (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.