服务回调到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
Service call backs to activity in android
提问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 IBinder
Interface. This is used by your AIDL Interface implementation and return the IBinder
in
一旦服务绑定,它将创建一个隧道与它的客户端进行通信,即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
, 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
调用和检索任何服务的接口