Waiting for asynchronous callback in Android's IntentService Waiting for asynchronous callback in Android's IntentService android android

Waiting for asynchronous callback in Android's IntentService


Use the standard Service class instead of IntentService, start your asynchronous task from the onStartCommand() callback, and destroy the Service when you receive the completion callback.

The issue with that would be to correctly handle the destruction of the Service in the case of concurrently running tasks as a result of the Service being started again while it was already running. If you need to handle this case, then you might need to set up a running counter or a set of callbacks, and destroy the Service only when they are all completed.


I agree with corsair992 that typically you should not have to make asynchronous calls from an IntentService because IntentService already does its work on a worker thread. However, if you must do so you can use CountDownLatch.

public class MyIntentService extends IntentService implements MyCallback {    private CountDownLatch doneSignal = new CountDownLatch(1);    public MyIntentService() {        super("MyIntentService");    }    @Override    protected final void onHandleIntent(Intent intent) {        MyOtherClass.runAsynchronousTask(this);        doneSignal.await();    }}@Overridepublic void onReceiveResults(Object object) {    doneSignal.countDown();}public interface MyCallback {    public void onReceiveResults(Object object);}public class MyOtherClass {    public void runAsynchronousTask(MyCallback callback) {        new Thread() {            public void run() {                // do some long-running work                callback.onReceiveResults(...);            }        }.start();    }}


If you are still looking for ways to use Intent Service for asynchronous callback, you can have a wait and notify on thread as follows,

private Object object = new Object();@Overrideprotected void onHandleIntent(Intent intent) {    // Make API which return async calback.    // Acquire wait so that the intent service thread will wait for some one to release lock.    synchronized (object) {        try {            object.wait(30000); // If you want a timed wait or else you can just use object.wait()        } catch (InterruptedException e) {            Log.e("Message", "Interrupted Exception while getting lock" + e.getMessage());        }    }}// Let say this is the callback being invokedprivate class Callback {    public void complete() {        // Do whatever operation you want        // Releases the lock so that intent service thread is unblocked.        synchronized (object) {            object.notifyAll();        }       }}