Identifying NFC tag ID

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 11:56:32

问题


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();      
}

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?

Edited: LogCat outputs:

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)

回答1:


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.



来源:https://stackoverflow.com/questions/18322424/identifying-nfc-tag-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!