Android do not keep activities

Android-do-not-keep-activities-featured.jpg

I have an application which has two Activities, let’s call them A and B. A is the initial Activity, and B is the second Activity. Once B is started, I do not want the activity to be destroyed until the application stops running, since B sets up an external network connection.

What I want is for people to enter the Activity at A, press the widget, and go to B, i.e. A -> B. If they press the back button on B, I do not want B destroyed. I don’t care if A is re-created or not, although by default it is not. The current activity is now A, if people press the widget to go to B, I want them to re-enter the existing B activity with the open network connection. If they press back again, I want them to go to the A activity. Now in A, if they press back, I want all activities in the application to close.

I have gotten somewhere with this in terms of creating an onBackPressed() method in B (so that the B activity is not destroyed when going to A). Also, adding the Intent flag “FLAG_ACTIVITY_REORDER_TO_FRONT” to the intent in A which calls B prevents B from being re-created when I call it a second time from A, although this may not be the best way.

To reiterate what I do:

Enter application at Activity A.
Press widget in A which opens Activity B.
Press back button in B to open Activity A. This should not close B, but put it on the stack.
Again in A. I press the widget for B. This should open up the existing B activity.
Now in B I press back to get to A.
Press back in A to exit the application.

The program flow is [Home screen] -> Activity A -> Activity B. Back keys will reverse this flow.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>