How to stop Handler Runnable?
Asked Answered
D

4

43

I am using a handler in the following program and I want to stop it when i=5 but the handler doesn't stop and run continuously.

   b1.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            handler = new Handler();
           runnable = new Runnable() {
                 public void run() {

                    try {
                        Toast.makeText(getApplicationContext(), "Handler is working", Toast.LENGTH_LONG).show();
                        System.out.print("Handler is working");

                       if(i==5){
                           //Thread.currentThread().interrupt();
                            handler.removeCallbacks(runnable);


                            System.out.print("ok");
                                        Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
                        }
                       i++;
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
                   handler.postDelayed(this, 5000); 

               }
           };
           handler.postDelayed(runnable, 5000);
           //return;
        }
    });
Despond answered 7/9, 2013 at 7:48 Comment(4)
you already have this handler.removeCallbacks(runnable); developer.android.com/reference/android/os/Handler.htmlVaud
you can also use a count down timer a handler or a timer taskVaud
possible duplicate of cancelling a handler.postdelayed processCosgrove
Stop Runnable Thread https://mcmap.net/q/382872/-android-how-do-i-stop-runnableCorrody
R
60

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); 
    }
});
Revile answered 7/9, 2013 at 8:1 Comment(5)
can you please just explain why did you write handler.postDelayed(runnable, 5000); two timesNewtonnext
@AjitDubey May be latest edit will help you understand better.Revile
@M-WaJeEh- As I understand first postDelayed(runnable, 5000) will start after 5 Sec and other one( which is inside run method) start counting interval of 5 sec. am I right?Newtonnext
yes, first postDelayed is to initiate runnable which continues to run until ``i==5` is true.Revile
Some help with this :#40955445 pleaseRottweiler
P
27
protected void onStop() {
    super.onStop();
    handler.removeCallbacks(runnable);
}

you can stop it like this

Psi answered 7/9, 2013 at 7:49 Comment(1)
Stop Runnable Thread https://mcmap.net/q/382872/-android-how-do-i-stop-runnableCorrody
G
1

Just saw this question. I would use CountDownTimer() instead. Run it for 5 seconds total and every second:

new CountDownTimer(5000, 1000) {
    public void onTick(long milsecRemain) {
        // Code to run every second
        Log.i("Seconds left", String.valueOf(milsecRemain/1000));
}
    public void onFinish() {
        // 10 seconds have passed
    }
}.start();
Galingale answered 29/12, 2018 at 21:35 Comment(0)
E
0

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 whatever
finish();
}


private void  RunProcess()
{
   // action that i do when tick 
// time to leave or stop
bFlagForceExit = 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);        }
};
Envoi answered 28/2, 2015 at 0:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.