Stephen Hosking
Stephen Hosking

Reputation: 1465

Will a "foreground" bound service be stopped eventually because client will be stopped?

My requirement: Detect and respond to power events. I have an activity which allows the user to set up the responses. The app must keep responding after the UI has gone to the background (either by user action, ie "Home", or by, for example, receiving a phone call).

My analysis:

  1. Use a BroadcastReceiver which accepts ACTION_POWER_DISCONNECTED (and ..CONNECTED)
  2. I have implemented the receiver within the activity, and it works as expected. It continues to work in the background for some time, but eventually stops working because of normal android lifecycle, ie. the OS destroys it.
  3. (Proposed) To keep the receiver running, I follow this recommendation and make it a service, with startForeground.
  4. (Proposed) Because it must interact with the UI, ie, by accepting changes to its settings, it should be a bound service.

The expected problem:

According to the documents a bound service is stopped when all clients unbind. I have only one client (the UI), which will unbind in its onDestroy method. This will be called when client is stopped by the OS, which will eventually happen under normal resource management.

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Questions

  1. Is this analysis correct? ie. Will a bound service, with one UI client, eventually be destroyed when the client is destroyed, as part of normal OS management?
  2. If so, what should I do about it?
  3. Any other tips please :)

Asked as a hypothetical, because there is quite a bit of work setting up the bound service and then proving that it stops as expected. Also, even it it appears to work, I might be doing this wrong.

Upvotes: 0

Views: 654

Answers (1)

Scott Stanchfield
Scott Stanchfield

Reputation: 30634

Why not register the broadcast receiver in your manifest? It will be started and invoked automatically when the power intents are broadcast. Then you don't need to worry about any sort of "keep alive" processing (and you won't need a service unless you need to do some longer processing)

Upvotes: 1

Related Questions