0

I'm new to Android development and I'm confused about Service to Activity communication. I need to listen to a socket and when a packet is received, update something in the Activity. I'm planning on listening to the socket with a Service and want to tell the Activity when something has been received.

For now I just want my Service to send a message to my Activity every 5 seconds. When the Activity receives the message it prints it to a TextView.

I've looked at (Bound Services) but this appears to only be one way: an Activity calling methods in a Service. Do I need broadcasts? Aren't they for process to process communication?

Can anyone point me in the right direction? Thanks.

tompreston
  • 630
  • 7
  • 24
  • Try using `Handlers` to send message back to your activity. – Divya Motiwala Apr 18 '13 at 13:32
  • This worked: http://stackoverflow.com/questions/3998650/what-is-the-simplest-way-to-send-message-from-local-service-to-activity – tompreston Apr 18 '13 at 14:42
  • Glad you found your answer. Broadcasts are the correct approach, but you should consider using a LocalBroadcastManager to keep the communication in your app: LocalBroadcastManager.getInstance(context).sendBroadcast(intent); – JustinMorris Apr 19 '13 at 22:40

1 Answers1

0

Use a callback.

ServiceInterface.aidl:

package com.test.service;
import com.test.service.ServiceCallback;
interface ServiceInterface {

    /**
     * Register callback for information from service.
     */
    void registerCallback(ServiceCallback cb);

    /**
     * Remove a previously registered callback interface.
     */
    void unregisterCallback(ServiceCallback cb);
}

ServiceCallback.aidl

package com.test.service;

/**
 * Callback interface used by IRemoteService to send
 * synchronous notifications back to its clients.  Note that this is a
 * one-way interface so the server does not block waiting for the client.
 */
oneway interface ServiceCallback {
    /**
     * Your callback function
     */
    void onCallback(int data);
}

Found a link to Malachi's Android site explaining with more code.

mach
  • 8,315
  • 3
  • 33
  • 51