Vilius
Vilius

Reputation: 1189

NFC detection: either start activity or display dialog

I have a main-activity which shows some data in a list and a nfc-asynctask which reads some data from a card. I want to achieve the following behavior:

  1. If the app is closed and a card is put near the mobile phone, the main-activity and simultaneously the nfc-asynctask should be started. The results of the asynctask should be presented in a dialog.
  2. If the app is opened and a card is put near, the nfc-asynctask should be restarted and only a dialog with the results should be opened.

My current approach always starts the main-activity. This means that sometimes, there are multiple instances of my main-activity and when the user hits the back-button, instead of switching to the home-menu, another activity instance is put on.

Manifest

<activity
    ...
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.nfc.action.TECH_DISCOVERED"/>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/filter_nfc"/>
</activity>

Upvotes: 0

Views: 1110

Answers (1)

Michael Roland
Michael Roland

Reputation: 40849

Have a look at Android's foreground dispatch facility. If you register your app for foreground dispatch, your activity receives an onNewIntent() event instead of getting started a second time.

Also, I suggest putting the TECH_DISCOVERED intent in a separate intent filter:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
    <action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
           android:resource="@xml/filter_nfc" />

Upvotes: 1

Related Questions