I would like to start an application using an NFC tag. I got that part working using an android application record (AAR) as described in Start Android application from NFC-tag with extra data or by using NDEF_DISCOVERED
/ TECH_DISCOVERED
intent filters. But how do I pass data from the NFC tag (e.g. some text) to my activity upon starting it through the NFC event?
I've read through NFC Basics, but as far as I understand that it seems to want to implement a mechanism for reading the tag, when I really do not want to re-read the tag once the app is opened by the tag, but instead I just want the data passed in at the same time.
Moreover, these mechanisms seem to allow the app to read the tag after it has been started by the tag. In other words, I am worried that if someone hits the tag later when the app is already opened that tag will be read again (which is what I do not want).
Second, how do I create such NDEF message?
Android will automatically read the NDEF message of an NFC tag and process it in order to
In order to get your activity started and have Android pass the pre-read NDEF message, you could use the
NDEF_DISCOVERED
intent filter:Then from within your activity, you could process that NDEF message:
Note that
onResume()
is run whenever your activity becomes the foreground activity. Hence, it might be run multiple times for the same tag. THerefore, you could either use another life-cycle method or take some precautions that you do not parse the message multiple times.If you want to drop all further NFC events, once your activity is open, you could follow the approach that I described in response to Android app enable NFC only for one Activity. Hence, you would register for the foreground dispatch (which gives your activity priority in receiving NFC events, and you can then simply drop those events.
Finally, to create the NDEF message for your NFC tag, you would do something like this:
If you want to make sure that only your app is started by this tag (or if not installed Play Store is opened for your app), you could also add an AAR: