如何使用nfc android beam发送纯文本

时间:2015-03-19 11:47:46

标签: android nfc ndef android-beam

我正在使用Eclipse-Android并创建一个应该使用以下代码发送纯文本的应用程序:

编辑:

private void write(String text, Tag tag) throws IOException, FormatException {

    NdefRecord[] records = { createTextRecord(text, "yes") };
    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;
}

但我用arduino读到的是包名和Google Play商店链接。如何配置它将被读取的唯一消息是纯文本?

1 个答案:

答案 0 :(得分:0)

我已经使用此代码创建了文本记录,这非常适用

public static NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = payload.getBytes(utfEncoding);
    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);
    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    NdefRecord.RTD_TEXT, new byte[0], data);
    return record;
} 

在AndroidManifest.xml文件中的活动中添加以下intent-filters:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>

访问:http://developer.android.com/guide/topics/connectivity/nfc/nfc.html了解有关NFC的更多信息