Waiting for asynchronous callback in Android's IntentService

后端 未结 6 1676
栀梦
栀梦 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:45

    I agree, it probably makes more sense to use Service directly rather than IntentService, but if you are using Guava, you can implement an AbstractFuture as your callback handler, which lets you conveniently ignore the details of synchronization:

    public class CallbackFuture extends AbstractFuture implements MyCallback {
        @Override
        public void onReceiveResults(Object object) {
            set(object);
        }
    
        // AbstractFuture also defines `setException` which you can use in your error 
        // handler if your callback interface supports it
        @Override
        public void onError(Throwable e) {
            setException(e);
        }
    }
    
    
    

    AbstractFuture defines get() which blocks until the set() or setException() methods are called, and returns a value or raises an exception, respectively.

    Then your onHandleIntent becomes:

        @Override
        protected final void onHandleIntent(Intent intent) {
            CallbackFuture future = new CallbackFuture();
            MyOtherClass.runAsynchronousTask(future);
            try {
                Object result = future.get();
                // handle result
            } catch (Throwable t) {
                // handle error
            }
        }
    

    提交回复
    热议问题