How to find out whether an NFC tag is still in range of an Android now?

前端 未结 2 1655
情深已故
情深已故 2020-12-03 06:22

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 pla

2条回答
  •  执笔经年
    2020-12-03 06:58

    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.

提交回复
热议问题