Android - Run function with seconds of delay

1

My question is: how do I make one function run 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);   
}
    
asked by anonymous 28.05.2018 / 13:46

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 wait in milliseconds.

    
28.05.2018 / 13:54