Android / NFC: Get Tag in onCreate() without new Intent

ε祈祈猫儿з 提交于 2019-11-28 10:36:21

If you want to receive the NDEF discovery intent upon the start of your activity, you need to add an intent filter that triggers on the tag's NDEF message to your application manifest:

<activity ... >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

I guess you already have the above, so you will need to add an NDEF intent filter:

    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />

You can use either a URI based trigger:

        <data android:scheme="http" android:host="mroland.at" android:pathPrefix="/test" />

Or a MIME based scheme:

        <data android:mimeType="application/vnd.mroland.test" />

Or if you want to receive the NDEF discovered intent for a tag that contains only an AAR (I have to admit that I never tested this so I only assume that this should work):

        <data android:scheme="vnd.android.nfc" android:host="ext"
              android:pathPrefix="/android.com:pkg" />

But you have to use one of them. (At least on most devices you have to. Some devices/Android versions will accept the intent filter even without a data element.)

    </intent-filter>
</activity>

You can then get the intent in onCreate(), onStart(), onResume() or wherever you want to read it using the getIntent() method.

Note that if you don't add an intent filter for NDEF_DISCOVERED to your manifest, an NDEF message with an AAR for your application will cause the intent action MAIN with the category LAUNCHER to be passed to your first activity that declares such an intent filter. In that case you will not receive the NDEF message. So if you want to receive the NDEF message you have to to declare an intent filter for NDEF_DISCOVERED. In that case, you can choose which activity is started by the AAR by setting the NDEF_DISCOVERED intent filter for that specific activity.

You need to use the onNewIntent() method as discussed in the documentation. The onCreate() method should contain the setup code that you currently have in onResume(). This will cause the app to work in all cases.

From the Android documentation (http://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc.html):

public void onPause() {
    super.onPause();
    mAdapter.disableForegroundDispatch(this);
}

public void onResume() {
    super.onResume();
    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}

public void onNewIntent(Intent intent) {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //do something with tagFromIntent
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!