问题
I have an Activity that is defined to be singleTop so that only the one instance will exist.
<activity
android:name=".MyMainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:launchMode="singleTop" android:multiprocess="true">
I set up a Notification Intent with some data, and include it in a PendingIntent, and send it to the Notification Manager.
Intent notificationIntent = new Intent(context, MyMainActivity.class);
notificationIntent.setAction(MyMainActivity.CustomInternalMessageAction);
notificationIntent.putExtra(MyMainActivity.ReceiveTestMessage, rawMessageText);
...
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
mNotificationManager.notify(number, notification);
If the actiivty is not running, the intent starts the activity via onCreate() as expected.
If The activity is running, but in the stopped state / not in foreground (like when clicking the home button), and the notification is clicked, my activity's onNewIntent() is called as expected.
However, if the Activity is already called when it's in the foreground, then onNewIntent() doesn't get called.
How can I set up this notificaiton so that my singleTop Activity gets sent the intent, when it's in the pause/stop state (and also still functions in the other cases I mentioned). I'm thinking there's a flag to set on my notificationIntent object, but the functions of the flags aren't really clear for the case of singleTop activities.
回答1:
If your application is composed by more than one activity, the remain activities need to be defined as singleTop
as well if you want to receive a onNewIntent()
call when that activity is active.
Let suppose that main activity is A
and is defined as singleTop
and from there you start activity B
not defined as singleTop
. If now you select a notification that calls your application, the application will start on activity B
but onNewIntent()
is not called.
You can also override this behaviour adding the flag Intent.FLAG_ACTIVITY_CLEAR_TOP
which remove activity B
from stack and Activity A
will recive the call on onNewIntent()
.
来源:https://stackoverflow.com/questions/12861051/intent-not-picked-up-by-singletop-activity