Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicate from Application to Service

I want to communicate from my Android Application to my Android Service. I've two options but I don't know which to choose:

  1. Register the service with the application
  2. Use the LocalBinder to connect from the Application to the service.

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?

like image 499
userM1433372 Avatar asked Oct 31 '22 17:10

userM1433372


1 Answers

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.

like image 184
pratsJ Avatar answered Nov 09 '22 22:11

pratsJ