Reputation: 739
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:
The program flow is [Home screen] -> Activity A -> Activity B. Back keys will reverse this flow.
Upvotes: 2
Views: 2552
Reputation: 20319
Whenever an activity goes off the screen there is no way to guarantee that it won't be killed by the OS. This means two things. Any visual state that you want to persists you must keep track of yourself. You can do this with the onSaveInstanceState
and the onRestoreInstanceState
.
You mentioned that you want to open a network connection in an activity that might go off the screen. You should really consider doing this in a Service
. Services are very similar to activities except they are designed to work off screen. They are great for doing something that doesn't need user interaction.
With regards to always having the back button switch between the two activities you can do this by intercepting the back button presses in your activity and then having your app switch activities. However remember that the back button has a very specific function on android and users are accustomed to apps behaving a certain way. Try not to do anything that flies in the face of the android UX conventions. Personally I find it frustrating when apps go against conventions like using the back button to exit out of activities and return to the home screen.
Upvotes: 1
Reputation: 36302
Instead of trying to keep activity B alive, you should instead not rely on the activity to keep your network connection alive. There are several ways of handling this, including using a Service
and managing the connection from a custom Application
class. See my answer to this other post for a little more information: How to maintain Server Socket through Activities?
Upvotes: 2