Search code examples
androidservicescreensleepforeground

Keep app service active during device sleep


So I've made an Android video-calling app that tries to be available in the background so that the user may receive calls when the screen is off. I've noticed however that the app would be paused when the device went to sleep.

The solution I've found that worked was to rewrite everything to a service and then request a wakelock so the service wouldn't be paused during sleep.

Surely, since there are so many of these types of apps, there is a more elegant way to do this? A periodic check wouldn't work since you would want to take the call in real-time.


Solution

  • It depends on the Android version, for version older than 6 a partial wakelock is enough to keep the device awake, for Android 6 you also need a foreground service, that's a Service that calls startForeground() and shows a notification, but to keep the device awake has a big impact in battery usage.

    You do not necessarily need to transfer all the code to the Service due it is the whole application that stays awake.

    A more elegant solution to replace all this would probably be to use Push Notifications, it is what most messaging applications use. Firebase has Push Notifications.