0

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>
Vilius
  • 1,169
  • 5
  • 19
  • 32

1 Answers1

1

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" />
Michael Roland
  • 39,663
  • 10
  • 99
  • 206
  • I must admit, that for the first purpose, it works fine! That means that if the app is closed or the main activity is in focus. But if I have another activity open, the user gets redirected to the main activity, but the main activity gets recreated... That means multiple instances. – Vilius Oct 18 '13 at 17:28
  • Well, if you want that behavior also for other activities of your app, then you have to enable the foregorund dispatch for those activities too. Upon receiving the foreground dispatch event, you can then cycle back to your main activity. – Michael Roland Oct 18 '13 at 18:41
  • Foreground Dispatch was the keyword I was looking for. Even with a hierarchical view structure (activity A -> activity B -> activity C) I was able to chain the calls for onNewIntent and so always redirect the user to the main activity. Thank you again! – Vilius Oct 20 '13 at 13:04