I used a service to start a Thread, in this thread, I wrote a while loop(I set a flag, while flag is true, the thread runs, if the flag is false, then the thread won’t do anything, thus stop the thread manually) in this thread. when I debug my code, I often noticed that the thread is over, but the service was still running. Is it recycled by android system?
How can I do to prevent my thread from recycling?
====== EDIT =======
“will by thread be cleaned up by the system automatically before it ends” – means the thread is being killed when it shouldn’t be
Are you calling Thread.yield() in your loop to allow the system to do other things? If not- then android could be killing the thread for consuming 100% CPU usage – if it’s a simple loop the stack-trace won’t change so it will thing your script hung
http://developer.android.com/reference/java/lang/Thread.html#yield()
Yield() tells the thread-executor that it should stop and run other threads before returning to yours, without it your loop will steal resources from other apps
You can also sleep if you are sure your flag won’t change for a certain amount of time
Edit – Background – it’s the way android detects hung threads – If a thread takes up 100% of the CPU then it dumps a stack trace to a file, waits a short amount of time and then dumps another stack trace – if the two match it assumes the code has stopped running and will either issue an ANR ‘xx is not responsing’ dialog for an activity, OR, if it’s a service, it will simply kill it and restart it automatically.
By yielding you prevent it from consuming 100% so it never tries to do that.