【问题标题】:Android: Write a byte array via NFCAndroid:通过 NFC 写入字节数组
【发布时间】:2015-11-27 11:23:25
【问题描述】:

我目前正在研究 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;
}

但是我需要如何改变上面的代码来写一个字节数组而不是字符串呢?

【问题讨论】:

  • 您对我们的期望是什么?

标签: android tags bytearray nfc ndef


【解决方案1】:

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

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

您可以将“example.com”设置为您想要用于 NFC 论坛外部类型的任何域名,并将“mytype”设置为您想要为外部类型提供的任何名称(请注意,外部类型名称必须小写。

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 2012-07-17
    • 2022-10-04
    • 1970-01-01
    • 2012-03-19
    • 2019-01-29
    • 2016-08-07
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多