我尝试了很多方法,对我没用。下面的代码显示了ndefmessage,但它不是可读格式。它显示一些ndef消息格式为b @ 15d ...
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);
}
答案 0 :(得分:3)
NdefRecord的有效负载不一定是String
。
您需要查看类型名称格式(TNF)和类型以确定如何解码有效负载。
如果您在编写标记new String(record.getPayload())
时在有效负载中编码了一个字符串,那么它将正常工作。
如果您使用其他软件编写了纯文本标记,则可能是TNF_WELL_KNOWN
类型RTD_TEXT
。在这种情况下,有效负载字节数组将包含语言代码作为String的第一个字节。有关如何解析有效负载的示例,请参阅http://developer.android.com/resources/samples/NFCDemo/src/com/example/android/nfc/record/TextRecord.html。