Search code examples
javaandroidmultithreadingthread-sleep

Thread within a Splash Screen


package com.example.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class Splash extends Activity {
    private Intent myintent;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        myintent = new Intent(this, MainActivity.class);
        splashScreen(1000); }

    public void splashScreen (final int x)
    {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(x);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                startActivity(myintent);
                finish();
            }
        }).run();
    }

}

There's the code, and here is the problem : the SplashScreen do not get the content view of the splash XML layout file... Now, I have my suspicions that it is a thread problem and that somehow the thread is executed before the setContentView method although that method is located before the run method of the Thread in code, so it's illogical that I'm thinking this way but I'm like running out of reasons for this Splash Screen not to work


Solution

  • Change thread.run() to thread.start(): http://www.javafaq.nu/java-article1131.html

    new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(x);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                startActivity(myintent);
                finish();
            }
        }).start();
    

    A better way to implement Splash:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
    
        myintent = new Intent(this, MainActivity.class);
    
       new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                startActivity(myintent);
                finish();
            }
        }, 1000);
    }