Question

I thought when I exit the app on the device and it is not visible anymore in the taskmanager the app would restart from the very beginning when I start it again.

But for some reason my app keeps some variables from the previous run and does not really restart correctly.

This happens only if restarted on the device itself. Restarting with Eclipse starts the app correctly from the very start initializing all variables.

Why is this? Is my assumption wrong that when exiting the app all classes and variables will be destroyed?

Many thanks

Was it helpful?

Solution

Well, it's more complicated than just that.

First of all, you will not see the normal Android application lifecycle when you're running it in the debugger. Killing and restarting the app will indeed start you from the beginning. The normal Android app lifecycle is not very intuitive to developers, though. Normally, if a user 'backs' out of an app to the Android home-screen, one would expect your app to be killed once there are no Activities alive. This is not the case. The Android OS will keep your application alive in memory until memory pressure causes it to release the app. This is done because if the user 'opens' the application again, it will start up much, much faster. I'll point out that your Application's onDestroy() method will actually never be killed, because that surprises some developers too.

If, however, you still have Activities alive, but they are in the background, and the Android needs memory, it will kill your activities, but will call onSaveInstanceState before doing so. This will give your Activity an opportunity to save its state in a Bundle, and in fact, most of this will be done for you by the default implementation. At this point, if all of your Activities are killed, your application will be killed, but the Android will still hold onto the saved state and from the user's point of view, the application is still alive (it will still show up in the list of active applications). When the user returns to the application, the Android will re-construct the top-most Activity (onCreate will be called, but with the Bundle that contains the contents that were saved with onSaveInstanceState) and display it to the user. As the user pops Activities off the stack again, the ones below will be re-constructed, etc, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top