What is the best way of passing an handler function to a service in Android?

47 Views Asked by At

The problem I'm trying to create a service that makes all the Http Request of my application to my backend. Different endpoints give different outputs, so I basically need an handler function for every endpoint.

Some code This is my service (I simplified the code to make it more readable).

public class HttpRequestService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("PPLSERV", "onStartCommand");

        // HttpRequest is an object that contains HttpMethod, values and the endpoint of the request
        HttpRequest req = intent.getParcelableExtra("REQ");

        makeHttpRequest(req, new Response.Listener {
                   @Override
                    public void onResponse(Response response) {
                        // response handler
                    }
                });

       }
}

I need the code for // response handler.

My solution I was thinking about creating this handler method inside my HttpRequest object, and modify it by Overriding it:

HttpRequest request = new HttpRequest() {
    @Override
    public void responseHandler(Response response) {
        // do stuff
     }
}

This solution doesn't work, because the object gets parceled (intent.putExtra), then unparceled (intent.getParcelableExtra) and by doing this the Override gets lost.

Possible ideas Since methods behaviour is not persistent across parceling, I was thinking about:

  • binding the service
  • using a Broadcast Receiver

I should mention that making a class that has such method (maybe with an interface) for every endpoint is not an option.

How should I handle this? Is there a better way of structuring the code?

1

There are 1 best solutions below

0
David Wasser On

Basically you need a way for your Service to callback to the client that initiated the HTTP request. There are several possibilities:

  • Client can pass a PendingIntent to the Service, which the Service can then trigger to return data/status to the client. This PendingIntent can either start an Activity, a BroadcastReceiver or another Service depending on your needs.
  • Service can send a broadcast Intent, which the client can be listening for. There are various ways to do this depending on your situation. The client could pass in some data which can be used to customize/configure the broadcast Intent (ACTION, data, "extras", whatever).
  • Use a bound Service and AIDL. This is somewhat more complicated, but you can create a set of interfaces that you can use to communicate between the client and Service, either synchronously or asynchronously.

There is no correct answer. There are multiple possibilities and you should choose the one that works best for your situation.