使用Nexus S编写NFC标签

Mar*_*tuc 10 android nfc nexus-s

我有一个Gingerbread 2.3.4供电的Nexus S,我最近得到了一些可写的NFC标签.到目前为止,我可以将它们读作空白标签,但我找不到向它们写入数据的方法.
我的所有研究都引导我阅读这篇文章:从1月份开始用Nexus S编写标签(2.3.4发布之前).

如何使用Nexus S在应用程序中编写NFC标签?有什么指针吗?

Pas*_*nen 16

我发现Android NFC API文本和开发指南有点棘手,所以一些示例代码可能会有所帮助.这实际上是我在诺基亚6212设备中使用的MIDP代码的一个端口,所以我可能还没有正确地弄清楚Android NFC API的所有内容,但至少这对我有用.

首先,我们创建一个NDEF记录:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后我们将记录写为NDEF消息:

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();
}
Run Code Online (Sandbox Code Playgroud)

要写入标记,您显然需要Tag对象,您可以从Intent获取该对象.