Title

Saturday, 7 February 2015

How to stop Handler Runnable?


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

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

 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){ // just remove call backs   handler.removeCallbacks(runnable);   System.out.print("ok");   Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();   } else { // post again   i++;   handler.postDelayed(this, 5000);   }   } catch (Exception e) {   e.printStackTrace();   }   }   };   handler.postDelayed(runnable, 5000);   }  });
Answer2
protected void onStop() {   super.onStop();   handler.removeCallbacks(runnable);  }

you can stop it like this

No comments:

Post a Comment