简体   繁体   中英

How can I make sure Android Beam doesn't start a new instance of my 'singleTop' activity?

First, the use case : 2 phones have my app opened on the same screen. I want one user to be able to share the screen content (data) with the other one without necessarily opening a new instance of the activity when beaming using NFC. (both Android devices are running Ice Cream Sandwich)

So I have a singleTop activity declared like this in the manifest.

<activity android:name=".activity.MyActivity" android:configChanges="orientation|keyboardHidden" android:launchMode="singleTop">
  <intent-filter android:label="@string/activityLabel">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="a.b.c/x.y.z" />
  </intent-filter>
  <intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="application/x.y.z"/>
  </intent-filter>
</activity>

When a VIEW action is fired and the activity is already on top, the onNewIntent() method is called in the same instance if the activity.

When a NDEF_DISCOVERED action is fired and the activity is already on top, the onCreate() method is called in a new instance of the activity.

You describe the case that the app is already open and the proper Activity is in the foreground. In that case, you can make use of the foreground-dispatching of NFC intents by calling NfcAdapter.enableForegroundDispatch() in your Activity's onResume() (and disableForegroudDispatch() in onPause() ). This will force all NFC Intents to be delivered to your Activity (via onNewIntent() ).

你应该使用:android:launchMode =“singleInstance”适合我。

I don't have an answer for you. But I have a workaround: have the NDEF_DISCOVERED start a new activity. Make that activity invisible ( Theme.NoBackground ) and in the onCreate, make it start the MyActivity with singleTop and finish immediately. MyActivity should now appear with onNewIntent .

Have you looked at the Android Beam sample:

http://developer.android.com/resources/samples/AndroidBeamDemo/index.html

It implements this behavior that you want (minus VIEW intent filtering). I'm not sure if that intent will affect the NDEF_DISCOVERED one, but it would be interesting to maybe modify the Android Beam sample to see if you can cause the same behavior as your app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM