Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do people like to pair CLEAR_TOP and SINGLE_TOP in android

The flag FLAG_ACTIVITY_CLEAR_TOP finds the task containing activity X and clears the top to bring X to its resume state. The flag FLAG_ACTIVITY_SINGLE_TOP, would only keep a single instance of X at the top. Therefore, I should never need to include SINGLE_TOP if I am already using CLEAR_TOP: that's because CLEAR_TOP's behavior includes SINGLE_TOP's behavior. So why do so many sample codes include the two together? Is it because those developers don't understand the full power of CLEAR_TOP? Again, almost every example I see online includes the two together. Why the redundancy?

For example if I call CLEAR_TOP for X on the task W->X->Y->Z, then I get W->X. On the other hand, if I were to call SINGLE_TOP for X on the task W->X->Y->Z I would end up with W->X->Y->Z->X and if I were to call it for Z I would get W->X->Y->Z. So really CLEAR_TOP adds nothing to the equation: it's like adding 0 to some other value.

like image 614
Katedral Pillon Avatar asked Aug 10 '15 18:08

Katedral Pillon


1 Answers

The behaviour of CLEAR_TOP is different, depending on whether or not the Activity is a singleTop activity or the flag SINGLE_TOP is also provided.

Let's first assume that the Activity has a standard launch mode (not singleTop). If you use the CLEAR_TOP flag without SINGLE_TOP, Android does the following:

  • Clears the Activity stack back to (and including) the target Activity (by finishing all activities in the stack that were on top of target activity and finishing the existing instance of the target activity).
  • Creates a new instance of the target Activity and calls onCreate() on that instance.

Instead, let's assume that the Activity still has a standard launch mode (not singleTop). If you use the CLEAR_TOP flag together with the SINGLE_TOP flag, Android does the following:

  • Clears the Activity stack back to (but NOT including) the target Activity (by finishing all activities in the stack that were on top of the target activity).
  • Calls onNewIntent() on the existing instance of the target Activity, passing the Intent that was used in the startActivity() call.

As you can see, the behaviour is different.

NOTE: If the target Activity is declared as launchMode="singleTop" in the manifest, then the behaviour of using CLEAR_TOP should be the same as if you also specified SINGLE_TOP. However, there are some bugs in Android related to this (I can't find the links at the moment). So you shouldn't rely on the launchMode setting, but always specify SINGLE_TOP flag if you want the existing instance of the target Activity NOT to be recreated.

like image 173
David Wasser Avatar answered Oct 14 '22 15:10

David Wasser