Android:通过NFC写一个字节数组

时间:2015-11-27 11:23:26

标签: android tags bytearray nfc ndef

我目前正致力于NFC,并希望将字节数组写入NFC标签。我可以使用以下代码编写一个字符串:

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;
}

但是我怎么需要更改上面的代码来编写一个字节数组而不是字符串?

1 个答案:

答案 0 :(得分:0)

您可以创建一个外部记录,而不是创建文本记录,该记录包含要作为其有效负载存储在标记上的字节数组:

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

您可以将“example.com”设置为您要用于NFC论坛外部类型的任何域名,将“mytype”设置为您要为外部类型指定的名称(请注意外部类型名称必须为小写。< / p>

相关问题