Android Thread Pool has runnables building up without execution after background state
My application has a thread pool that creates 3 simultaneous threads. As I invoke runnables, they are added to my thread pool.
My problem happens when the application goes to the background for a while. Eventually, my threads stop executing the runnables in my pool and the pool just continues to grow. Even if I bring my application back to the foreground, my threads开发者_运维问答 do not start running again.
My theory is that when my application goes to the background that my threads are being killed. I'm not sure by what and I'm also not sure of a good way of determining whether my threads are killed so that I can start them again.
Do you have any suggestions as to something I can look for to determine whether or not a thread has been killed?
You can't use a thread pool to execute code in the background because the Android activity lifecycle won't consider your app to be active, and will kill your process (including all threads) eventually after you lose UI focus. What you want is an Android Service which has a different lifecycle. To do things like this we use a local service with a Handler and a HandlerThread that we can post Runnables into. You'll probably want something similar.
Note: Every time I do this I feel like there must be an easier way, so it might be worth searching if someone has simplified this pattern.
精彩评论