Waiting for asynchronous callback in Android's IntentService

后端 未结 6 1615
栀梦
栀梦 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

    My favorite option is to expose two similar methods, for example:

    public List getDogsSync();
    public void getDogsAsync(DogCallback dogCallback);
    

    Then the implementation could be as follows:

    public List getDogsSync() {
        return database.getDogs();
    }
    
    public void getDogsAsync(DogCallback dogCallback) {
        new AsyncTask>() {
            @Override
            protected List doInBackground(Void... params) {
                return getDogsSync();
            }
    
            @Override
            protected void onPostExecute(List dogs) {
                dogCallback.success(dogs);
            }
        }.execute();
    }
    

    Then in your IntentService you can call getDogsSync() because it's already on a background thread.

提交回复
热议问题