How to read an NFC tag which is already attached t

2019-07-30 00:49发布

问题:

My requirement is to read an NFC tag which is already attached to the device.

I observed the following in my application:

An NFC tag is already attached to the device and NFC is off. When I then launch my Android app it will ask to turn on the NFC and, after turning on NFC, my app will read the NFC tag that was already attached to the device.

An NFC tag is already attached to the device and NFC is on. When I then launch my app manually, it will not detect the NFC tag.

Why is the NFC tag not detected by the app in the latter case? Is there any way to detect and read a tag that was already attached to the device before the app is started (manually)?

回答1:

In general that's not possible. Android only dispatches a tag to an app if the tag is newly discovered (i.e. the tag has just been tapped). Thus, apps cannot access tags that were already in the field of the NFC reader when the app is launched.

Since the Android NFC API does not allow the NFC feature to be disabled and re-enabled from within an app (this can only be done through the Settings app), its also not possible to temporarily disable the NFC reader to trick Android into detecting the tag as freshly tapped.

However, on Android version >= 4.4 and < 5.1 (or was that < 6.0?) there is a bug (undocumented feature?) in the implementation of the NFC reader-mode API (enableReaderMode() that causes tags to be redecteded after enabling reader-mode. Consequently, on these Android versions you could use enableReaderMode() to rediscover already-attached tags. Be warned though that while this works in AOSP, some device manufacturer-specific modifications of Android might not contain this bug/feature.