I want to communicate from my Android Application to my Android Service. I've two options but I don't know which to choose:
Solution 1
The application:
public class MyApplication extends Application {
MyService myService;
public void setMyService(MyService myService) {
this.myService = myService;
}
public void testCallService(){
myService.sendResponseApdu("test".getBytes());
}
}
and the service:
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?
Solution 2
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
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.
https://stackoverflow.com/a/5066187/2839624
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With