简体   繁体   中英

Daemon Thread is still alive after closing the app

I'm just testing with an almost empty android project .

I created a daemon thread in the Main Activity.

Started the app, and pressed the back button on the phone to close the app.

But the daemon thread never dies.

Daemon Thread works really well with an empty JAVA PROJECT .

But with android, doesn't work.

I searched for the solution for hours but only got this.

A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI.

Does anyone know how to solve this?

PS. I stopped the app not by pressing the hardware back button but by pressing the 'Force stop' button in 'App info', and both of the app and the thread are gone!

I first learned about Daemon Thread from some example codes for android develoment.

But nobody mentioned about what I've experienced.

Do android developers just believe Daemon Threads will be killed for sure?

But the daemon thread never dies.

Presumably, you did not cancel() the thread. You need to do this at an appropriate point.

But with android, doesn't work.

It works just fine. It works the same as in Java, as you can tell by reading your quoted passage. The difference is in how long your process lives and in the threads in that process (Android processes have other threads besides ones that you fork).

Does anyone know how to solve this?

Call cancel() on your thread at an appropriate point.

Pressing back button does not close the app (assuming that closing means process termination). That only finishes an activity but process is still running. To achieve desired behavior you can use eg. AsyncTask and call cancel() from appropriate callback of your Activity eg. in onDestroy() or onBackPressed() if you are interested exactly in back button presses.

apologies for pointing possible basic out but follow your problem have you ensured after closing that its not running in you Task Manager (ctrl+alt+delete)..have task manager running alongside your daemon then during the closing of daemon watch what happens during and after closing in task manager as it may be backing up files in accordance with settings-check settings in daemon....or have you used an ExecutorService to run as Daemon in Java in which case this will prevent your program from shutting down see here ExecutorService - 10 tips and tricks

Java Applicatioin Process Hangs on Windows and Cached Thread Pool

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