android - 多次并行调用 AsyncTask

标签 android android-asynctask

我正在尝试从循环中调用 AsyncTask。它工作正常,但问题是执行所有请求需要花费更多时间。请建议我如何让它更快。

for (int i = 0; i < 6; i++) {
    response  = requestWeatherUpdate(location);
}

请求天气更新

private WeatherResponse requestWeatherUpdate(String location) {
        url = ""+ location;
        Log.d("URL for Weather Upadate", url);
        WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask();
        String weatherRequestResponse = "";
        try {
            weatherRequestResponse = weatherReq.execute(url).get();
            if (weatherRequestResponse != "") {
                parsedWeatherResponse = ParseWeatherResponseXML
                        .parseMyTripXML(weatherRequestResponse);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return parsedWeatherResponse;

    }

使用回调

  public class WeatherUpdateAsyncTask extends AsyncTask<String, Void, String> {
    Context context;
    CallBack callBack;

    public WeatherUpdateAsyncTask(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected String doInBackground(String... arg0) {
        String responseString = "";
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            HttpGet get = new HttpGet(arg0[0]);
            client.getParams().setParameter("http.socket.timeout", 6000);
            client.getParams().setParameter("http.connection.timeout", 6000);
            HttpResponse responseGet = client.execute(get);
            HttpEntity resEntityGet = responseGet.getEntity();
            if (resEntityGet != null) {
                responseString = EntityUtils.toString(resEntityGet);
                Log.i("GET RESPONSE", responseString.trim());
            }
        } catch (Exception e) {
            Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
        }
        Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
        client.getConnectionManager().shutdown();
        return responseString.trim();

    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        callBack.run(result);
    }

}

请求天气更新

 private WeatherResponse requestWeatherUpdate(String location) {
    url = ""
            + location;
    Log.d("URL for Weather Upadate", url);
    WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask(new CallBack() {
        @Override
        public void run(Object result) {
            try {
                String AppResponse = (String) result;
                response = ParseWeatherResponseXML
                        .parseMyTripXML(AppResponse);

            } catch (Exception e) {
                Log.e("TAG Exception Occured",
                        "Exception is " + e.getMessage());
            }
        }
    });
    weatherReq.execute(url);
    return response;

}

我在这里打电话

for (int i = 0; i < 4; i++) {
            inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            RelativeLayout layout = (RelativeLayout) inflater.inflate(
                    R.layout.sector_details, depart_arrivals_details, false);
            depart_time = (TextView)layout.findViewById(R.id.depart_time);
            depart_airport_city = (TextView)layout.findViewById(R.id.depart_airport_city);
            temprature = (TextView)layout.findViewById(R.id.temprature);
            humidity = (TextView)layout.findViewById(R.id.humidity);
            flight_depart_image = (ImageView)layout.findViewById(R.id.flight_depart_image);


            depart_time.setText("20:45");
            depart_airport_city.setText("Mumbai");
            /*
             * This part will be updated when we will se the request and get the response 
             * then we have to set the temp and humidity for each city that we have recived
             * */
            temprature.setText("");//Here i have set the values from the response i recived from the AsynkTask
            humidity.setText("");//Here i have set the values from the response i recived from the AsynkTask

            flight_depart_image.setImageResource(R.drawable.f1);

            depart_arrivals_details.addView(layout, i);
        }

最佳答案

  1. AsyncTask 上调用 get() 会阻塞调用线程。不要那样做。而是在 onPostExecute() 中将结果传递给调用者。

  2. 从 Honeycomb 开始,默认实现在串行执行器上按顺序执行异步任务。要并行运行异步任务,请使用 executeOnExecutor(THREAD_POOL_EXECUTOR, ...) 而不是 execute(...)

关于android - 多次并行调用 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19180023/

相关文章:

java - Android - 非 UI 线程渲染我的 UI 无响应

Android 单个 AsyncTask 中的多个 Web 服务调用

android - 在 AsyncTask Android 中获取 JSON

java - 异步任务变慢问题

java - 添加AsyncTask后空指针。

android - 如何在 Retrofit 中使用具有暂停乐趣的 NetworkBoundResource

android - 在 Android 上使用 native 对话框不使用 Facebook 登录按钮的 Facebook 登录

java - 带有用户滑动手势的滑动按钮

android - 如何更改工具栏上项目的颜色

java - 无法在 AsyncTask 中获取经纬度