服务回调到android中的活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2026393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:15:35  来源:igfitidea点击:

Service call backs to activity in android

androidcallbackservice

提问by Ambika

I have a background service running and a client which interacts with the service.

我有一个正在运行的后台服务和一个与该服务交互的客户端。

When the client requests for some operation, the service performs it and it should send the result back to the activity (client).

当客户端请求某些操作时,服务会执行该操作并将结果发送回活动(客户端)。

I know how to invoke the service methods in activity and using call backs we can achieve what I want to do. But I am not able to understand the call back mechanism and code example provided in Api demos (remoteservice).

我知道如何在活动中调用服务方法并使用回调我们可以实现我想要做的事情。但是我无法理解 Api 演示(远程服务)中提供的回调机制和代码示例。

Could someone explain how this service callback works; or anything which is achievable using simpler mechanism.

有人可以解释这个服务回调是如何工作的吗?或使用更简单的机制可以实现的任何事情。

回答by George Nguyen

Here is the flow
Create your intent to call a service. You can either startService()or BindService()with BIND_AUTO_CREATE

这是
创建调用服务的意图的流程。你可以startService()BindService()BIND_AUTO_CREATE

Once the service is bond, it will create a tunnel to talk with it clients which is the IBinderInterface. This is used by your AIDL Interface implementation and return the IBinderin

一旦服务绑定,它将创建一个隧道与它的客户端进行通信,即IBinder接口。这是由您的AIDL接口实现并返回IBinder

private final MyServiceInterface.Stub mBinder = new MyServiceInterface.Stub() {
    public int getNumber() {
        return new Random().nextInt(100);
    }
};

public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Service OnBind()", Toast.LENGTH_LONG).show();
    return mBinder;
}

Once it returns the mBinder, ServiceConnectionthat you created in the client will be called back and you will get the service interface by using this

一旦它返回mBinderServiceConnection您在客户端创建的将被回调,您将通过使用此获取服务接口

           mConnection = new ServiceConnection() {

        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub

            mService = MyServiceInterface.Stub.asInterface(service);


    };

Now you got the mServiceinterface to call and retreive any service from that

现在你有了mService调用和检索任何服务的接口