java – Switching to another Activity after 5 seconds

Question:

Hello. I want to make something like a splash screen in the application. The user enters the application, the first Activity opens for him, and after 5 seconds he throws it to another.

I do this:

int ii = 0;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setContentView(R.layout.fon);

    try {

        TimeUnit.SECONDS.sleep(5);
        ii = 5;

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block

        e.printStackTrace();

    }

    System.out.println(ii);

    if (ii == 5) {
    Intent intent2 = new Intent(this, Web.class); 
    startActivity(intent2);
    }

}

And the result is the following: The user enters the application, he sees the first Activity and after 5 seconds another activity opens. But the problem is that on the first activation it does not see the screen, that is, setContentView(R.layout.fon); does not work setContentView(R.layout.fon);

What am I doing wrong? I would be grateful for your help!

Answer:

You paused the main thread with the line

TimeUnit.SECONDS.sleep(5);

So you should have crashed by ANR

There is no need to stop the main thread. This is bad practice. You need to do otherwise – start the pending task in one of many ways, for example, like this:

Thread thread = new Thread() {
    @Override
    public void run() {
        try {
             TimeUnit.SECONDS.sleep(5);
             Intent intent2 = new Intent(ТУТ_ИМЯ_КЛАССА_АКТИВИТИ.this, Web.class); 
startActivity(intent2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();
Scroll to Top