Neil Axinto Neil Axinto - 3 months ago 15
Android Question

Android - resuming activities without killing previous activity

I want to know how to switch between 2 activities without killing any of the 2 activities, So that I can resume it's state.
I tried this:

Activity1.class

Intent i=new Intent(this,Activity2.class)
startActivity(i);


Activity2.class

Intent i=new Intent(this,Activity2.class)
startActivity(i);


This codes just creates another activity and destroys the previous activity when I press back button. What I need is how can I switch activities while pausing the previous and resume to the previously paused activity without killing the activity I'm at.

Answer

You can use FLAG_ACTIVITY_REORDER_TO_FRONT, and if you already have an instance of the activity it will bring it to front and call its onResume().
The if is because Android can kill your background activity any time if the system lack of resources.

Intent i=new Intent(this,Activity2.class)
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);

Also check FLAG_ACTIVITY_PREVIOUS_IS_TOP, depends on your app logic.