2015-03-19 21 views
1

我使用Eclipse的Android和創造是應該使用此代碼來發送純文本的應用程序:如何發送純文本只使用NFC的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商店鏈接。我怎樣才能配置它將被讀取的唯一消息是純文本?

+0

您無法發出純文本。您只能照射一個或多個NDEF記錄。 – ThomasRS 2015-03-19 17:19:25

+0

是否意味着我只能發揮商店鏈接或包名稱? – 2015-03-19 17:37:10

+1

你的問題不包括相關的代碼! 'createRecord()'在哪裏被調用?你如何激活/註冊梁?你在用什麼設備? – 2015-03-19 18:00:09

回答

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-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的更多信息