2012-06-06 47 views
2

我嘗試了很多方法,沒有爲我工作。下面的代碼顯示了ndefmessage,但它不是可讀的格式。它顯示一些NDEF消息格式爲b @ 15D ...使用Android閱讀nfc標籤中的數據值,並以可讀格式在標籤中顯示它們

public void onNewIntent(Intent intent) { 
    Tag myTag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
    def ndefTag = Ndef.get(myTag); 
    int size = ndefTag.getMaxSize();   // tag size 
    String type = ndefTag.getType();   // tag type 
    NdefMessage ndefMesg = ndefTag.getCachedNdefMessage(); 
    NdefRecord[] ndefRecords = ndefMesg.getRecords(); 
    int len = ndefRecords.length; 
    for (int i = 0; i < len; i++) { 
    typ = ndefRecords[i].getType(); 
    payload = ndefRecords[i].getPayload(); 
    } 
    String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16"; 
    int languageCodeLength = payload[0] & 0077; 
    try { 
    @SuppressWarnings("unused") 
    String languageCode = new String(payload, 1,languageCodeLength,"US-ASCII"); 
    } catch (UnsupportedEncodingException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 
    try { 
    text =new String(payload,languageCodeLength+1,payload.length 
     -languageCodeLength - 1, textEncoding); 
    Toast.makeText(getApplicationContext(), 
     text+"First Try",Toast.LENGTH_LONG).show(); 
    mText.setText("Discovered tag "+text); 
    } catch (UnsupportedEncodingException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    String val = new String(typ); 
    val+=new String(payload); 
    Toast.makeText(getApplicationContext(), 
     "Second"+val,Toast.LENGTH_LONG).show(); 
    } 
    Log.i("Foreground dispatch", "Discovered tag with intent: " + intent); 
    mText.setText("Discovered tag "+text); 
} 

回答

2

一個NdefRecord的有效載荷並不一定是String

您需要查看類型名稱格式(TNF)和類型以確定如何解碼有效負載。

如果您在寫入標籤new String(record.getPayload())時已在有效負載中編碼了一個字符串,將會正常工作。

如果您使用其他軟件編寫了純文本標籤,則可能是TNF_WELL_KNOWN類型RTD_TEXT。在這種情況下,有效載荷字節數組將包含語言代碼作爲字符串的第一個字節。有關如何解析有效負載的示例,請參閱http://developer.android.com/resources/samples/NFCDemo/src/com/example/android/nfc/record/TextRecord.html

+0

感謝它的工作,我現在可以檢索數據值。無論何時數據在寫入NFC標籤時以純文本書寫 – Joseph