androidnfcndefnfc-p2pandroid-beam

How to send bytes[] by NFC


How can I send raw bytes by NFC P2P. I've got this on sender side:

private static NdefRecord createByteRecord(final byte[] b){
    final byte[] data = new byte[b.length + 1];
    data[0] = (byte) 0x0;
    System.arraycopy(b, 0, data, 1, b.length);    
    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}

I don't know, if "NdefRecord.RTD_TEXT" is a good choice here. On the receiver side it looks like this:

private String readText(NdefRecord record) throws UnsupportedEncodingException
{
    byte[] payload = record.getPayload();
    //DO SOMETHING WITH BYTES, BUT GOT WRONG RESULTS WITH THIS BYTES    
    String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
    int languageCodeLength = payload[0] & 0063;
    return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}

What record type should be used to transfer raw bytes of data? How should they be packed into an NDEF record?


Solution

  • To transfer byte array, it's better to use TNF_MIME_MEDIA. You could create your own mime type for instance:

    "application/vnd.com.mycompany.myapp.beam"
    

    For instance to create NDEFRecord:

    byte[] bytes = ...;
    NdefRecord mimeRecord = NdefRecord.createMime("application/vnd.com.mycompany.myapp.beam", bytes);
    

    Below doc from android:

    https://developer.android.com/guide/topics/connectivity/nfc/nfc.html#mime