Search code examples
androidandroid-layoutandroid-intentsplash-screen

Why can't I view the splash screen?


I have the code below, which creates a splash screen. When I start my app I don't view the splash screen instead I see directly the first activity:

public class splash extends Activity {
    private static final int STOPSPLASH = 0;

    //time in milliseconds
    private static final long SPLASHTIME = 13000;

    private ImageView splash;

    //handler for splash screen
    private Handler splashHandler = new Handler() {
        /* (non-Javadoc)
         * @see android.os.Handler#handleMessage(android.os.Message)
         */
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOPSPLASH:
                    //remove SplashScreen from view
                    splash.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };  

    /** Called when the activity is first created. */
    @Override
        public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.main);        

        Intent intent = new Intent(this, prima.class);

        splash = (ImageView) findViewById(R.id.imageView1);

        Message msg = new Message();
        msg.what = STOPSPLASH;       

        splashHandler.sendMessageDelayed(msg, SPLASHTIME);        

        startActivity(intent);  
    }
}

Solution

  • You have to do startActivity() from your handler. If you do it directly you will directly switch to the next activity.

    public class splash extends Activity {
        private static final int STOPSPLASH = 0;
        // time in milliseconds
        private static final long SPLASHTIME = 13000;
        private Intent nextActivity;
    
        // handler for splash screen
        private Handler splashHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case STOPSPLASH:
                        // start next Activity
                        startActivity(nextActivity);
                        break;
                }
            }
        };
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            nextActivity = new Intent(this, prima.class);
            splashHandler.sendEmptyMessageDelayed(STOPSPLASH, SPLASHTIME);
        }
    }