Need help with background HTTP service implementation
I want to build a background service that handles web API requests. The main goal is to start this service when my app launches, then send HTTP requests through it while showing loading dialogs to users.
Right now I have a working service that uses AIDL interfaces, but I read that AIDL is mainly for communication between different apps. Since I only need this within my own app, maybe I can simplify it. But I’m not sure how to handle callbacks without AIDL.
Another problem is that when I call fetch(ApiEndpoints.getAuthUrl(), parameters), my app freezes for several seconds. I thought services were supposed to run on separate threads to avoid this issue.
My current setup includes:
- A service class with GET and POST methods
- Two AIDL interface files for callbacks
- A ServiceController class that handles binding and lifecycle
- Dynamic Handler creation for different callback types
I don’t need complete code solutions, just some guidance on the right approach.
Here’s my main service class:
public class HttpApiService extends Service {
final RemoteCallbackList<IServiceCallback> callbacks = new RemoteCallbackList<IServiceCallback>();
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public IBinder onBind(Intent intent) {
return serviceStub;
}
public void onCreate() {
super.onCreate();
}
public void onDestroy() {
super.onDestroy();
callbacks.kill();
}
private final IHttpService.Stub serviceStub = new IHttpService.Stub() {
public void performAuth(String user, String pass) {
Message message = new Message();
Bundle bundle = new Bundle();
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("user", user);
parameters.put("pass", pass);
String response = fetch(ApiEndpoints.getAuthUrl(), parameters);
bundle.putString("result", response);
message.setData(bundle);
message.what = Constants.AUTH_ACTION;
messageHandler.sendMessage(message);
}
public void addCallback(IServiceCallback callback) {
if (callback != null)
callbacks.register(callback);
}
};
private final Handler messageHandler = new Handler() {
public void handleMessage(Message message) {
final int count = callbacks.beginBroadcast();
for (int i = 0; i < count; i++) {
try {
switch (message.what) {
case Constants.AUTH_ACTION:
callbacks.getBroadcastItem(i).onAuthComplete(message.getData().getString("result"));
break;
default:
super.handleMessage(message);
return;
}
} catch (RemoteException e) {
}
}
callbacks.finishBroadcast();
}
public String fetch(String endpoint, HashMap<String, String> params) {...}
public String retrieve(String endpoint) {...}
};
}
Interface files:
package com.myapp.android
oneway interface IServiceCallback {
void onAuthComplete(String response);
}
package com.myapp.android
import com.myapp.android.IServiceCallback;
interface IHttpService {
void performAuth(in String user, in String pass);
void addCallback(IServiceCallback callback);
}