简体   繁体   中英

Android worker thread not exiting

I have a thread derived from the Thread class inside a small test app. I start it by using its start() method. Unfortunately, it doesn't seem to terminate when I stop the app's execution from within Eclipse by using the stop button. The only way I can get the thread to terminate is by uninstalling the app.

Is this normal? Can I get the app to completely stop and exit memory by stopping it in the debugger or do I always have to use a "clean" way to exit from within the app itself?

You can do it cleanly by stopping the Thread in onDestroy() or onStop() of the Activity. To stop the Thread, you can keep a flag in the Thread and turn it on when you want to stop.

public void stopRunning() {
    stopped = true;
}

public void run() {
    while (!stopped) {
        try {
            // Do something
        } catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM