Search code examples
javaandroidmultithreadinghandlerrunnable

SetContentView does not work while I'm using handler


I am trying to make app sleep using Thread. I have got 2 solutions but one of them causes a problem.

This is a shorter code which works perfectly:

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

        final Handler goToMenu = new Handler();

        goToMenu.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(getApplicationContext(), Menu.class);
                startActivity(i);
            }
        },5000);
}

But this one is problematic. When I put the time in millis to make app wait it works and the second Activity starts but the R.layout.welcome does not appear. The app just waits with a gray background until the startActivity(i) gets executed.

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

        final Handler goToMenu = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {

                Intent i = new Intent(getApplicationContext(), Menu.class);
                startActivity(i);
            }
        };

        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (this) {
                        wait(5000);
                    }

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    Log.d(TAG, "Waiting didnt work!!");
                    e.printStackTrace();
                }
                goToMenu.sendEmptyMessage(0);

            }

        };

        Thread waitThread = new Thread(run);
        waitThread.run();

What is wrong?


Solution

  • To start a new thread, use Thread#start() and not Thread#run().

    run() just executes the Runnable synchronously i.e. blocking the current thread.