How to establish a two-way communication between A

2019-01-22 16:39发布

问题:

I'm working on establishing a two-way communication between an Activity and a Service which runs in a different process.

Querying the process from the Activity is no big deal. But I want the process to notify the Activity on events. The idea behind it is this: the service runs independently from the actual app. It queries a webserver periodically. If a new task is found on the webserver the process should notify the activity.

I found this thread over at AndDev.org but it doesn't seem to work for me. I've been messing around with BroadcastReceiver. I've implemented an interface which should notify the Activity but the problem is that the listener is always null since the Broadcast from the process is done via Intent, hence the class that extends BroadcastReceiver will be newly instantiated.

How can I establish a 2-way communication? This has to be possible. Thanks for any help,

steff

回答1:

Either use BroadcastReceiver or have the Activity register a callback or listener object that the Service calls on key events. The links above are to book example projects demonstrating each of those techniques.



回答2:

I think you should have the BroadcastReceiver start your activity again with the result in the Intent.

Or you could use AIDL about AIDL. The samples also have an (multiple?) example how to use AIDL and services. But AIDL might be to much of a hassle for your purpose.



回答3:

You have to use BroadcastReceiver to receive intents, and when you want to communicate simply make an Intent with appropriate values.

This way you should be able to make a 2-way communication between any component.