Search code examples
androidnfc

enableForegroundDispatch for Activity launched from another app


I develop an app with NFC Tags interaction. Most of time application must ignore tag discovery events. And other apps should not catch tag discoery events when my app is foreground. So I used EnableForegroundDispatch to handle that.

This works fine. I handle excess TAG_DISCOVERED intents into my activity's onNewIntent methods.

The problem: When my activity is launched from another app, enableForegroundDispatch is not working. I receive TAG_DISCOVERED intents in new activity's onCreate method. Here is my foregroundDispatch

if (nfcAdapter == null) {
            Log.w(TAG, "enableForegroundNfcDispatch: no nfcAdapter", new Exception());
            return;
        }
        Log.d(TAG, "enableForegroundNfcDispatch: ");
        if (!nfcMonopolyMode) {
            if (nfcTagDiscoveryPendingIntent != null) {
                nfcAdapter.enableForegroundDispatch(this, nfcTagDiscoveryPendingIntent, nfcTagDiscoveryFilter, null);

                return;
            }
            IntentFilter discovery = new IntentFilter(ACTION_TAG_DISCOVERED);
            nfcTagDiscoveryFilter = new IntentFilter[]{discovery};

            Intent nfcProcessIntent = new Intent(getBaseContext(), getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);


            nfcTagDiscoveryPendingIntent = PendingIntent.getActivity(getApplicationContext(), REQUEST_CODE_NFC_DISCOVERED_TAG, nfcProcessIntent, 0);

            nfcMonopolyMode = true;
            nfcAdapter.enableForegroundDispatch(this, nfcTagDiscoveryPendingIntent, nfcTagDiscoveryFilter, null);
        }

May be there is something to do with flags? Please help


Solution

  • My experience is that if you enableReaderMode with all the flags (including skip NDEF check) then basically detection of any card type is sent to your App if running in the foreground.

    As well as enableReaderModein onResume I have Broadcaster Receiver to enableReaderMode of NFC service State change.

    Checking a number of Different Tags this seems to work BUT they are all NfcA based of varying formats. As confirmed by stackoverflow.com/questions/33633736/… but it seems Android 10 might have a timing issues with Kiosk Mode