Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
Caffeinated Coder Avatar asked Sep 13 '12 15:09

Caffeinated Coder


2 Answers

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;
            }
        }
    };
}
like image 164
Jelle Avatar answered Nov 15 '22 16:11

Jelle


Try this

public class SplashActivity extends Activity {
    Handler handler;
    private long timeDelay = 2000; //2 seconds
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.SplashLayout);
        final Intent i = new Intent(this, Landing.class);
        handler = new Handler(); 
        handler.postDelayed(new Runnable() { 
             public void run() { 
                 startActivity(i); 
                 finish();
             } 
        }, timeDelay); 
    }      
}
like image 36
Feona Avatar answered Nov 15 '22 17:11

Feona