服务回调到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).
我知道如何在活动中调用服务方法并使用回调我们可以实现我想要做的事情.但是我看不懂Api demos(remoteservice)中提供的回调机制和代码示例.
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).
有人能解释一下这个服务回调是如何工作的吗?或使用更简单的机制可以实现的任何事情.
Could someone explain how this service callback works; or anything which is achievable using simpler mechanism.
推荐答案
流程如下
创建调用服务的意图.您可以使用 BIND_AUTO_CREATE
一旦服务绑定,它将创建一个隧道与它的客户端进行通信,即IBinder
界面.这由您的 AIDL 接口实现使用,并在
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
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;
}
一旦它返回mBinder
,你在客户端创建的ServiceConnection
就会被回调,你将通过这个获取服务接口
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
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);
};
现在你有了 mService
接口来调用和检索任何服务
Now you got the mService
interface to call and retreive any service from that
这篇关于服务回调到android中的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!