Tobias
Tobias

Reputation: 265

using synchronous and async communication between Activity and Service on Android

I am currently writing an app, which consists of a service and an activity. The service is running in the background, doing some live audio processing. If the user want to get some information about the running service or want to change the settings of the service, the activity gets started and bind to the service.

Currently i am using the asynchronous messenger system to communicate between the service and the activity. For example, the service can send some results to the activity through a message and the activity can handle this message and show the results. This works fine, but it is stressful to write the messaging stuff for each communication. And it is not always needed. Sometimes i only want to ask the service, if a flag is set or not. If i do this asynchronous, i have to send a message to the service which asks for the value of the flag and the service has then to send a message back to the activity to answer the request.

So i want to have some getter and setter which can synchronously access the service. This can be done by using a binder, which works too.

The problem is, that i sometimes need synchronous communication to get the value of flags etc. and sometimes i need asynchronous communication to push the results from the service to the activity. So what i need is a binder and a messenger. But i dont know how this can be done, because the service can only return one object from the onBind() method, either a binder object or a messenger object.

Do you have any suggestions how this can be done or some other approach to realise asynchronous and synchronous communication between an activity and a service?

Thanks in advance!

Tobias

Upvotes: 0

Views: 1905

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006819

If you are already binding to the service, your activity can supply a listener object to the service, which the service will then call when events occur.

You just need to make sure that you unregister that listener object before unbinding from the service, and do both before the activity is destroyed, so your service does not wind up with a strong reference to a defunct activity.

Upvotes: 1

Related Questions