androidback-stackandroid-task

FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK acts weird


I've been testing the intent flags but I need to clarify something. I have two items in my navigation drawer and on click I do this,

Intent intent = new Intent(this, activityClazz);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

which classes are activities with same navigation drawers. -No fragment is used for various reasons-. In those activities I have buttons which open same activities but without the intent flags. What I wanted to do is to navigate activities with default Android behavior but also stack them in different stacks according to navigation items, like a tab usage.

Test case:

  1. startActivity without the clear-new flag
  2. startActivity with the clear-new flag
  3. back

I expect to return to the first activity since I started the second one with a new task, so the first one should have stayed in the first stack) but I found out that the first one already destroyed.


Solution

  • The first activity (the one started without the flags) is destroyed because the flag combination for your second activity does the following:

    1. FLAG_ACTIVITY_NEW_TASK: Start the activity in a new task OR if the activity already exists bring its task to the foreground. In our case, it does not exist yet. If you would only use this flag, then you would have task1 with activity1 and task2 with activity two. If you not hit the back button, task2 and activity 2 are dismissed and you return back to task1 and activity1.
    2. FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK: The clear task flag now enforces that if a task is brought to the front by new task then it is first cleaned (activities are finished). Citing the documentation:

    If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

    In conjunction, this means that with the back button you bring task1 with activity1 to the front, BUT the clear flag immediately finishes activity1. So this is why you encounter activity1 as being finished already.