The place where random ideas get written down and lost in time.

2019-11-17 - Android Background Service

Category DEV

A few of my older apps rely on a common principle of having a permanent background service. This broke with the API changes in Android O & P (API 26).

Trying to fix T3 & RTAC in-situ has been a bit of a PITA, so it’s time to do an isolated “canonical example” app to figure that out. But first I need to understand why I have a background service and how to adjust it for these API. Also to clearly list which API levels are the issues.

Existing cases:

  • RTAC:
    • Needs to run on Hi10 tablets, Android 5.1 (API 22, Lollipop MR1).
    • Permanent background service.
    • Designed to keep the app alive at all times, even if not in foreground. Keep all the network connections active. Wakelock to make sure the tablet never sleeps.
    • Notification shown when main activity is in background.
  • DccThrottle:
    • Same as RTAC. Permanent, active even when in background.
  • Bearing v1:
    • Similar to RTAC. Permanent, active even when in background.
  • T2:
    • T2 is API 9+, T3 is API 26+.
    • Job-oriented background service.
    • Started by “check” menu, alarm, or receiver, only for the duration of the operation.

The needs for T3 are very different and ideally we would not use a service for that if we can avoid it. The only reason a service was used here is because that was the recommended design at the time. I understand OS requirements can change, but it’s somewhat ironic an app breaks when it was following the recommended design, with undertones of “you’re doing it wrong”.

The T3 case was handled in 2019-07-08.

It uses:

  • JobService to schedule a task.
  • Still relies on an UpdateReceiver starting an actual Service.
  • Boot_Received triggers the UpdateReceiver.

Now the question is whether a service is even needed at all. Does the new API offer something else?

https://developer.android.com/about/versions/oreo/android-8.0-changes.html#back-all 

In theory that doc seems fine: start a service using startForegroundService, then call startForeground with a notification  In practice that seems to fail, and the service still gets killed 5 minutes later when testing on an Android O device or emulator.

There’s a lot of that on SO:
https://stackoverflow.com/questions/49637967/minimal-android-foreground-service-killed-on-high-end-phone 

Thus my suggestion is to create two simple samples/demo apps:

  • T2 case: a “short job”, triggered by a button, an alarm (specific time), or a boot receiver.
  • Permanent case (e.g. RTAC, DccThrottle, etc) of a permanent “foreground” service.

For the latter, integrate some external lib such as Doki that shows details from dontkillmyapp.com for a specific device.

https://bitbucket.org/ralfoide/misc-exp-public/src/master/android/  is a good place to store these.


 Generated on 2024-11-20 by Rig4j 0.1-Exp-f2c0035