سؤال

I have doubt with android backstack , please consider the scenario I have two activities A and B in same app ,

  1. start with A.
  2. from A launch B using FLAG_ACTIVITY_NEW_TASK
  3. from B launch A using FLAG_ACTIVITY_NEW_TASK
  4. press Back button 3 times to return to home screen.

My question is how does the backstack work with this flag , is new task created every time and previous task is pushed to background or activity is created on top of same task.

My doubt is if first one is correct then does back button really remove the activity from top of the stack and if second is correct what is the use of that flag in correct sense.

Thanks in advance.

Regards, Rohit

هل كانت مفيدة؟

المحلول

First of all, launching B using FLAG_ACTIVITY_NEW_TASK will NOT create a new task unless you have explicitly set android:taskAffinity in the manifest for B. The reason for this is that, by default, all Activities in your application have the same taskAffinity and taskAffinity overrides FLAG_ACTIVITY_NEW_TASK.

If you have set the taskAffinity of A and/or B so that they are different (or both empty), then it works like this:

  • User launches A from homescreen. You now have one task (let's call it TaskX)
  • A launches B with FLAG_ACTIVITY_NEW_TASK. You now have two tasks (let's call the new task TaskY). TaskX is pushed to the background and TaskY is in the foreground.
  • B launches A with FLAG_ACTIVITY_NEW_TASK. You still only have two tasks. B (in TaskY) launched A which created a new instance of A and put it in TaskX because the first instance of A has the same taskAffinity as the second instance of A). This also causes TaskX to come to the foreground and TaskY to go to the background.
  • Press "back". The second instance of A is removed from the stack and you go back to the first instance of A in TaskX. Pressing the "back" key goes back within the current task.
  • Press "back". The first instance of A is removed from the stack. TaskX is now empty as it has no activities in it. The previous task (TaskY) is brought to the foreground and B is resumed.
  • Press "back". The instance of B is removed from the stack. TaskY is now empty and the home screen is shown.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top