Waiting for asynchronous callback in Android's IntentService

后端 未结 6 1616
栀梦
栀梦 2021-02-05 03:08

I have an IntentService that starts an asynchronous task in another class and should then be waiting for the result.

The problem is that the IntentSer

6条回答
  •  别跟我提以往
    2021-02-05 03:37

    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();
    
    @Override
    protected 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 invoked
    private class Callback {
        public void complete() {
            // Do whatever operation you want
    
            // Releases the lock so that intent service thread is unblocked.
            synchronized (object) {
                object.notifyAll();
            }   
        }
    }
    

提交回复
热议问题