编写使用的是Nexus S的NFC标签的是、标签、Nexus、NFC

2023-09-12 09:11:07 作者:心死只是一瞬间

我有一个姜饼2.3.4 动力的Nexus S ,然后我最近得到了一些可写的 NFC 标记。到目前为止,我可以阅读它们为空白标签,但我无法找到一种方法把数据写入其中。 我所有的研究已经使我的这篇文章:写作标签与Nexus S的一月( 2.3.4之前发布的)。

I have a Gingerbread 2.3.4 powered Nexus S and I recently got some writable NFC tags. So far I can read them as blank tags, but I couldn't find a way to write data to them. All my research has lead me to this article: Writing tags with Nexus S from January (before 2.3.4 release).

你怎么写NFC标签的应用程序中,用你的Nexus S?任何指针?

How do you write NFC tags inside your application, using your Nexus S? Any pointers?

推荐答案

我发现Android的NFC API文本和Dev Guide的有点棘手遵循这样一个有点例如code可能会有所帮助。这实际上是MIDP code端口我一直在使用诺基亚6212的设备,所以我可能还没有想通了一切关于Android的NFC API正确,但至少这为我工作。

I found the Android NFC API text and dev guide a bit tricky to follow so a bit of example code might help here. This is actually a port of MIDP code I've been using in Nokia 6212 devices, so I probably haven't yet figured out everything about Android NFC API correctly, but at least this has worked for me.

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

First we create an NDEF record:

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

然后,我们写的记录作为NDEF消息:

Then we write the record as an NDEF message:

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

要写入的标签,你显然需要标记对象,它可以从意向得到。

To write to a tag, you obviously need the Tag object, which you can get from the Intent.

 
精彩推荐
图片推荐