开发者

How does the Android system behave with Threads that sleep for too long?

开发者 https://www.devze.com 2023-02-22 15:41 出处:网络
So in my \"Home\" activity in my Android app, I have a non-deamon thread that is constantly running in the background that checks a blog for 开发者_开发知识库new posts every 30 minutes or so to fire n

So in my "Home" activity in my Android app, I have a non-deamon thread that is constantly running in the background that checks a blog for 开发者_开发知识库new posts every 30 minutes or so to fire notifications. It works fine when I make the thread sleep just for a few seconds for testing purposes to make sure that it is indeed working in the background, but in the actual phone, when the event is supposed to fire after half an hour, it just doesn't. So my question is, when I do *Thread.sleep(30_MINUTES)* does the android system kill it or something for being an inactive thread for too long? Does android kill sleepy threads?


Why don't you try AlarmManager to fire your polling code every 30 minutes ? Once the polling is done re-schedule if for the next 30 minutes. AlarmManager is much more reliable than making the threads to sleep


OK, so the problem was solved. What was causing the problem was that in Android when you put a Thread to sleep for let's say 30 minutes, when the device goes to sleep (the screen turns off after inactivity on the phone) the CPU goes into a so called "deep sleep state" which causes the thread's counter -that wakes the thread wake up- to pause while the screen is off. This means that when you say Thread.sleep(500000) for example, those 500000 milliseconds are counted only when the phone is awake. The solution is to use AlarmManager and a BroadcastReceiver to run the code periodically.

Here's a simple guide on how to use AlarmManager with a BroadcastReceiver: http://justcallmebrian.com/?p=129


I am not sure what you are doing in your coding but definitely android system does not kill a thread on its own whether sleepy or not doesnt matter.


What exactly is happening during this time? I believe the only situation in which what you're describing (using the technique you describe) would work reliably is if both (a) your activity (or another activity or service that runs in the same process) is the foreground activity for the entire life of the thread and (b) there's a wakelock preventing the CPU from sleeping.

Android may not kill individual threads, but it absolutely can and will kill processes based on the process lifecycle.

0

精彩评论

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