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?
Basically you need a way for your
Serviceto callback to the client that initiated the HTTP request. There are several possibilities:PendingIntentto theService, which theServicecan then trigger to return data/status to the client. ThisPendingIntentcan either start anActivity, aBroadcastReceiveror anotherServicedepending on your needs.Servicecan send a broadcastIntent, 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 broadcastIntent(ACTION, data, "extras", whatever).Serviceand AIDL. This is somewhat more complicated, but you can create a set of interfaces that you can use to communicate between the client andService, 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.