-2

I am currently working on NFC and would like to write a byte array to an NFC tag. I am able to write a string using the following code:

private void write(String text, Tag tag) throws IOException, FormatException {
    NdefRecord[] records = { createRecord(text) };
    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();
}

private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
    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 recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,  NdefRecord.RTD_TEXT,  new byte[0], payload);

    return recordNFC;
}

But how would I need to change the above code to write a byte array instead of the string?

Michael Roland
  • 39,663
  • 10
  • 99
  • 206

1 Answers1

1

Instead of creating a text record, you could create an external record that contains the byte array that you want to store on the tag as its payload:

byte[] byteArray = ...
NdefRecord[] records = {
    NdefRecord.createExternal("example.com", "mytype", byteArray)
};

You can set "example.com" to whatever domain name you want to use for the NFC Forum external type and "mytype" to whatever name you want to give the external type (note that external type names must be lowercase.

Michael Roland
  • 39,663
  • 10
  • 99
  • 206