I wanted to add NFC functionality to my RelayRemote project but found the amount of examples about writing custom data to an NFC tag on Android very lacking. The Android docs have a bunch of info on basic NFC and how it works, but for actually writing the data to the tag, they try to push you to some convenience functions that were added in Jelly Bean (4.1). Unless you’re targeting Jelly Bean and up (not likely at the time of this writing), it doesn’t help to use these functions.
In my case, I wanted to write the ID of a relay to turn on/off to the tag, which would then be read, have the ID looked up in the database, and let the network thread class send the data to the server. The first step in this process was writing the NFC tag. To do this, we set up a pending intent with an intent that has the data to write to the tag in it. Android will execute this pending intent the next time a tag comes into range. Basically, what we’re doing is putting the device into a sort of write mode where when a tag comes into contact, Android will get our app a callback and we’ll try to write our data to the tag.
The intent setup looks something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
// Construct the data to write to the tag
// Should be of the form [relay/group]-[rid/gid]-[cmd]
String nfcMessage = relay_type + "-" + id + "-" + cmd;
// When an NFC tag comes into range, call the main activity which handles writing the data to the tag
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
Intent nfcIntent = new Intent(context, Main.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
nfcIntent.putExtra("nfcMessage", nfcMessage);
PendingIntent pi = PendingIntent.getActivity(context, 0, nfcIntent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
nfcAdapter.enableForegroundDispatch((Activity)context, pi, new IntentFilter[] {tagDetected}, null);

