识别NFC标签ID [英] Identifying NFC tag ID
问题描述
我正在尝试使用以下代码在android上识别NFC标签的唯一标识符:
I am trying to identify the unique identifier of NFC tag on android using the following code:
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tag myTag = (Tag) getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
String nFCID = myTag.getId().toString();
Toast.makeText(getApplicationContext(), "NFC id is: "+ nFCID, Toast.LENGTH_SHORT).show();
}
不幸的是,当我将应用程序部署到真实设备并扫描NFC标签时,我的应用程序将崩溃,提示不幸的是xyz必须停止...". 我知道getID()将返回字节数组,我必须将其解析为String.但是至少我希望这段代码返回一些值,而不是使应用程序崩溃.有任何解决方法的想法吗?
Unfortunately, when I deploy the app to a real device and scan an NFC tag, my app will crash stating "Unfortunately xyz has to stop...". I know getID() will return byte array and I have to parse it to String. But at least I expect this code to return some values rather than crashing the app. Any ideas how to fix it?
已LogCat输出:
W/dalvikvm(25548): threadid=1: thread exiting with uncaught exception group=0x41b652a0)
E/AndroidRuntime(25548): FATAL EXCEPTION: main
E/AndroidRuntime(25548): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.xyz.nfcid/com.xyz.nfcid.MainActivity}:
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
推荐答案
我很确定,您的标签为空.您应该先检查字符串操作
I'm pretty sure, that your tag is null. You should check the action String first
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
//... do something
}
我已经写了完整的教程,它应该会对您有所帮助.
I've written a complete tutorial, which should help you.
这篇关于识别NFC标签ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!