Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop Handler in Android?

Tags:

android

In My Application my handler doesn't stop. How can I stop the handler?
It continues to start after closing the activity. What can i do?

the code is :

 handler = new Handler()         {             @Override             public void handleMessage(Message msg)              {                 // TODO Auto-generated method stub                 super.handleMessage(msg);                 if(i<max)                 {                     evnetChangedisplay(i);                     i++;                         handler.sendEmptyMessageDelayed(0, 5000);                     }                 else                     {                         i = 0;                         handler.sendEmptyMessageDelayed(0,0000);                     }                 }         }; handler.sendEmptyMessageDelayed(0,000); 
like image 277
Hardik Gajjar Avatar asked Apr 28 '11 13:04

Hardik Gajjar


People also ask

How do I get rid of handler on Android?

removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.

How do you stop handler threads?

postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(MapsActivity. this,MapsActivity. class); startActivity(i); finish(); } }, TIME_OUT); Then you can use Handler#removeCallbacksAndMessages to remove this or any callback.

What is a handler in Android?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .


2 Answers

It sounds like the activity finishes its lifecycle before the Handler executes the code. You can manage a handler.post(runnable) by creating an instance member for the handler and runnable, then managing the handler in the Activity Lifecycle methods.

private Handler myHandler; private Runnable myRunnable = new Runnable() {     @Override     public void run() {         //Do Something     } }; 

Start the runnable with handler.post.

protected void onStart() {     super.onStart();     myHandler = new Handler();     myHandler.post(myRunnable);  } 

If the runnable hasn't executed by the time onStop is called, we don't want to run it. Remove the callback in the onStop method:

protected void onStop() {     super.onStop();     mHandler.removeCallbacks(myRunnable); } 
like image 126
Rich Ehmer Avatar answered Oct 02 '22 11:10

Rich Ehmer


use removeCallbacks or removeCallbacksAndMessages

like image 41
twocity Avatar answered Oct 02 '22 12:10

twocity