Creating HTTP service for API communication

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);
}

Your freezing issue happens because service methods run on the main UI thread by default. Services don’t create background threads automatically - you’ve got to handle that yourself. You can definitely drop AIDL since everything’s in the same process. Try a simple bound service with regular Java interfaces, or better yet, use IntentService which handles background threading for you. I’ve hit similar problems and wrapping HTTP calls in AsyncTask or ExecutorService fixed the blocking right away. You might also want to check out Retrofit with RxJava or WorkManager if you’re on newer Android versions. The real problem is your fetch method runs synchronously on whatever thread calls it. Move that network stuff to a background thread and use callbacks or broadcasts to update your UI when it’s done. Way simpler than your current AIDL mess.

your service setup’s way too complex for intra-app communication. The UI freeze happens because fetch() blocks the main thread - services don’t automatically run in the background. use a simple bound service with regular interfaces and put network calls in an AsyncTask or executor. i dropped AIDL for similar stuff and switched to EventBus instead. much cleaner with way less boilerplate.

You’re overcomplicating this. Since everything’s in the same process, ditch AIDL and use LocalBroadcastManager or direct callbacks instead. Your app freezes because you’re doing network calls on the main thread - even with a service, that fetch call runs synchronously wherever you call it. Wrap your HTTP stuff in ExecutorService or ThreadPoolExecutor inside the service methods. I hit this same issue recently and switched to a singleton HTTP manager with CompletableFuture. Fixed both the complexity and UI blocking. Try OkHttp with enqueue for async requests, then broadcast results back through LocalBroadcastManager. Kills the AIDL overhead and handles threading properly.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.