android - 使用Android读取nfc标签中的数据值并以可读格式显示在标签中

标签 android nfc

我试了很多方法,都没用。下面的代码显示了 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);
}

最佳答案

NdefRecord 的负载不一定是 String

您需要查看类型名称格式 (TNF) 和类型以确定如何解码负载。

如果您在编写标签时在负载中编码了一个字符串,new String(record.getPayload()) 将正常工作。

如果你用其他软件写过一个纯文本标签,它可能是 tnf TNF_WELL_KNOWN type RTD_TEXT。在这种情况下,有效负载字节数组将包含语言代码作为字符串的第一个字节。参见 http://developer.android.com/resources/samples/NFCDemo/src/com/example/android/nfc/record/TextRecord.html有关如何解析有效负载的示例。

关于android - 使用Android读取nfc标签中的数据值并以可读格式显示在标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10919470/

相关文章:

Android/OkHttp - client.newCall(request).execute() 总是返回异常

android - 如何保存我的 Activity 状态?

android - 如何读取 Mifare 经典 Nfc 标签?

nfc - Mifare Classic 1k - 仅在 Samsung S III mini GT-i8190N 上出现错误

java - 安卓工作室 : I need help in converting a code in java that returns an int from MYSQL database into a string (SHAREDPREFERENCES)

android - 如何在调用另一个 Activity 后恢复状态?

android - 禁用 JNI C 代码中变量的编译器优化

python - nfcpy : Can't escape a while loop constantly listening with nfcpy

java - 如何从 Java 中的字符串中精确获取 16 个字节

android - NFC - 读/写设备之间的通信