How to use NFC in Android
The NFC technology stands for Near Field Communication and you can find the specification at NFC Forum. In this first post, we will analyse some basic aspects of NFC in Android, and we will describe how to implement a Android NFC app to read tags.
If you want to experiment NFC, there are several websites where you can buy NFC with a few euro.
NFC can be used in a different situation: we can use it to turn on our Wifi when we are at home or launch task actions and so on.
We will focus our attention on NDEF data that is a special type of NFC tag.
There are some basic steps we have to follow before using the NFC.
NFC NDEF Structure
here are several types ofNFC (NDEF) tag:
- NFC Forum well-known type [NFC RTD]
- Media-type as defined in RFC 2046
- Absolute URI as defined in RFC 3986
- NFC Forum external type [NFC RTD]
It is possible to know the NFC type using the last three bytes in the NFC header. The structure is shown below:
The most important byte (7th) is the Message Begin byte, this byte is 1 if the it is the starting message otherwise is zero. The 6th byte is the Message End, this byte is 1 if the this record is the end record otherwise is 0. SR is the Short Record and it is 1 if it is a short record. This information are important if we want to handle the NDEF tag data correctly.
We know that Android SDK provides the method getPayload() that returns an array of bytes that represent the tag content. We have to read and parse this array to extract information.
Android NFC Filter
When we develop an Android NFC Tag, the first thing we want is our app is notified when we get near a NFC tag. To this purpose we use a intent filter. Android SDK provides three different filter that we can use with different level of priority:
We focus our attention on ACTION_NDEF_DISCOVERED, that has the highest level of priority. As said, our goal is being notified when the smart phone is near a NFC tag and, if we have only this app installed and capable to handle this NFC tag, we want that the app starts immediately.
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
NFC Well-known type: Text Record
The NFC Well-Known type is the simplest record type to read NFC tag in Android. To get the NFC payload, the first thing to do is reading the header (payload) and parse it. The most significative byte (the 7th) represent the text encoding. Find more at Read NFC Tag in Android.
NFC NDEF Smart poster
This is the most complex NDEF tag, because it can be made by several inner contents made by several types.
In this case is very important to read the message header to know if the record is a Message Begin or Message end or if the record is a Short Record.
If you want to have more details jump to the original post.