The android.nfc package allows applications to read NDEF message in NFC tag. Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. In this guide we're going to implement a simple interaction. To to that, you will need and Android device with NFC support and a NFC tag.
The ideia of this tutorial will be simple. Aproach any NFC tag to you your mobile device to hide the red circle in the app. Aproach it again to make the circle visible.
NFC is used today mostly to payments. From bus cards payments to the new Apple Pay or Google Wallet, interacting with NFC will be even more commun in the future.
Our app will be pretty simple. It will hide/show the red circle ball when NFC is detected. I'll not cover how to start your app, but everything you'll is to create a normal project in Android Studio using a Blank Activity.
To explain the process to detect NFC, I will take a 3-step approach:
- ❱ NFC Access
- ❱ Activate NFC
- ❱ Execute any task when NFC is detected
To acceess the NFC (normally there is only one in the Android device) Android provides a Helper to get the default NFC Adapter. Is a static method from NfcAdapter. Create the variable as a member class as we'ra going to use it in other methods.
The next step will be saving a refenrence of PendingIntent. As the documentation says, "the returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time.". That means we are going to need this intent in the next step.
Now we are going to give the current active application priority for reading scanned tags. On the onResume() method, we'll reference an intent for NfcAdapter.ACTION_TAG_DISCOVERED. As the name says, this Intent means to start an activity when a tag is discovered. In other words, we will say to the NfcAdapter (we got on the last method) that this Activity is interested when a NFC approach is detected.
Execute any task when NFC is detected
From here on, it's just Android simple development. We'll use the onNewIntent() method from the Activity's lifecycle. The only thing is to verify if the intent is that one we're looking for, since Android will call this for any intent.
Now you can put any NFC close to the device and hide/show the red circle. You can see the gist for the whole Activity here. comments powered by Disqus