Android - Clear task flag not working for PendingIntent

后端 未结 9 1958
夕颜
夕颜 2020-12-17 09:34

I have a task stack of A > B > C. I am currently on C, and then I press the home button. I get a notification with the intent to take me to Activity A. I press the notificat

9条回答
  •  一向
    一向 (楼主)
    2020-12-17 10:17

    I created a demo project as your description and it works just as what you want.

    I don't know how do you get the notification, so in my project I use a BroadcastReceiver to get a Broadcast and then show the Notification in the onReceive() method of the Receiver. I think you can compare my demo with your project to find the problem. BTW, my test is performed under API 16.

    Here is my demo: https://github.com/leoguo123/AndroidDemo

    In the repository:

    Test project contains 3 Activity(A > B > C) and it can show the Notification when receive a proper broadcast. SendBroadcast project is responsible for sending the broadcast.

    The code for generating the notification:

        public class MyBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            showNotification(context);
        }
    
        private void showNotification(Context context) {
            Intent intent = new Intent(context, ActivityA.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
            NotificationManager nmr = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
            Notification.Builder builder = new Notification.Builder(context);
            builder.setContentTitle("Open A with B and C being closed");
            builder.setContentText("Open A with B and C being closed");
            builder.setSmallIcon(R.drawable.ic_launcher);
            builder.setContentIntent(pi);
            builder.setAutoCancel(true);
            Notification nt = builder.build();
            nmr.notify(0, nt);
        }
    }
    

提交回复
热议问题