1

My app needs to run in background for long time and periodically send data to server. I tried AlarmManager but it is restricted in doze mode. I next thought is the foreground service.

Does the device enter doze mode while a foreground service is running?

If the device enters doze mode, is internet connection restricted while foreground service is running?

jarly
  • 231
  • 1
  • 4
  • 16

1 Answers1

1

That works for me pretty well, tested several hours of continuous operation with some emulators and Android 6.0 and 7.1 real devices, network connection never lost :

In the Main Activity onPause I acquire a Partial WakeLock and I start a Service with STARTFOREGROUND_ACTION intent, the Service calls startForeground and shows a Notification.

On Activity onResume the WakeLock is released, the Service stops with STOPFOREGROUND_ACTION intent and the Service itself calls stopForeground & stopSelf.

And also that avoids Activity to be destroyed on Back Key press :

 @Override
    public void onBackPressed() {
         moveTaskToBack(true);
    }

Of course I provide a menu option to stop the background porcessing and finish the Activity

My code that periodically ask an internet server is placed in the Activity, it uses a timer.

Hope it will help

from56
  • 3,976
  • 2
  • 13
  • 23
  • I didn't quite get your solution here. Android Doze Mode ignores all wake locks. – jarly Jul 03 '17 at 15:08
  • Not for me with an active Foreground Service + Notification. I already tested in several real devices. – from56 Jul 03 '17 at 15:47
  • Deeply discussed here : https://stackoverflow.com/questions/37869201/how-does-doze-mode-affect-background-foreground-services-with-without-partial-f – from56 Jul 03 '17 at 15:50
  • Even with foreground service, the AlarmManager's setExact and setExactAndAllowWhileIdle are not working in Doze Mode.Sometime after the device wakes up, the AlarmManager triggers. setAlarm is working in doze mode but it shows a alarm icon on status bar. Any other way to schedule periodical task in service? – jarly Jul 05 '17 at 10:50
  • It seems that for avoid enter Doze mode the foreground service must show a notification ... – from56 Jul 05 '17 at 14:05