开发者

How to stop threads and handlers in Android

I honestly can't figure it out - I've heard that thread.stop() is not a good thing to use. It also isn't working for me. How to get threads/han开发者_Python百科dlers to stop running?


Threads should be terminated in a "polite" way. You should build in some mechanism for your thread to stop. You can have a volatile boolean parameter that is checked on every loop of your thread (assuming you have loops in there) like so:

while (!threadStop) {
    // Do stuff
}

And then you can set the boolean value to false from another thread (make sure you handle all synchronization issues though) and your thread will stop in it's next iteration.


Ok the answer to stop threads have been done. To stop handler you have to use this following method :

removeCallbacksAndMessages from Handler class like this

myHandler.removeCallbacksAndMessages(null);


you can use it like this..

Thread mythread=new Thread();

if(!mythread){
    Thread dummy=mythread;
    mythread=null;
    dummy.interrupt();
}

or you can use

mythread.setDeamon(true);


The correct way of stopping a handler is: handler.getLooper().quit();
I usually implement this by sending a quit message to handler which terminates itself.

The correct way of stopping a generic Thread is: thread.interrupt();
The thread that is being stopped needs to handle the interrupt:

if(isInterrupted())
    return;

This can be put in a loop if you wish:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
    while(!isInterrupted() && (line = br.readLine()) != null) {
        // Do stuff with the line
    }
}
catch(IOException e) {
    // Handle IOException
}
catch(InterruptedException e) {
    // Someone called interrupt on the thread
    return;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜