Reputation: 8320
I have an activity which starts a service through a button press. During service initialization, if an error occurs, this error is displayed by a notification, as follows:
String tickerText = getString(R.string.init_error);
Notification notification = new Notification(
R.drawable.ic_stat_notify_msg,
tickerText, System.currentTimeMillis());
PendingIntent notificationIntent = PendingIntent.getActivity(
this, 0, new Intent(this, MyServiceActivity.class), 0);
notification.setLatestEventInfo(this,
getText(R.string.init_error_tts_title),
getText(R.string.init_error_tts_text),
notificationIntent);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(R.string.init_error, notification);
stopSelf();
When the notification appears in the status bar, I open the notifications window. Then, when I click on the notification, a new instance of MyServiceActivity is launched... Why?
Upvotes: 0
Views: 1633
Reputation: 983
I have a music player that has the initial launcher activity, then a selection activity and then the player. The notification needs to return the user to the player. I used Christophe's idea and found that putting
android:alwaysRetainTaskState="true"
android:launchMode="singleTop"
in the manfest's activity tag of the PLAYER ACTIVITY gave me the correct behavior. Then make sure your notification invokes the PLAYER ACTIVITY class. I didn't do this at first. It invoked the app launcher class and, while this was okay for newer Androids, it left me with the extra activity problem in Android 2.3.6. Now all is good.
If my activity fix doesn't work for you, you'll have to brute-force your way through the choices found at
http://developer.android.com/guide/topics/manifest/activity-element.html#lmode
I should add that my player is stateless, just four buttons connected to a service. But if your activity needs its state set up when the notification's intent comes in, you need to override onNewIntent:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
Kudos to Christophe. This is a hard question to get the right answer for.
Upvotes: 2
Reputation: 7305
Try to add this attribute on your activity tag on the manifest :
android:launchMode=["multiple" | "singleTop" |
"singleTask" | "singleInstance"]
with value singleTop
or singleInstance
Activity Element Documentation
Upvotes: 5