从AsyncTask返回数据而不阻塞UI [英] Returning data from AsyncTask without blocking UI

查看:83
本文介绍了从AsyncTask返回数据而不阻塞UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与AsyncTask类有关的概念性问题.我们使用AsyncTask,以便不会阻塞主UI. 但是假设我想从设备的内存中检索一些数据,并且为此使用了AsyncTask类.代码的相关行如下(假定返回的数据类型为String):

I have a conceptual problem related to AsyncTask class. We use AsyncTask so that the main UI is not blocked. But suppose, I want to retrieve some data from the device's memory, and I use AsyncTask class for this. The relevant line of the code will be as follows (assuming the data type returned is String):

  //code
    String data = new ExtendedAsyncTask().execute(param1, param2).get();
  //use this returned value.

以上行不会阻塞UI,从而破坏使用AsyncTask的目的吗?如果是,那么如何在不阻止UI的情况下获取相关数据?我想补充一点,下一行代码将需要此数据来执行某些任务,因此取决于返回的值.

Won't the above line block the UI, defeating the purpose of using the AsyncTask ? If yes, then how do I get the relevant data without blocking UI ? I would like to add that the next line of code will need this data to perform some task, and hence depends on the returned value.

谢谢

推荐答案

get() method will block the UI thread.要获取相关数据,您需要从doInBackground返回值,并在onPostExecute参数中捕获该值.

get() method will block the UI thread. To get the relavent data you need to return the value from doInBackground and capture the value in onPostExecute parameter.

doInBackground返回的值由onPostExecute方法捕获

Value returned by doInBackground is captured by onPostExecute method

示例:

public class BackgroundTask extends AsyncTask<String, Integer, String >{
       private ProgressDialog mProgressDialog;
       int progress;
       public BackgroundTask() {
           mProgressDialog = new ProgressDialog(context);
             mProgressDialog.setMax(100);
             mProgressDialog.setProgress(0);
    }

       @Override
    protected void onPreExecute() {
           mProgressDialog =ProgressDialog.show(context, "", "Loading...",true,false);
        super.onPreExecute();
    }
     @Override
     protected void onProgressUpdate(Integer... values) {
     setProgress(values[0]);
  }

    @Override
    protected String doInBackground(String... params) {
            String data=getDatafromMemoryCard();    

        return data;  // return data you want to use here
    }
    @Override
    protected void onPostExecute(String  result) {  // result is data returned by doInBackground
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
        mProgressDialog.dismiss();
        super.onPostExecute(result);
    }
   }


如果您在单独的类中使用asynctask,则将AsyncTask与这样的回调接口一起使用

If you are using asynctask in separate class, then use AsyncTask with callback interface like this

这是我之前提供的关于相同

Here is the answer I have provided earlier about the same AsyncTask with Callback

这篇关于从AsyncTask返回数据而不阻塞UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆