Search code examples
androidandroid-intentandroid-activity

FLAG_ACTIVITY_CLEAR_TOP and android:launchMode="singleInstance"


I think I've just found a really strange bug... But it can just be somekind of feature that I never heard of.

On my application if I have any Activity on the AndroidManifest with android:launchMode="singleInstance" when you try to "clean" the stack to a certain point with the following code:

    Intent intent = new Intent(this, Xpto.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

It goes to that activity. But when you press back, it returns to the previous.that should have been finished...

Example:

A -> B -> C

Then from C I call A with Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP having A singleInstance on the Manifest. It goes to A but it only brings it to front. And does not finishes C and B.

Can somebody explain this behaviour?

The Xpto class I'm calling is at the time the root activity of the stack.


Solution

  • from reading this thread:

    http://groups.google.com/group/android-developers/browse_thread/thread/5eb400434e2c35f4

    it seems that:

    "The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent(). "

    which means that you need to set your launchMode to multiple instance, and use only FLAG_ACTIVITY_CLEAR_TOP.

    Intent intent = new Intent(this, Xpto.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    

    In the scenario you described, activity's B and C are not finished when you start activity A (which is the root activity). The documentation describes that with launch mode of singleInstance and the flag FLAG_ACTIVITY_SINGLE_TOP set, activities B and C will NOT be finished. If you want to have activities B and C finished, then you must set the launch mode to multiple instance and NOT set the flag FLAG_ACTIVITY_SINGLE_TOP.