How to stop Handler Runnable? How to stop Handler Runnable? multithreading multithreading

How to stop Handler Runnable?


Because you call postDelayed() again after removing call backs. Please use this code:

final Handler handler = new Handler();final Runnable runnable = new Runnable() {         public void run() {               Log.d("Runnable","Handler is working");               if(i == 5){ // just remove call backs                    handler.removeCallbacks(this);                     Log.d("Runnable","ok");                } else { // post again                    i++;                    handler.postDelayed(this, 5000);                 }       }   };//now somewhere in a method b1.setOnClickListener(new OnClickListener() {    public void onClick(View v) {        handler.removeCallbacks(runnable);         handler.postDelayed(runnable, 5000);     }});


protected void onStop() {    super.onStop();    handler.removeCallbacks(runnable);}

you can stop it like this


I found a solution which works for me. This is an example of code, where I expect a timer stop, but I saw it was alive, even if I was out of activity:

boolean bFlagForceExit = false; Handler timerHandler = new Handler();private   Runnable timerRunnable = new Runnable() {    @Override    public void run() {        if  (bFlagForceExit )    MyProcessForExit();         if (bSomeflagForRunAction)            RunProcess();        timerHandler.postDelayed(this, MILISEGUNDOS_ESPERA);        }};private void  MyProcessForExit(){    timerHandler.removeCallbacks(timerRunnable);// close activity or whateverfinish();}private void  RunProcess(){   // action that i do when tick // time to leave or stopbFlagForceExit = true;}

Then I found that this works if removeCallbacks(timerRunnable) was called for other threads, so, I solved the problem like this.

boolean bFlagForceExit = false; Handler timerHandler = new Handler();private   Runnable timerRunnable = new Runnable() {    @Override    public void run() {        if  (bFlagForceExit )        {    // add a thred for run your stop handler            new Thread(new Runnable() {                public void run() {                    SalirDeProceso();                }            }).start();        }        if (bSomeflagForRunAction)            RUnProcess();        timerHandler.postDelayed(this, MILISEGUNDOS_ESPERA);        }};