Max
Max

Reputation: 1025

Android: What is the best way to make repetitive Background Tasks Android Oreo ready?

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.

Upvotes: 4

Views: 926

Answers (2)

SafaOrhan
SafaOrhan

Reputation: 720

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.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007474

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.

Upvotes: 1

Related Questions