从应用程序进行通信,以服务 [英] Communicate from Application to Service
问题描述
我想从我的Android应用程序进行通信,以我的Android服务。我有两个选择,但我不知道该选择:
I want to communicate from my Android Application to my Android Service. I've two options but I don't know which to choose:
- 注册服务与应用程序
- 使用LocalBinder从应用到服务连接。
解决方法1
应用程序:
public class MyApplication extends Application {
MyService myService;
public void setMyService(MyService myService) {
this.myService = myService;
}
public void testCallService(){
myService.sendResponseApdu("test".getBytes());
}
}
和服务:
public class MyService extends HostApduService {
@Override
public void onCreate() {
super.onCreate();
((MyApplication)getApplication()).setMyService(this);
}
@Override
public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) {
return new byte[0];
}
@Override
public void onDeactivated(int reason) {
}
}
要调用的应用程序使用的参考服务的服务。 该服务是本地服务。 (未远程服务) 将在所有情况下,这种方式工作?
To call the service the application uses the reference to the service. The Service is a local service. (not a remote service) Will this approach work in all circumstances?
解决方案2
使用的本地服务的方法与ServiceConnection绑定到服务上符合<一个例子href="http://developer.android.com/reference/android/app/Service.html#LocalServiceSample">http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
Use the LocalService approach with a ServiceConnection to bind to the service conform the example on http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
解决方案2将工作。将在实施例1的工作吗?什么是(DIS)的解决方案1相比的优点解决方案2?
Solution 2 will work. Will example 1 work too? What are the (dis)advantages of solution 1 compared to solution 2?
推荐答案
作为每官方机器人文档,服务是为了在后台执行长时间运行操作,如果有显著量服务和活动之间的相互作用,它们建议使用绑定服务。之所以使用绑定服务是绑定具有优势,丰富的通信接口。
As per official android documentation, service are meant to perform long running operations in background and if there is significant amount of interaction between service and activities, they recommend to use the bound services. The reason for using bound services is that Binding has advantage of rich interface for communication.
http://stackoverflow.com/a/5066187/2839624
我工作的一个类似的应用程序,我选择了绑定服务,出于同样的原因从活动的通信通过接口来服务,并使用Localbroadcastreceiver通信从服务活动,以活动。
I was working on a similar application where I chose the bound services for the same reason with communication from activity to service via interface and communicating events from service to activity using Localbroadcastreceiver.
这篇关于从应用程序进行通信,以服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!