Search code examples
javaandroidandroid-animationsplash-screen

How to show a Splash Screen with Animation while activity is loading in background. (Android)


The MainActivity of my Android app is takes a long time to load. So, I want to make a splash screen which will show until the MainActivity has finished loading i.e: all the work of the onCreate method of MainActivity is done, after which the Splash Screen must be closed and the MainActivity launched. Furthermore, The Splash Screen has an animation on it.

The onCreate method for the Splash Screen is:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    ImageView imageView = (ImageView) findViewById(R.id.circle);
    final Animation startRotateAnimation = AnimationUtils.loadAnimation(this, R.anim.android_rotate_animation);
    startRotateAnimation.setRepeatCount(Animation.INFINITE);
    imageView.startAnimation(startRotateAnimation);

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

            Intent i = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(i);
            // close this activity
            finish();
        }
    }, SPLASH_TIME_OUT);

}

The SplashScreen will finish in the above code after the time specified by SPLASH_TIME_OUT, which is a fixed integral constant.

and android_rotate_animation.xml is:

<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="3000"
android:startOffset="0"
/>

How should I make the SplashScreen only show until the MainActivity finishes loading?

I cannot use multiple image files for animation due to project restriction.

The SplashScreen is meant to behave like a loading screen. An animation will play on it (like a loading bar) until MainActivity has finished loading, after which MainActicity will launch.


Solution

  • To achieve this, you can either move the data-loading into your SplashScreenActivity and start the MainActivity when data is loaded, or move ahowing a Splash-View to your MainActivity, where you initially just show the Splash-View until data is loaded and then hide that view or replace it with the actual view of the MainActivty.

    EDIT I suggest, you use an AsyncTask to perform the loading asynchronously. You can update the progress bar in its onProgressUpdate() method and when work is done, in onPostExecute() you can hide the progress bar and show the normal layout.