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

2019-11-29 - Background Foreground Demo Android App

Category DEV

Just completed this yesterday, and it works as expected:
https://bitbucket.org/ralfoide/misc-exp-public/src/master/android/bg-demo/

(In retrospect, I should have called the demo “fg-demo”).

First off, I’d say duplicating the job-demo project was easy and the way to go: dup the folder, remove app/build as well as anything excluded by gitconfig, then do a simple grep/sed on “job.demo”. The only 2 places where it was used was in the app name.

The demo uses a “startForegroundService”, a regular Service, and a “startForeground” from the onStartCommand of the service, with a notification.

The service is started when the activity is started/resumed. The service is only stopped when the stop button in the activity is explicitly used. The service itself runs a thread that updates a counter. The activity binds to the service to give a callback, used to update the counter on screen.

As this is both a “bound” service (for the activity) and a “started” service, it keeps running until it is both stopped and unbound from the UI.

There are a few cases where the system may kill & restart the service immediately.

Which project make sense using that, and which do not?

In the past, I’ve been using background services for applications that:

  • Do some kind of system control and need to run in the background all the time.
  • Those that have expensive/complicated startup, for example with network connections to hold the update state.

In these cases, it’s a bit wasteful to stop everything as soon as the user switches between apps.

In a post-Android-O world, one should balance between this and using a JobService, or neither.

How would I use these for current, former, or future projects:

  • DccThrottle: Foreground service is a logical choice. User is expected to switch between apps, not lose control, and be able to change back immediately. Service only needs to be started once at least one engine is in command; stopped by asking for confirmation when trying to exit the app (or the double-back pattern).
  • RTAC: Background service is a logical choice, but not necessary. The app is supposed to be used in foreground. Instead it could just use an app singleton thread.
  • T3: JobService + AlarmManager.
  • Bearing: This was using a background service before. The new version just uses an activity-centric update. State is lost/reconstructed when outside of the activity.

Follow up work:

  • Change on-going notification to “App Blah is Running”.
  • Change notification setting so that it does not beep at me (lower priority).
  • Add 1 or 2 notification actions: “quit now” vs “open”.
  • Open would do what the current notification click does, bring the activity.
  • Quite would both stop the service and kill the app (or more exactly stop the activity if it’s open).


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