Writing NFC tags using a Nexus S

Marius Butuc picture Marius Butuc · Jun 8, 2011 · Viewed 18.6k times · Source

I have a Gingerbread 2.3.4 powered Nexus S and I recently got some writable NFC tags. So far I can read them as blank tags, but I couldn't find a way to write data to them.
All my research has lead me to this article: Writing tags with Nexus S from January (before 2.3.4 release).

How do you write NFC tags inside your application, using your Nexus S? Any pointers?

Answer

Pasi Välkkynen picture Pasi Välkkynen · Jun 13, 2011

I found the Android NFC API text and dev guide a bit tricky to follow so a bit of example code might help here. This is actually a port of MIDP code I've been using in Nokia 6212 devices, so I probably haven't yet figured out everything about Android NFC API correctly, but at least this has worked for me.

First we create an NDEF record:

private NdefRecord createRecord() throws UnsupportedEncodingException {
    String text       = "Hello, World!";
    String lang       = "en";
    byte[] textBytes  = text.getBytes();
    byte[] langBytes  = lang.getBytes("US-ASCII");
    int    langLength = langBytes.length;
    int    textLength = textBytes.length;
    byte[] payload    = new byte[1 + langLength + textLength];

    // set status byte (see NDEF spec for actual bits)
    payload[0] = (byte) langLength;

    // copy langbytes and textbytes into payload
    System.arraycopy(langBytes, 0, payload, 1,              langLength);
    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);

    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, 
                                       NdefRecord.RTD_TEXT, 
                                       new byte[0], 
                                       payload);

    return record;
}

Then we write the record as an NDEF message:

private void write(Tag tag) throws IOException, FormatException {
    NdefRecord[] records = { createRecord() };
    NdefMessage  message = new NdefMessage(records);

    // Get an instance of Ndef for the tag.
    Ndef ndef = Ndef.get(tag);

    // Enable I/O
    ndef.connect();

    // Write the message
    ndef.writeNdefMessage(message);

    // Close the connection
    ndef.close();
}

To write to a tag, you obviously need the Tag object, which you can get from the Intent.