Ronen Yacobi
Ronen Yacobi

Reputation: 844

Android activity lifecycle - activity restarts when coming from history

I have a splash activity (A) that calls a listview activity (B) which calls another activity (C). When I'm on activity C and I press Home, than kill the app (or wait of Android to do it), than longpress Home and come back to activity C there's a strange problem: When I click back I go back to B. Than I have a backbutton handler that asks the user if they want to exit and calls finish() on the activity. When I try to exit in this scenario, activity A starts again.

On regular operation it finishes B and doesn't go back to A. Why is that??

Thanks

Upvotes: 0

Views: 265

Answers (2)

David Wasser
David Wasser

Reputation: 95578

When the app is killed (either by you or by Android) the process hosting your applications is killed. However, Android remembers the state of the activity stack (in your case A->B->C).

When the user returns to the app, Android creates a new process for the app and recreates only the activity that was at the top of the activity stack (in this case: C). Now the user presses BACK, which causes activity C to finish and Android recreates the instance of activity B which is then shown (You will see calls to B.onCreate(), B.onStart() and B.onResume()).

Now the user presses BACK again. Your back button handler tries to call finish() on activity A, but there is no instance of activity A. Android hasn't created it yet! When activity B finishes Android remembers that there was an instance of activity A in the activity stack underneath B so it recreates the instance of activity A which is then shown (You will see calls to A.onCreate(), A.onStart() and A.onResume()).

I hope this explains what you are seeing.

Upvotes: 1

Mimminito
Mimminito

Reputation: 2843

Make sure you are calling finish() on A when you load B

Upvotes: 1

Related Questions