Reputation: 143
I am learning Android and NFC programming through the official android developer tutorial. What I want is to write an app that will be triggered by NFC tag. When the app starts, I want it to display a toast message containing the UID of the scanned tag. My simple code to achieve this is:
@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));
}
I also update the manifest file to enable NFC as shown below:
<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>
Then I use "NFC Task Launcher" app from Play Store to write into my tag so that the tag will trigger my new app. After creating the tag, tapping on it will successfully start my new app, but the app fails to display the toast of the UID and it will crash stating "Unfortunately Test NFC has stopped." What did I miss to cause this crash?
Upvotes: 0
Views: 7219
Reputation: 11
Try it like:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this,bin2hex(tag.getId()),Toast.LENGTH_LONG).show();
}
}
Upvotes: 1