简体   繁体   English

屏幕关闭时,Android服务似乎正在暂停

[英]Android service seems to be getting paused when screen is off

I have an android service that pulls updates from a server every 5 minutes. 我有一个android服务,每5分钟从服务器提取一次更新。 It works great when the screen is on, but when it is off it seems to pause. 当屏幕打开时,它的效果很好,但是当屏幕关闭时,它似乎暂停了。 Keep in mind the service runs in the foreground using start foreground(). 请记住,服务使用start front()在前台运行。

I am currently creating a new Thread and having it sleep in order to run the update every 5 minutes, is there a better method that would allow the timer to still run while the device is sleeping? 我当前正在创建一个新线程,并使其休眠以每5分钟运行一次更新,是否有更好的方法可以使计时器在设备休眠时仍然运行?

The update isn't happening because the phone is going to sleep when you turn off the screen. 无法进行更新,因为关闭屏幕后手机将进入睡眠状态。 Happens more often on WiFi if "Optimized WiFi" mode is turned on. 如果启用“优化WiFi”模式,则在WiFi上发生的频率更高。

You should have a look at wakelocks . 您应该看看唤醒锁 Acquire a wakelock to prevent device from falling asleep. 获取唤醒锁以防止设备入睡。 Release it to let it sleep again. 释放它使其再次入睡。 Note that this obviously increases battery consumption. 请注意,这显然会增加电池消耗。

Use an alarm via AlarmManager. 通过AlarmManager使用警报。 The alarm will wake the CPU, allowing you to do your processing. 该警报将唤醒CPU,使您可以进行处理。 If you're just waiting on a sleep in a thread, you won't be waken if the phone is off (its in sleep mode). 如果您只是在等待线程中的睡眠,则在手机关机(处于睡眠模式)时不会唤醒您。

Of course you'll need a background thread or task to do the actual downloading. 当然,您需要后台线程或任务来进行实际下载。 That's where a wakelock comes in. When the alarm goes off, request a wakelock. 那就是唤醒锁的所在。当警报响起时,请求唤醒锁。 When you're done checking/downloading, release it. 完成检查/下载后,将其释放。 For your case, you can keep the same architecture- just instead of a 5 minute sleep waiting to recheck, wait on a semaphore. 对于您的情况,您可以保持相同的体系结构-而不是等待5分钟的睡眠等待重新检查,等待信号量。 When the alarm comes in, request a wakelock and signal the semaphore. 警报响起时,请请求唤醒锁并发出信号量。 When the check is done, release the wakelock and semaphore, then wait on it again. 检查完成后,释放唤醒锁和信号灯,然后再次等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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