4

I heard Background Services won't work that free on android Oreo. I'm kinda confused how I should rewrite my Code. I'm working with android for a month or so now, so please try to answer as simple as possible.

I have a Service that is called On Boot and in the onCreate() of my MainActivity. In the service's onStartCommand it is calling a Handler. This handler will postDelay() itself every half minute and call a function. This function does some api requests and will push a notification when certain conditions were applied.

What is the best way to let this code work on android O+?

I thought about using a Foreground Service and display a useless ongoing notification, the user can make invisible but that idea does not sound good.

Roshan
  • 905
  • 9
  • 21
Max
  • 965
  • 1
  • 10
  • 28

2 Answers2

1

This handler will postDelay() itself every half minute and call a function

This will not work reliably on Android 6.0+, courtesy of Doze mode and app standby. In particular doing work anywhere nearly that frequently will be bad for the battery, and so Google is going to great lengths to prevent this sort of behavior.

What is the best way to let this code work on android O+?

The best thing to do is to get rid of it entirely. Use JobScheduler and do periodic work less frequently (e.g., every 15 minutes).

Using a foreground service will have your app behave on Android 8.0+ the way that it did on Android 6.0+ (i.e., still unreliable, but at least working for more than one minute).

I thought about using a Foreground Service and display a useless ongoing notification, the user can make invisible but that idea does not sound good.

Make a useful notification, allowing the user to control the behavior of the service.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for your answer! I found out that Android N didn't allow Scheduled Jobs, periodic < 15 Minutes, does that affect android O or did they made it more "friendlier" again? – Max Aug 25 '17 at 19:42
  • @Max: There are no changes in this area AFAIK. Frequent periodic work is major source of battery drain, which is why Google frowns upon it. – CommonsWare Aug 26 '17 at 12:31
0

Use GcmNetworkManager. You can set periodic tasks with more frequent interval. Since it uses different structures regarding api level, you will likely have no problems with oreo.

SafaOrhan
  • 690
  • 9
  • 19