0
votes

Essentially I have a runnable switching between two activities. I have a timer in onCreate runnable that is set to 0 milliseconds in the main activity which immediately switches to the splash screen. The splash screen is simply an imageview which then switches right back after 3000 milliseconds using a similar runnable.

My questions is this; can I simplify the code on the main activity, and do I really need the .postdelayed if I want to load SplashScreen.activity immediately?

If the delay is not necessary, how would I properly get rid of it so that the app immediately loads the splashscreen?

The main activity:

        /*
        SPLASH SCREEN
        */

        splashScreenRun = settings.getBoolean("splashScreenRun", splashScreenRun);

        if (splashScreenRun == true) {

            settings.edit().putBoolean("splashScreenRun", false).commit();

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    Intent splashIntent = new Intent(MainActivity.this, SplashActivity.class);
                    startActivity(splashIntent);
                    finish();

                }

            },0);

        }
        else {

            settings.edit().putBoolean("splashScreenRun", true).commit();

        }

        //END

And then the SplashScreen:

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

        //splash screen
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run(){

                Intent splashEndIntent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(splashEndIntent);
                finish();

            }

        },splashTimeout);
        //end splash screen
1
you can use onStart() for this and it is not necessary to use postdelayed. - Aniruddh Parihar

1 Answers

0
votes

First of all never use anonymous handlers. Use a handler object.

Handler handler = new Handler();
   runnable = new Runnable() {
   @Override
   public void run() {    
       startActivity(new 
       Intent(SplashActivity.this, MainActivity.class));                            
       overridePendingTransition(R.anim.right_in, R.anim.right_out);                                        
       finish();                             
         }};
    handler.postDelayed(runnable, 3000);

And in on destroy

@Override
protected void onDestroy() {
    super.onDestroy();
    handler.removeCallbacks(runnable);
}

This will prevent the app from crashes if the user close the app directly from task manager.

OR

You should use

runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    //Do your stuff here.
                    }
                });

Hope this helps.