Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the handler?

Tags:

android

I have a doubt .. Am having a hander in an activity in my application. Though my activity destroyed the handler still functioning. Is it running on different process other than the application process ? Could any one plz explain why its working like so ? Is it possible to stop the handler while onDestroy of the activity ?

Thanks in advance.

like image 896
Prasath Avatar asked Feb 18 '11 05:02

Prasath


People also ask

How do I cancel handler?

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

How do I remove runnable from Handler?

Just use the removeCallbacks(Runnable r) method.

What is the 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 .

How do I close runnable on Android?

kill() mechanism, using existing API provided by the SDK. Manage your thread creation within a threadpool, and use Future. cancel() to kill the running thread: ExecutorService executorService = Executors.


1 Answers

As described in the documentation

http://developer.android.com/reference/android/os/Handler.html

"Each Handler instance is associated with a single thread and that thread's message queue."

When you are about to finish your activity, e.g. in onDestroy() you also need to cancel the callback for the runnable it was started for:

mHandler.removeCallbacks(previouslyStartedRunnable);

You can do that even without checking if runnable was already fired while your activity was active.

UPDATE:

There are two additional cases to be considered:

1.) You have implemented your Handler in a way that you created new class for the Runnable, e.g.

private class HandleUpdateInd implements Runnable...

Usually you need to do that if you have to start delayed runnable with current set of parameters (which may change until runnable fires). To cancel it you need to use

mHandler.removeCallbacksAndMessages(HandleUpdateInd.class);

2.) If you are using inline call (JPM thanks for the comment)

handler = new Handler() { public void handleMessage(Message msg) { ... } };

Then you need to define "what" value for that Message. Later on, if you need to cancel it you can use

handler.removeMessages(what); 

to perform that task.

like image 53
Zelimir Avatar answered Oct 02 '22 18:10

Zelimir