Search code examples
androidserviceipcmessagingaidl

Android: Communication between two Services of two separate APKs


Situation:

I have an Android System Application (persistent) with a Service that is supposed to run all the time. (Let's call it Service A)

Then there is another Application (not a System Application; normal App) that also has a Service. But this Service might run or might not run since the Android OS will kill it if it needs resources. (Let's call it Service B)

In short: We have two Applications (hence 2 APKs) that can be signed with the same certificate. (So they could run in the same process right?)

What I try to accomplish

The Service A listens to events. When it receives an event then I want the Service A to call the normal App (Service B) which should give a response back to Service A.

Approaches to let the two Services communicate

I could let them communicate using:

  • Binding (using an AIDL)
  • Messaging (but not optimal since passing complex objects is a must)

Problems

  • Which way to communicate is "the best" one for the described case?
  • What happens when Service A wants to delegate/send a message to Service B and Service B is not running? It must get a response from Service B. Should I always start Service B if it is not running when Service A wants to call it?

Thank you!


Solution

  • Which way to communicate is "the best" one for the described case?

    You only cite two options, since "Aidl" and "Binding" are the same thing. You use AIDL to describe and implement the client-side proxy and the server-side stub for cross-process service binding.

    Given that you want call-and-response, binding is probably a better choice. Note, though, that there is no IPC approach that supports "complex objects" very well, outside of using Parcelable, Serializable, or converting the object graph into JSON or something.

    What happens when Service A wants to delegate/send a message to Service B and Service B is not running?

    When you call startService() or bindService(), Android forks a process for App B and creates an instance of the service (invoking its onCreate()) method. At that point, the behavior is the same as if the process and service had already been running.