Go back to previous screen on backbutton pressed a

2019-02-20 08:15发布

问题:

I am using code similar to Creating a simple notification to create and show a notification from a network call.

The issue is that I want the activity that responds to the notification to do it's business and then on a backbutton click, put the previously active activity back in the foreground, with it's back stack intact. This is regardless of if the previously active activity was part of my app or somebody elses.

Currently it is following the generated TaskStackBuilder. Leading it back up the app hierarchy and out to the home screen. This is bad UI-design as it breaks the work-flow of anyone using the device, forcing them to manually go back to their app and spending more buttonclicks than necessary. It is also rather unintuitive.

According to the official desing guidelines this is how it should work. The implementation I linked to higher up makes back button have the same functionality as up button should have

It is also a common way to implement it in a plethora of other apps, including official google ones (google-play update notifications come to mind), so there must be a relatively standard way to do this.

回答1:

Intent intent = new Intent(getApplicationContext(), MainActivity.class)
//add Intent.FLAG_ACTIVITY_CLEAR_TASK flag this will clear all activitys and 
//launched activity at top. Means no other activity of this application will be running
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
     or
// add Intent.FLAG_ACTIVITY_MULTIPLE_TASK which start one more task your applications 
//   where activity will not be cleared;
  .addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
  PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
  Notification n  = new Builder(context.getApplicationContext())
                 .setContentTitle("simple notification title")
                 .setContentText("simple message")
                 .setContentIntent(pendingIntent)
                 .setAutoCancel(true)
                 .addAction(R.drawable.ic_launcher, "And more",pendingIntent ).build();


  NotificationManager notificationManager =(NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                                           notificationManager.notify(0, n);