I have the following issue: I wrote an android service - a music player - that runs in the background and launches a notification at startup. Clicking on this notification opens activity A that allows to interact with this player. This works fine.
The issue is when I have third-party activity, e.g., a web browser, running and I click on the notification. This click takes me to activity A, but clicking on the BACK button - that is the issue - takes me to the home screen. Instead, I want to resume the previously running activity, i.e., the web browser.
Does anybody know how to do that?
private void initNotification(){
Intent resultIntent = new Intent(this, AudioPlayerActivity.class);
//resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AudioPlayerActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
stackBuilder.getIntents();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(...);
mBuilder.setContentTitle("...");
mBuilder.setContentText("...");
mBuilder.setContentIntent(resultPendingIntent);
// create a notification manager that then displays the notification
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
Your problem is the use of
TaskStackBuilder
. Unfortunately, this class makes a lot of assumptions about how you want your application managed. When you useTaskStackBuilder
to construct anPendingIntent
stack, it adds the following flags to the "root"Intent
:(NOTE: This code snippet is from the source for for
TaskStackBuilder
in Android 4.1.1)Since
Intent.FLAG_ACTIVITY_TASK_ON_HOME
is set, it launches your task on top of the HOME screen instead of launching it on top of the user's current task.If you can avoid using
TaskStackBuilder
, you can get around this problem. If you really need to build an activity stack, you can usePendingIntent.getActivities()
, where you can control which flags are set in eachIntent
. Otherwise, just usePendingIntent.getActivity()
to create thePendingIntent
that you put in theNotification
.NOTE: Edit to add example code
Try this: