0

Is it possible to stop the handler while counting 6 seconds? That the toast does not appear For example, I want the handler not to work in 3 seconds and the toast not to appear, then go to the second activity in 3 seconds. Thanks for the help friends

final Handler h= new Handler();
    h.postDelayed(new Runnable(){
        @Override
        public void run() {
            Toast.makeText(Ab.this, "finish 6 seconds", Toast.LENGTH_SHORT).show();
        }
},6000);
Ivan Barayev
  • 2,035
  • 5
  • 24
  • 30
sara
  • 9
  • 2
  • Does this answer your question? [How to remove all callbacks from a Handler?](https://stackoverflow.com/questions/5883635/how-to-remove-all-callbacks-from-a-handler) – Chisko Jan 29 '21 at 03:22

2 Answers2

1

You can use h.removeCallbacksAndMessages(null);.

Dilshod
  • 147
  • 4
  • 12
0

How to stop Handler in Android

Though I would not use a handler for this, but more likely a CountDownTimer. It is easier to understand.

int time = 6000;

new CountDownTimer(time, 1000) {

    public void onTick(long millisUntilFinished) {
        if(millisUntilFinished == 3000) {
            Toast.makeText(Ab.this, "finish 3 seconds", Toast.LENGTH_SHORT).show();
        }
    }

    public void onFinish() {
        Toast.makeText(Ab.this, "finish 6 seconds", Toast.LENGTH_SHORT).show();
    }
}.start();
FunnyO
  • 383
  • 2
  • 20