Waiting for asynchronous callback in Android's IntentService

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

    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();
        }
    
    }
    
    @Override
    public 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();
        }
    
    }
    

提交回复
热议问题