enableForegroundDispatch for Activity launched from another app Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of enableForegroundDispatch for Activity launched from another app without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

Answer

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

We are here to answer your question about enableForegroundDispatch for Activity launched from another app - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji