How to return to the latest launched activity when re-launching application after pressing HOME? How to return to the latest launched activity when re-launching application after pressing HOME? android android

How to return to the latest launched activity when re-launching application after pressing HOME?


    @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {         // Activity was brought to front and not created,         // Thus finishing this will get us to the last viewed activity         finish();         return;     }     // Regular activity creation code... } 


Oh, I think I've found the answer.

Because I was launching the app by using IntelliJ, it seems it launches the application in a different way than a user, clicking a home screen widget, would launch. It's explained in the answer to another SO question:

This is due to the intents being used to start the app being different. Eclipse starts an app using an intent with no action and no category. The Launcher starts an app using an intent with android.intent.action.MAIN action and android.intent.category.LAUNCHER category. The installer starts an app with the android.intent.action.MAIN action and no category.

Ref: App always starts fresh from root activity instead of resuming background state (Known Bug)

So I've manually killed the application in the phone, and relaunched it again from the home screen widget. Then opened the GameActivity, and pressed HOME. Now, when relaunching it the GameActivity is still visible and keeping its UI state as it was when I left it.

And I guess that the reason why a new instance of the activity was created when pressing the shortcut before was due to a different Intent being used for starting the activity.


The simplest solution is to write a preference out during onPause or serialize your state out to a persistent file and then read this file during onResume in your main entry point Activity. This activity would rebuild the application state and re-launch the correct activity.

You're seeing this because you app may be killed by the OS on exit. You never know for sure so if you want true persistence of usage, ie go back to the last activity no matter what, you need to write your state to a persistent store.