Search code examples
androidscreensplash-screen

Best way to have a splash screen in an Android application?


I need a splash screen for my application. Tried creating an activity having the image for my splash screen; and tried using for loop and the Timer class for introducing a time delay. But it din't work that way. Am I doing it wrong; if yes, what is the right way?


Solution

  • The above solutions are good, but what if the user presses the back-key (and closes your app) before the splash-delay is over. The app will probably still open the next Activity, which isn't really user-friendly.

    That's why I work with a custom Handler, and remove any pending messages in onDestroy().

    public class SplashActivity extends Activity
    {
        private final static int MSG_CONTINUE = 1234;
        private final static long DELAY = 2000;
    
        @Override
        protected void onCreate(Bundle args)
        {
            super.onCreate(args);
            setContentView(R.layout.activity_splash);
    
            mHandler.sendEmptyMessageDelayed(MSG_CONTINUE, DELAY);
        }
    
        @Override
        protected void onDestroy()
        {
            mHandler.removeMessages( MSG_CONTINUE );    
            super.onDestroy();
        }
    
        private void _continue()
        {
            startActivity(new Intent(this, SomeOtherActivity.class));
            finish();
        }
    
        private final Handler mHandler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                switch(msg.what){
                    case MSG_CONTINUE:
                        _continue();
                        break;
                }
            }
        };
    }