How to cancel an Handler?

Asked

Viewed 149 times

2

I have this Code

final Handler handler = new Handler();
final Runnable r = new Runnable() {
                public void run() {
                    if (garagem.isChecked()!= luzgaragem){
                        garagem.setChecked(luzgaragem);
                        //Quando chegar aqui parar tudo

                    }else {
                        handler.postDelayed(this, 1000);
                        System.out.println("estou aqui");
                    }
                }
            };
            handler.postDelayed(r, 1000);

How can I create a loop and stop it when give if true ??

1 answer

2

You can use the following code within the run():

while(true) {
  if(garagem.isChecked() != luzgaragem) {
    garagem.setChecked(luzgaragem);
    wait(); //Quando quiser que ele volte a executar, basta executar um notify ou notifyAll
  } else {
    handler.postDelayed(this, 1000);
    System.out.println("estou aqui");
  }
}
  • I also managed with this command Handler.removeCallbacksAndMessages(null);

  • 1

    @With this line, the change is irreversible. Using my example, it is reversible.

Browser other questions tagged

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