0
我正在通過官方的android開發者教程學習Android和NFC編程。我想要的是編寫一個將由NFC標籤觸發的應用程序。當應用程序啓動時,我希望它顯示包含掃描標籤的UID的Toast消息。我簡單的代碼來實現這一目標是:在Android中獲取NFC的UID
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(getApplicationContext(), "UID: " + bin2hex(tag.getId()), Toast.LENGTH_SHORT).show();
}
// Parsing binary to string
static String bin2hex(byte[] data) {
return String.format("%0" + (data.length * 2) + "X", new BigInteger(1,data));
}
如下圖所示
我也更新清單文件以啓用NFC:
<uses-permission android:name="android.permission.NFC"/>
....
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
<activity
android:name="com.testapp.testnfc.MainActivity"
android:label="@string/app_name" >
.....
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
然後我用「NFC任務啓動器」的應用從Play商店寫入我的標籤,以便標籤將觸發我的新應用程序。創建標籤後,點擊它將成功啓動我的新應用程序,但應用程序無法顯示UID的敬酒,它會崩潰,說明「不幸測試NFC已停止」。我錯過了什麼導致這次事故?
異常日誌可能? – takumar