Edit : Seems I have missed a tag and the OP does not ask for Java code. Leaving this anyway for future reference
Your guess is correct, although it might be possible to define the intents you want to listen for in the AndroidManifest.xml, foreground dispatch really puts your app in the front, giving you the ability to capture all launched NFC intents.
The way it is described in the docs gives you a clue.
I assume you're familiar with the lifecycle of the Android Activities, Intent Dispatching and such.
Structure
Using the following structure, you'd have 4 fields :
private PendingIntent pendingIntent;
private IntentFilter[] mIntentFilters;
private String[][] mTechLists;
private NfcAdapter mNfcAdapter;
In the onCreate
you'd get :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
mIntentFilters = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)};
mTechLists = new String[][]{new String[]{Ndef.class.getName()},
new String[]{NdefFormatable.class.getName()}};
}
This does not actually enable the Foreground Dispatch yet, it is just the preparation.
The application would receive the Ndef and NdefFormatable technologies
Why do we subscribe for ACTION_NDEF_DISCOVERED ?
The order in which Android tries to handle the intent is as such :
- ACTION_NDEF_DISCOVERED
- ACTION_TECH_DISCOVERED
- ACTION_TAG_DISCOVERED
So we make sure our app is the first to be looked at by Android.
Enable FGD
Put the following line of code in the onResume
method :
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, mIntentFilters, mTechLists);
}
Why is this in the onResume
? As the docs state : enableForegroundDispatch() must be called from the main thread and only when the activity is in the foreground (calling in onResume() guarantees this)
This should enable your app to receive the intent, of course, when actually running.
If you want to receive intents while not running, you'd have to go to the AndroidManifest.