Android: Foreground service vs. wakeLock

后端 未结 2 1296
囚心锁ツ
囚心锁ツ 2021-02-04 04:17

I am relatively new to Android, so what I am asking may seem obvious (although I have read all the similarly titled questions, and have searched extensively). I need to monitor

相关标签:
2条回答
  • 2021-02-04 04:38

    I had exactly the same need and problem. I believe the solution is to use both a partial wake lock and a foreground service. Android will try not to kill a background service that holds a wake lock but is free to kill it when it needs the resources and possibly restart it later. That's fine for a lot of purposes but at least in my case that is not good enough. Putting a service into the foreground state is the way to tell Android that that killing it is unacceptable. Yes, it might still happen in extreme situations but that would now be a violation of the API contract whereas with a background service Android is free to kill it. You should therefore probably code as if that that will never happen but just know that this is a possible but probably rare error.

    0 讨论(0)
  • 2021-02-04 04:43

    Holding a WakeLock and a foreground Service are not really related and shouldn't be compared are to which direction is best.

    Android OS is built to swap out processes based on a variety of factors. This means your process might get killed at any point by Android and it provides a framework to help you, the developer, to ensure your app can save and restore its state when this happens.

    A WakeLock simply prevents the CPU from sleeping which helps save battery when the phone is not in use.

    Now, a combination of both would help you achieve what you want but at great user cost. I wouldn't want an app in my phone to keep the CPU constantly running or a notification icon to show up constantly in the notification bar (that's what a foreground service does).

    Keep in mind, starting a service in foreground mode does not guarantee your app will not get killed. It might still happen albeit rarely.

    What is it you are trying to achieve here? Why keep monitoring the devices accelerometer? Perhaps you should only monitor it only when an Activity of your app is in the foreground instead.

    0 讨论(0)
提交回复
热议问题