Activity Recognition stops receiving updates when phone goes to standby(screen off state)

只谈情不闲聊 提交于 2019-12-02 21:10:33

To avoid draining the battery, an Android device that is left idle quickly falls asleep. It's the reason of your service stopping. You can read more about how it can be handled here: Keeping the Device Awake. Also take a look on WakefulIntentService from cwac-wakeful library. Looks like it's what you are looking for.

Take a look at "Repeating Alarms":

They operate outside of your application, so you can use them to trigger events or actions even when your app is not running, and even if the device itself is asleep.

https://developer.android.com/training/scheduling/alarms.html

Or at "WakeLock":

One legitimate case for using a wake lock might be a background service that needs to grab a wake lock to keep the CPU running to do work while the screen is off. Again, though, this practice should be minimized because of its impact on battery life.

Specially "WakefulBroadcastReceiver":

Using a broadcast receiver in conjunction with a service lets you manage the life cycle of a background task.

A WakefulBroadcastReceiver is a special type of broadcast receiver that takes care of creating and managing a PARTIAL_WAKE_LOCK for your app. A WakefulBroadcastReceiver passes off the work to a Service (typically an IntentService), while ensuring that the device does not go back to sleep in the transition. If you don't hold a wake lock while transitioning the work to a service, you are effectively allowing the device to go back to sleep before the work completes. The net result is that the app might not finish doing the work until some arbitrary point in the future, which is not what you want.

https://developer.android.com/training/scheduling/wakelock.html#cpu

If you consider to use the second approach be careful about draining the battery...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!