【问题标题】:How to get result from AsyncTask without blocking UI thread?如何在不阻塞 UI 线程的情况下从 AsyncTask 获取结果?
【发布时间】:2017-02-22 01:54:18
【问题描述】:

我有扩展AsyncTask 的外部类从网站获取字符串以将其解析为JSONObjectJSONArray。目前我正在使用方法.get() 来获取结果,但是应用程序正在丢帧,同时等待服务器响应。我想使用它可重用,因为我从许多不同的类中获取数据。 我的 Asynctask 类:

public class JsonTask extends AsyncTask<String, String, String> {
   protected String doInBackground(String...params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            Log.d("Response: ", "> Establishing Connection" );
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
                Log.d("Response: ", "> " + line);

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }}

现在我通过以下方式获取数据:

    String result = new JsonTask().execute(url).get();

【问题讨论】:

  • @RichArt - 可能是因为 AsyncTask.execute() 返回异步任务实例本身,而不是 String 或任何其他类型的结果。

标签: java android json multithreading android-asynctask


【解决方案1】:

根据 get 方法的文档:

如有必要,等待计算完成,然后检索其结果。

因此它会阻塞 UI,直到它完成将返回结果的后台任务。

您可以在JsonTask 中创建一个接受doInBackground 的返回值的侦听器,onPostExecute 将调用该侦听器。

【讨论】:

    【解决方案2】:

    我想你可以再读一遍document

    当一个异步任务执行时,该任务会经过4个步骤:

    1. onPreExecute()
    2. doInBackground(参数...)
    3. onProgressUpdate(进度...)
    4. onPostExecute(Result),在后台计算完成后在 UI 线程上调用。后台计算的结果作为参数传递给这一步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多