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 :
Consider:
private Handler myHandler= new Handler(){
@Override
public void handleMessage(Message msg){
switch(msg.what){
case 0:
this.removeMessages(0);
messageSendingCodeWhat0();
break;
default:
super.handleMessage(msg);
break;
}
}
};
It never stops because you are always sending a message! I think you want to remove handler.sendEmptyMessageDelayed(0,0000);
, which in fact makes no sense (are you delaying a message 0 milliseconds?).
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);
}
Your Handler (if implemented like this) will be active as long as the Looper instance is active, which is for the whole life cycle of the thread (which has little to do with activity life cycle).
If you want the handler to stop re-triggering itself, you need to take care of it yourself.
Sending 0-delayed message to self looks slightly weird, anyway. What are you trying to achieve, actually?
use removeCallbacks or removeCallbacksAndMessages
A Handler is simply a interface to the event loop of a thread. So if you stop the thread then you "stop" the Handler.
assuming that your Handler is for a background thread.
Here's an example where quit() is designed to send a looper.quit() method to the event loop which will stop the thread and the Handler.
public class MyThread extends Thread
{
private Handler m_handler;
@Override
public void run()
{
Looper.prepare();
m_handler = new Handler();
Looper.loop();
}
// Simply post the quit runnable to the thread's event loop
public void quit()
{
m_handler.post(new QuitLooper());
}
// Inner Runnable which can be posted to the handler
class QuitLooper implements Runnable
{
@Override
public void run()
{
Looper.myLooper().quit();
}
}
}
Therefore, in your Activity's onPause() or onStop() methods, just call myThread.quit().