简体   繁体   English

服务回调到android中的活动

[英]Service call backs to activity in android

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演示(remoteservice)中提供的回调机制和代码示例。

Could someone explain how this service callback works; 有人可以解释这个服务回调是如何工作的; or anything which is achievable using simpler mechanism. 或者使用更简单的机制可以实现的任何东西。

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 IBinder Interface. 一旦服务结合,它将创建一个隧道与客户端进行通信,即IBinder接口。 This is used by your AIDL Interface implementation and return the IBinder in 这将由您的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 , ServiceConnection that you created in the client will be called back and you will get the service interface by using this 一旦它返回mBinder ,您将在客户端中创建的ServiceConnection将被回调,您将通过此方式获得服务接口

           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 mService interface to call and retreive any service from that 现在你有了mService接口来调用和检索任何服务

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

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