You probably don’t want to restart the application from the very beginning when starting from the “recent tasks” list, because your application may work fine. What you need to do is to remember whether your application was correctly “initialized” (whatever that means. If the user returns to your application and the process has been killed and restarted since the initialization of your application, you need to detect this and then redirect the user back to the first activity of your application.
The best way to do this is to create a base class for all your activities. In this base class, you implement code in onCreate() , which checks whether your application is initialized correctly or not. If it has not been correctly initialized, you must redirect the user to the first action. Something like that:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Check if the application has been restarted by AndroidOS after it has killed the process due to inactivity // in this case, we need to redirect to the first activity and dump all other activities in the task stack // to make sure that the application is properly initialized if (!isApplicationInitialized() && !(this instanceof FirstActivity)) { Intent firstIntent = new Intent(this, FirstActivity.class); firstIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // So all other activities will be dumped startActivity(firstIntent); // We are done, so finish this activity and get out now finish(); return; } // Now call the activity-specific onCreate() doOnCreate(savedInstanceState);
All your actions should inherit from this base class, and they should NOT override onCreate() . Instead, they should implement the doOnCreate() method, which will be called from the onCreate() base class (see above).
NOTE. This only works if the root activity (in this FirstActivity example) never terminates until the application shuts down. This means that you will always have an instance of FirstActivity at the root of your task. This is necessary for Intent.FLAG_ACTIVITY_CLEAR_TOP work correctly.
David wasser
source share