How to stop Handler Runnable?

user2745636 picture user2745636 · Sep 7, 2013 · Viewed 70.3k times · Source

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;
        }
    });

Answer

M-WaJeEh picture M-WaJeEh · Sep 7, 2013

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); 
    }
});