Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

android - How to stop the handler?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...