Android Splash Screen Example

Android splash screen is a popular screen effect in app development. It is always used in below two scenarios.

  1. Show app logo or company info in several seconds when the app initialize. The splash screen show time is fixed in this case.
  2. Show something when the app load data from a web server in the network. The splash screen show time is always uncertain in this case.

This article will show you two examples about how to implement splash screen in above cases.

1. Android Splash Screen Example Files Introduction.

There are six files in this splash screen example.

  1. activity_splash_screen.xml : This is the layout file which is used to show splash screen UI. It contains only one ImageView UI component.
    <ImageView
        android:id="@+id/splashImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/img1" />
  2. img1 : The splash screen display image. Read How To Add Images In Android Studio Drawable Folder to learn more.
  3. activity_splash_screen_main.xml : This layout file contains a TextView ui component which will be shown in the main screen after the splash screen display.
    <TextView
        android:id="@+id/textView12"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome to app main activity."
        android:gravity="center_horizontal"
        android:textSize="20dp"
        android:textColor="@color/colorRed"/>
  4. SplashScreenActivity.java : This is the splash screen activity class, it contains the main java code which will implement splash effect. We will focus on this class later.
  5. SplashScreenMainActivity.java : This is the main activity java class that execute after splash screen.
  6. AndroidManifest.xml : This is the manifest xml file which contains activity configuration info.
    <activity android:name=".SplashScreenActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SplashScreenMainActivity"></activity>

1. Show Splash Screen In Fixed Time.

To show the splash screen in certain duration. We use Handler.postDelayed(Runnable runnableObj, long milliSeconds) method. Please see private void splashScreenUseTimer(long milliSeconds) method and it’s comments in SplashScreenActivity.java for more detail.

READ :   Android Change Orientation Without Restarting Activity Example

android splash screen example fix load time

2. Show Splash Screen In Uncertain Time.

This example use android.os.AsyncTask to simulate a network data retrieval process. The wait time is uncertain. And the splash screen will be shown until the data load complete. Please see private void splashScreenUseAsyncTask() method and it’s comments in SplashScreenActivity.java for more detail.

android splash screen example uncertain load time

3. SplashScreenActivity.java

package com.dev2qa.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

public class SplashScreenActivity extends AppCompatActivity {

    private float imageAplha = 1f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        //splashScreenUseTimer(5000);

        splashScreenUseAsyncTask();
    }

    // Show splash screen in fixed time.
    private void splashScreenUseTimer(long milliSeconds)
    {
        // Get splash image view object.
        final ImageView splashImageView = (ImageView)findViewById(R.id.splashImage);

        // Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
        CountDownTimer countDownTimer = new CountDownTimer(milliSeconds, 100) {
            @Override
            public void onTick(long l) {
                // Reduce the splash screen background image's alpha value for each count down.
                splashImageView.setAlpha(imageAplha);
                imageAplha -= 0.1;

                if(imageAplha <= 0)
                {
                    imageAplha = 1;
                }
            }

            @Override
            public void onFinish() {
                // When count down complete, set the image to invisible.
                imageAplha = 0;
                splashImageView.setAlpha(imageAplha);
            }
        };
        // Start the count down timer.
        countDownTimer.start();

        // Create a new Handler object.
        Handler splashScreenHandler = new Handler();
        // Create a thread object.
        Runnable splashScreenThread = new Runnable() {
            @Override
            public void run() {
                // Start SplashScreenActivity.
                Intent mainIntent = new Intent(SplashScreenActivity.this,
                        SplashScreenMainActivity.class);
                SplashScreenActivity.this.startActivity(mainIntent);
                // Close SplashScreenActivity.
                SplashScreenActivity.this.finish();
            }
        };
        // Execute splashScreenThread after 5 seconds.
        splashScreenHandler.postDelayed(splashScreenThread, milliSeconds);
    }


    // Show splash screen until network load data complete.
    private void splashScreenUseAsyncTask()
    {
        // Create a AsyncTask object.
        final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
        retrieveDateTask.execute("", "", "");

        // Get splash image view object.
        final ImageView splashImageView = (ImageView) findViewById(R.id.splashImage);

        // Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
        CountDownTimer countDownTimer = new CountDownTimer(5000, 100) {
            @Override
            public void onTick(long l) {
                // Reduce the splash screen background image's alpha value for each count down.
                splashImageView.setAlpha(imageAplha);
                imageAplha -= 0.1;

                if(imageAplha <= 0)
                {
                    imageAplha = 1;
                }
            }

            @Override
            public void onFinish() {
                // When count down complete, set the image to invisible.
                imageAplha = 0;
                splashImageView.setAlpha(imageAplha);

                // If AsyncTask is not complete, restart the counter to count again.
                if(!retrieveDateTask.isAsyncTaskComplete()) {
                    this.start();
                }
            }
        };
        // Start the count down timer.
        countDownTimer.start();
    }

    // This is the async task class that get data from network.
    private class RetrieveDateTask extends AsyncTask<String, String, String>{

        // Indicate whether AsyncTask complete or not.
        private boolean asyncTaskComplete = false;

        public boolean isAsyncTaskComplete() {
            return asyncTaskComplete;
        }

        public void setAsyncTaskComplete(boolean asyncTaskComplete) {
            this.asyncTaskComplete = asyncTaskComplete;
        }

        // This method will be called before AsyncTask run.
        @Override
        protected void onPreExecute() {
            this.asyncTaskComplete = false;
        }

        // This method will be called when AsyncTask run.
        @Override
        protected String doInBackground(String... strings) {
            try {
                // Simulate a network operation which will last for 10 seconds.
                Thread currTread = Thread.currentThread();
                for (int i = 0; i < 10; i++) {
                    currTread.sleep(1000);
                }
            }catch(Exception ex)
            {
                ex.printStackTrace();
            }finally {
                return null;
            }
        }

        // This method will be called after AsyncTask run.
        @Override
        protected void onPostExecute(String s) {
            // Start SplashScreenMainActivity.
            Intent mainIntent = new Intent(SplashScreenActivity.this,
                    SplashScreenMainActivity.class);
            SplashScreenActivity.this.startActivity(mainIntent);
            // Close SplashScreenActivity.
            SplashScreenActivity.this.finish();
            this.asyncTaskComplete = true;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.