Search code examples
androidandroid-intentnfcandroid-pendingintent

NFC intent launch app with launcher activity only if the app isn't running in background


I'm trying to open my application from NFC app chooser dialog which appears when NFC tag is detected by the system. My app appears in chooser dialog.

Case 1:

When application is running in background. On NFC tag detection bring background activity(top activity in task) to foreground.

Problem

I need to specify which activity handles the nfc intent from system in manifest file. So when user selects my application from app chooser system launchs that specified activity. Instead of bring background activity to the front.

Case 2:

When application is not running lunch application with it's launcher activity.

Problem

To achieve this I need to specify launcher screen as NFC intent handler in manifest file. By doing this my app will fail in case 1!

AndoridManifest.xml snippet

         <activity android:name=".activityName" ...>
                <intent-filter>
                    <action android:name="android.nfc.action.TECH_DISCOVERED"/>
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
                <meta-data
                    android:name="android.nfc.action.TECH_DISCOVERED"
                    android:category="android.intent.category.DEFAULT"
                    android:resource="@xml/nfc_tech_filter" />
         </activity>

What can be the solution to satisfy both cases? I tried with ActivityManager but didn't get the solution with it.


Solution

  • I solved my problem by adding following code into launcher activity's onCreate(). I kept intent filter and meta data same for launcher activity. The trick here is to check if application task is already running into system or not.

    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
                finish();
                return;
    }
    

    Above code will check if application task is already running or not. If its running then launcher activity will close him self and will brought top most activity of task to the front.

    Reference:

    https://stackoverflow.com/a/21022876/2465752 https://developer.android.com/reference/android/R.styleable.html#AndroidManifestActivity_launchMode