简体   繁体   English

使用服务连接发送初始消息

[英]Send an Initial message with Service Connection

I have an android service, which is connected to a service connection.我有一个 android 服务,它连接到一个服务连接。 Upon initialization, I'd like to send a single String, for example "test message" to the Service connection.初始化后,我想向服务连接发送一个字符串,例如“测试消息”。 How would I do this?我该怎么做?

    public class exampleService extends Service {
    private final IBinder iBinder = new Messenger(new IncomingHandler(this)).getBinder();
    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

}

.... ……

private ServiceConnection myService = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder)
        {
            Log.i("exampleService", "Binding Connect");
            messenger = new Messenger(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            messenger = null;
        }
    };

The ServiceConnection monitors the state of the connection to the service, as opposed to communicating information to the service. ServiceConnection监视与服务的连接状态,而不是向服务传递信息。 To communicate with the service, you need to use the binder that is passed as an argument to the onServiceConnected(ComponentName name, IBinder binder) callback.要与服务通信,您需要使用作为参数传递给onServiceConnected(ComponentName name, IBinder binder) binder的 binder。

In your code sample, you are using a Messenger to perform communication instead of directly interacting with the binder.在您的代码示例中,您使用Messenger来执行通信,而不是直接与活页夹进行交互。 For an example of how to work with Messenger , see the Remote Messenger Service Sample .有关如何使用Messenger的示例,请参阅远程 Messenger 服务示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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