在异步任务或异步任务中执行多个任务,并从postexecute返回数据

时间:2014-02-28 14:22:00

标签: java android android-asynctask

我有API我用来检索各种频道的直播有线电视的每日时间表。我有一个场景,我需要指导哪种方法应该在这里工作。

假设我需要API的10个不同频道的时间表。

  • 我应该execute 10个不同的async tasks来检索所需的数据吗?

问题: 如何在arraylist中收集数据并在完成所有执行后返回? onpostexecute返回结果后,如何访问main函数中的arraylist?

  • 或者我应该只为我的单async task提供频道列表,并让它为我调用它的主函数构建一个arraylist输出?

问题: 由于我将为此目的访问webservice,与第一种方法相比,它是否会使它运行缓慢? 这种方法的第二个问题与我的第一个问题相同,我需要知道在任务执行完成后何时以及如何获得完整的resultset

以下是一些解释问题的代码:

//going with the first approach
//invoking my asynctask from an activity or another class

//I need a global arraylist which I can use after postexecute returns its result
ArrayList<String> channels = channelManager.getAllChannelsByRegion("xyz");
        final ArrayList<ChannelSchedule> schedules = new ArrayList<ChannelSchedule>();
        final ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
        for (int i = 0; i < channels.size(); ++i){
            AsyncInvokeURLTask task = null;
            try {
                task = new AsyncInvokeURLTask(
                    channels.get(i), context, new AsyncInvokeURLTask.OnPostExecuteListener() {
                        @Override
                        public void onPostExecute(String result) {
                            // TODO Auto-generated method stub                                                          
                            try {
//Need to add results to arraylist here...But cannot know when it ends completely
                                ChannelSchedule schedule = mapper.readValue(result, ChannelSchedule.class);
                                Log.v("channel name", schedule.getChannelName());
                                Log.v("channel date", schedule.getDate());
                                Log.v("channel thumb", schedule.getListOfShows().get(0).getShowThumb());
                                Log.v("channel time", schedule.getListOfShows().get(0).getShowTime());
                            } catch (JsonParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (JsonMappingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            task.execute();
        }

如果有什么不清楚或遗漏,请告诉我。

1 个答案:

答案 0 :(得分:1)

启动10个AsyncTask非常好。

您可以保留待处理请求数的计数。由于OnPostExecute在UI线程上运行,因此不存在竞争条件的风险。

private int numberOfPendingRequests;

public void MyFunc() {
  ArrayList<String> channels = channelManager.getAllChannelsByRegion("xyz");
  final ArrayList<ChannelSchedule> schedules = new ArrayList<ChannelSchedule>();
  final ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
  numberOfPendingRequests = channels.size();
  for (int i = 0; i < channels.size(); ++i) {
    schedules.add(null);
  }
  for (int i = 0; i < channels.size(); ++i) {
    AsyncInvokeURLTask task = null;
    final int index = i;  // final so it can be used in the onPostExecute.
    try {
      task = new AsyncInvokeURLTask(
        channels.get(i), context, new AsyncInvokeURLTask.OnPostExecuteListener() { 
          @Override public void onPostExecute(String result) {
            try {
              ChannelSchedule schedule = mapper.readValue(result, ChannelSchedule.class);
              Log.v("channel name", schedule.getChannelName());
              Log.v("channel date", schedule.getDate());
              Log.v("channel thumb", schedule.getListOfShows().get(0).getShowThumb());
              Log.v("channel time", schedule.getListOfShows().get(0).getShowTime());
              schedules.set(index, schedule);
              numberOfPendingRequests--;
              if (numberOfPendingRequests == 0) {
                // Everything is received, do stuff here.
              }
            } catch (JsonParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          }
       });
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    task.execute();
  }
}