如何在for循环内同步执行AsyncTasks

时间:2017-09-22 07:45:41

标签: android for-loop android-asynctask

switch (view.getId()) {

      case R.id.trimmBttn:
        final Integer stime[] = { 2, 4, 7, 9, 12, 18 };
        final Integer endTime[] = { 4, 6, 9, 11, 15, 20 };

        Thread thread = new Thread(new Runnable() {
          @Override public void run() {
            for (int i = 0; i < stime.length; i++) {

              trimmVideo = new TrimmVideo(getExternalFilesDir(null) + "/12.mp4", stime[i],
                  endTime[i]).execute();
            }
          }
        });

        thread.start();

        try {
          thread.join();
        } catch (InterruptedException e) {

        }

        break;
    }




    private class TrimmVideo extends AsyncTask<Void, Void, Void> {
    private String mediaPath;
    private double startTime;
    private double endTime;
    private int length;
    private ProgressDialog progressDialog;

    private TrimmVideo(String mediaPath, int startTime, int length) {
      this.mediaPath = mediaPath;
      this.startTime = startTime;
      this.length = length;
      this.endTime = this.startTime + this.length;
    }

    @Override protected void onPreExecute() {
      progressDialog = ProgressDialog.show(context, "Trimming videos", "Please wait...", true);
      super.onPreExecute();
    }

    @Override protected Void doInBackground(Void... params) {
      trimVideo();
      return null;
    }

    @Override protected void onPostExecute(Void result) {
      progressDialog.dismiss();
      super.onPostExecute(result);
    }

这是我的代码我想在for循环中同步执行Asyck任务,即 当循环从0开始然后为0值完成任务然后它应该开始值下一个asynk任务执行如果1被编译然后为2等等...请建议我我尝试使用线程加入但仍然不工作。

3 个答案:

答案 0 :(得分:0)

您可以按顺序使用异步任务

new TrimmVideo(getExternalFilesDir(null) + "/12.mp4", stime[i],
              endTime[i]).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR)
像这样。

可能对你有帮助。

答案 1 :(得分:0)

为什么不从onPostExecute()发出新的异步请求?

替代解决方案: How do I run Async tasks synchronously without post execute chaining?

答案 2 :(得分:0)

您可以执行以下操作:

 Integer[] stime;
 Integer[] endTime;

switch (view.getId()) {
  case R.id.trimmBttn:
     stime = new Integer[]{2, 4, 7, 9, 12, 18};
     endTime = new Integer[]{ 4, 6, 9, 11, 15, 20 };

    trimmVideo = new TrimmVideo().execute();

    break;
}

并在doInBackground()方法中使用forloop,如下所示

@Override
    protected Void doInBackground(Void... params) {
        for (int i = 0; i < stime.length; i++) {
        trimVideo(trimVideo(getExternalFilesDir(null) + "/12.mp4", stime[i],
              endTime[i]));
        }
        return null;
    }

通过仅创建一个AsyncTask对象实例来保存内存