简体   繁体   中英

How do I talk to an Activity from a Local Service in Android?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM