如何在AsyncTask doInBackground()中返回异步操作的结果?

时间:2015-08-27 20:42:41

标签: java android multithreading android-asynctask

我想在doInBackground()的{​​{1}}块中进行服务器请求调用。

问题是我的服务器调用是使用回调的异步函数执行的。

AsyncTask

如何从异步函数调用中获取返回值?

3 个答案:

答案 0 :(得分:3)

看看这个架构,它有助于我理解AsyncTask enter image description here

答案 1 :(得分:0)

onPostExecute是AsyncTask将代码发布到UI的地方,如果这是你要求的。

new DownloadImageTask().execute("http://example.com/image.png");


private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
 protected Bitmap doInBackground(String... urls) {
     return loadImageFromNetwork(urls[0]);
 }

 protected void onPostExecute(Bitmap result) {
     // set image for ImageView
     mImageView.setImageBitmap(result);
 }

}

答案 2 :(得分:0)

由于您的服务器调用已经以异步方式执行,因此您无需在doInBackground()中调用它,只需使用服务器通信解决方案提供的功能。

如果您尝试使用结果数据更新UI元素并获取must be called from main thread,则需要手动将结果处理逻辑发布到UI AKA main 线程,如下所示:

ServerLoader.getSharedInstance().get(url, 
    new new AsyncCallback<GetResult<Long>>() {

    @Override
    public void onFailure(Exception e) {
    }

    @Override
    public void onSuccess(GetResult<Long> result) {
        final Long myResult = result.getValue();
        // .post() on a view is what sends stuff to UI thread
        txtView.post(new Runnable(){
            public void run(){
                txtView.setText("" + myResult);
            }
        });
    }
);

如果您在使用ServerLoader代理AsyncTask电话时绝对设置,则可以实施如下的脏垫片:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
    protected CountDownLatch mLatch = null;
    protected Long mResult = null;
    protected Long doInBackground(URL... urls) {
        if (urls == null || urls.length = 0) {
            return null;
        }

        mLatch = new CountDownLatch(1);

        ServerLoader.getSharedInstance().get(url[0], 
            new new AsyncCallback<GetResult<Long>>() {

            @Override
            public void onFailure(Exception e) {
                // leave the result null
                mLatch.countDown();
            }

            @Override
            public void onSuccess(GetResult<Long> result) {
                mResult = result.getValue();
                mLatch.countDown();
            }

        );

        // the thread that DownloadFilesTask.doInBackground()
        // gets executed on will wait till it hears from ServerLoader
        mLatch.await();
        return mResult;
    }

    protected void onPostExecute(Long result) {
        // here you get the result
    }

}