如何在不阻止UI线程的情况下从AsyncTask获取结果?

时间:2017-02-22 01:54:18

标签: java android json multithreading android-asynctask

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

1 个答案:

答案 0 :(得分:0)

我想你可以再次阅读document

执行异步任务时,任务将经历4个步骤:

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