Start Activity with NFC in a specific task

2019-05-10 07:48发布

问题:

My app contains a number of activities. One of these activities responds to an NFC intent filter, as well as standard intents, however, this activity is launching in it's own task, and not in the same task as the app. The app is not necessarily running when the NFC intent is initiated but if it is, I want the activity to launch in the same task to ensure a seamless user experience. At the moment, the app is behaving as though there are 2 of them running.

Here is the manifest for my NFC activity:

<activity
        android:name="name.subname.app.activity.ItemSummaryActivity"
        android:label="@string/title_activity_item_summary" >
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />

            <data android:mimeType="application/vnd.name.nfcdemo" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>

Is it possible to launch the activity in the existing task, if it exists?

回答1:

I see two options here:

1) Add android:launchMode="singleTask" to activity tag in the manifest:

<activity
        android:name="name.subname.app.activity.ItemSummaryActivity"
        android:label="@string/title_activity_item_summary"
        android:launchMode="singleTask" >

"singleTask":

The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.

2) Supply Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT flag to startActivity() intent. But, if the activity is triggered by NFC (and using this option is not feasible) consider what @NFC guy has to say here.