HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Android splash screen

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
splashscreenandroid

Problem

I have implemented a splash screen, to hold/pause the screen for few seconds and then launch the next screen. I am very enthusiastic to know if there is a more basic way to write the code.

public class SplashActivity extends BaseActivity {

    private final int SPLASH_TIME_OUT = 2000;

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

        Thread splashTimerThread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(SPLASH_TIME_OUT);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                } finally {
                    Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
                    startActivity(intent);
                }
            }
        };
        splashTimerThread.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}

Solution

Using a thread for a SplashScreen is fine, however a much cleaner solution would to use a Handler as below...

public class SplashActivity extends BaseActivity {

    private final static int SPLASH_TIME_OUT = 2000;

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        }, SPLASH_TIME_OUT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}


Your SPLASH_TIME_OUT constant should be declared static.

Code Snippets

public class SplashActivity extends BaseActivity {

    private final static int SPLASH_TIME_OUT = 2000;

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        }, SPLASH_TIME_OUT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}

Context

StackExchange Code Review Q#128420, answer score: 6

Revisions (0)

No revisions yet.