Search code examples
javaandroidmultithreadingwait

How to get the activity to wait before jumping to the next activity on its own in Android?


I want to create an activity that opens when I start my app, wait some time and jumps to the next activity without the user pressing anything.

Here is my code:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Thread thread = new Thread();
    thread.start();
}

public class waitSeconds extends Thread {

    public void run() {
        Log.i("MyActivity", "MyClass");
        try {
            wait(300);
            Intent intent = new Intent(MainActivity.this, main_window.class);
            startActivity(intent);

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

As it seems that it is never going to the "run" method.

How can I do this?


Solution

  • include this in your Activity:

     public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        SplashHandler handler=new SplashHandler();
        Message msg = new Message();
        msg.what = 0;
        handler.sendMessageDelayed(msg, 3000);
    
    }
    
    private class SplashHandler extends Handler {
    
                public void handleMessage(Message msg)
                  {
                    switch (msg.what)
                    {
                    default:
                    case 0:
                      super.handleMessage(msg);
    
                      Intent intent = new Intent(MainActivity.this,main_window.class);
                      startActivity(intent);
                      MainActivity.this.finish();
                    }
                  }
            }