Search code examples
androidwakelockforeground-servicedoze

Android doze mode and foreground service


I read many questions here about doze mode like Android doze mode, Android N Doze mode - how to keep background download and processing?, Wakelock and doze mode and many others. But in many replies, opinions is different. I can't test it by myself (emulator does not support my processor, and my only test device is android 5.1). I would like to know the next situation. I have an activity, which controls the media player. On devices with android 6.0 and higher it wouldn't work as expected cause of doze mode. As many solutions says to prevent doze mode it should start a service in separate process in foreground and control media player from there. The question is: if i start foreground service with partial wake lock in separate process, which would do nothing except showing notification, and leave controls to media player in my activity, should it prevent the doze mode? Or maybe there any other ways except keep the screen on from window manager?


Solution

  • According to this SO question and answer:

    In this post's comments on Sep 17 Dianne Hackborn writes:

    Apps that have been running foreground services (with the associated notification) are not restricted by doze.

    - Source (sec_aw)

    It looks like using a foreground service prevents the app from being killed by Doze.

    Please note though, that some vendors (I know of Samsung, but there are probably others) create their own RAM conservation/battery saving tools. These may exhibit patterns completely different from Doze, and there's usually a bunch of other hoops to jump through. You are not guaranteed to get the same behavior on these devices either - they may be more or less aggressive, and the more aggressive ones tend to be worse for keeping services or whatever alive.

    There's also no universal way to deal with these, but someone has made an entire website dedicated to showing what vendors are problematic, as well as potential workarounds. Note that the majority of the problematic vendors only yield end-user solutions, which means you (the developer) have no way to fix it without the user doing something.

    While this is unfortunate, that's pretty much what happens when companies implement their own versions of Android. Also, from my own experience (primarily as a user rather than a dev) on a Samsung phone, the settings aren't always respected and still causes annoying behavior.

    Anyway, as long as Doze is present, foreground services should be fine. On other vendors, however, all bets are off and you're at the mercy of the vendor's implementation of some type of optimization system. On certain exposed operating systems (again, see the website linked earlier), you also have no choice but to ask the user to fix certain settings to keep stuff alive.