Search code examples
androidsplash-screenandroid-lifecycleapplication-lifecycle

Splash screen not relaunching when relaunching after Application memory collected


So in general the common approach to Splash Screen Activities is something like this:

public class SplashActivity extends Activity
    @override
    protected void onResume() {
    //Create a thread
     new Thread(new Runnable() {
            public void run() {
                //Do heavy work in background
                ((MyApplication)getApplication()).loadFromDb();
                startActivity(new Intent(SplashActivity.this,     MainActivity.class));
                finish(); //End this activity
            }
        }).start();
    }
}

The problem I found for this case is that when the app is in the background and it gets memmory collected, when you return it to the foreground Application.onCreate is called again, the Splash activity doesn't get called and instead whatever activity was open when the App went into background is opened. How do you make sure that in this situation the SplashScreen is the one that's launched?

Edit1: Btw, I've tried setting android:clearTaskOnLaunch="true" for the Splash Screen Activity, but that didn't seem to do anything.


Solution

  • So I've figured out a solution that works:

    Extend the Application class, add a boolean field isSplashInitialized and set it to false in Application's onStart. Then inside your Splash Activity when you're done your initialization stuff within it, before calling finish(), set Application's isSplashInitialized field to true. Then have a BaseActivity class that all your Activities extend. In it extend onCreate() and after calling super.onCreate(); do the following:

    if (!(this instanceof SplashActivity) && !MyApplication.getIntance().isSplashInitialized()) {
        Intent intent = new Intent(this, SplashActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }