Android can kill the OS process hosting your app at any time. Usually this happens when your app has been in the background for a while (ie: the user navigated away from your app to go do something else). This happens all the time.
When the user then returns to your app, Android creates a new OS process for the app, and creates a new instance of the Activity
that was on the top of the stack (ie: the Activity
that was showing on screen before the app was pushed to the background).
If you don't want this to happen, you can add the following attribute to the <activity>
declaration for SplashActivity
:
android:clearTaskOnLaunch="true"
This will force Android to always restart your app from the beginning if your user returns to it. However, this might make your users complain, because if the user is using your app, then takes a phone call, then returns to your app, it will start from the beginning again.
It is better if you detect the problem yourself, and redirect to the SplashActivity
only when necessary (ie: when your app needs to be initialized because the process has been killed and restarted). To do this, declare a static
variable named initialized
in SplashActivity
that you set to true
when your SplashActivity
has successfully initialized the app. In every other Activity
, do this in onCreate()
:
super.onCreate(savedInstanceState);
if (!SplashActivity.initialized) {
// Android killed my process, need to redirect the user to `SplashActivity`
redirectIntent = new Intent(this, SplashActivity.class);
startActivity(redirectIntent);
finish();
return;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…