Android app enable NFC only for one Activity

If you want to diable processing of NFC discovery events (NDEF_DISCOVERED, TECH_DISCOVERED, TAG_DISCOVERED) while a certain activity is in the foreground, you would register that activity for the foreground dispatch system. That activity can then ignore these events (which it would receive in its onNewIntent() method.

This will prevent NFC discovery events to be delivered to any other activities (so those in your app and in any other installed app) that have an NFC disovery intent filter registered in the manifest.

However, this method will not disable the device’s NFC modem. So the NFC chip will still poll for tags but they will just not be reported to any app.

So all activities that you want to disable NFC for would do something like this:

public void onResume() {
    super.onResume();
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}

public void onPause() {
    super.onPause();
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.disableForegroundDispatch(this);
}

public void onNewIntent(Intent intent) {
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        // drop NFC events
    }
}

Leave a Comment