1

in my Android project i've created an custom clock widget with a service which contains an instance of Broadcast Reciever and an intent filter. The Broadcast Reciever provides the update of the widget every time arrives the ACTION_TIME_TICK. This is working perfectly when set targetSdkVersion to 25, in gradle. But if i target to sdk 27, the service stops after few minutes. I've read the documentation about background executions limit in Android O, but i can't find any approach that is useful for my project. Do you have any suggestion?

deno750
  • 11
  • 1
  • 3
  • have you tried calling `startForeground` in your service? – M. Prokhorov Apr 10 '18 at 14:09
  • The best way to schedule repeating tasks on api 21+ is using a JobScheduler. You should give it a try, read here: https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129. Below api 21 the AlramManager will do the job. – HedeH Apr 10 '18 at 14:15
  • @M.Prokhorov Yes i tried, but this approach needs a persistent notification – deno750 Apr 10 '18 at 15:07
  • To clear things up: your service stops while the device screen is still on, or does your app needs to be constantly updated even in background? – M. Prokhorov Apr 10 '18 at 15:17
  • @M.Prokhorov I need a service that costantly updates the widget in background, even if the mainactivity is destroyed – deno750 Apr 10 '18 at 15:24
  • @deno750, maybe [this answer](https://stackoverflow.com/a/46181049/7470253) will be a good start for you. I personally think that if screen is off, no updates are necessary (it will be enough if widget will play catch-up once the screen is on again). – M. Prokhorov Apr 10 '18 at 15:54

1 Answers1

0

There are a couple of things you can try which, when used in concert, should be able to cut through all of the idle/standby/doze modes (irrespective of OS version).

  1. Use a WakefulBroadcastReceiver instead of an ordinary BroadcastReceiver. Make sure you include the WAKE_LOCK permission to use it correctly.
  2. Use the setExactAndAllowWhileIdle() method (on API 23 & above) to schedule the Intent for the receiver:

    if (Build.VERSION.SDK_INT < 23) {
        if (Build.VERSION.SDK_INT >= 19) {
            setExact(...);
        }
        else {
            set(...);
        }
    }
    else {
        setExactAndAllowWhileIdle(...);
    }
    
Scott Smith
  • 3,900
  • 2
  • 31
  • 63