Android - Run function with seconds delay

Asked

Viewed 83 times

1

My question is: how do I get one function to run seconds after another?

Mainactivity.class

public void onClick(View p1){
    //quero que essa função seja executada primeiro
    Toast.makeText(getApplicationContext(), "Toast 1", Toast.LENGTH_SHORT).show();

    //e essa dois segundos depois

    Intent it = new Intent(MainActivity.this, SecondActivity.class);
    startActivity(it);   
}

1 answer

3


You can use postDelayed:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent it = new Intent(MainActivity.this, SecondActivity.class);
        startActivity(it);
    }
}, 1000);

If you are using Java 8:

final Handler handler = new Handler();
handler.postDelayed(() -> {
    Intent it = new Intent(MainActivity.this, SecondActivity.class);
    startActivity(it);
}, 1000);

1000 is the time to be expected in milliseconds.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.