Android - Clear task flag not working for PendingIntent

后端 未结 9 1968
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 10:20

    A solution in terms of intent flag would be as following:

    1. In Manifest, add launchMode:singleTask for Activity A
    2. Use the following code block:

      final Intent notificationIntent = new Intent(mContext, ActivityA.class);
      notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      PendingIntent contentIntent = PendingIntent.getActivity(myContext, 0, notificationIntent, 0);
      

    What happens here is that when Activity A is launched using notification, by the definition of Intent.FLAG_ACTIVITY_NEW_TASK, since there exists a task A>B>C containing A, this task is brought forward also destroying the activities B and C and A starts with the onNewIntent --> onRestart --> onStart --> onResume

    If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent()

    Now the reason, why it doesn't behave nicely with just the intent flags is that, the Activity A wasn't launched with singleTask mode and Android somehow doesn't maintain the state of it.

提交回复
热议问题