Android异步任务完成

时间:2014-03-22 13:01:23

标签: android mobile android-asynctask

我代码打击。 我需要在循环中调用execute。 问题是我需要在执行完成时暂停循环,然后继续。 循环运行但它立即调用execute,这导致文件无法下载。

private class DownloadVerses extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        try {
            //Thread.sleep(5000);
            if(Utils.downloadFile(params[0])){
                int progressPercentage = Integer.parseInt(params[2]);
                downloadProgress.setProgress(progressPercentage);
                return "Downloading: "+params[1];

            }
            else{
                return "ERROR Downloading: "+params[1];
            }
        } catch (Exception e) {
            Thread.interrupted();
            return "ERROR Downloading: "+params[1];
        }


    }

    @Override
    protected void onPostExecute(String result) {

        if(result.contains("ERROR")){
            downloading.setTextColor(Color.parseColor("#f05036"));

        }
        else{
            downloading.setTextColor(Color.parseColor("#79a1ad"));

        }

        downloading.setText(result);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

我正在尝试:

DownloadVerses download = new DownloadVerses();

  int i = 0;
  while(i < verseTitles.size()){

      String progressString = String.valueOf(progress);

      if(download.getStatus() != AsyncTask.Status.RUNNING){
          download.execute(Mp3s.get(i), Titles.get(i),progressString);


              if(progress < 100){

                  if((progress + increment) > 100){
                      progress = 100;
                  }
                  else{
                      progress += increment;
                  }

              }
              i++;
      }     
}

1 个答案:

答案 0 :(得分:0)

删除此行...

DownloadVerses download = new DownloadVerses();

每次创建一个DownloadVerses的新对象来执行新的AsyncTask ...此过程不会阻止任何AsyncTask执行,它将允许每AsyncTask new DownloadVerses().execute(Mp3s.get(i), Titles.get(i),progressString); 独立执行。

  int i = 0;
  while(i < verseTitles.size()){

      String progressString = String.valueOf(progress);

      if(download.getStatus() != AsyncTask.Status.RUNNING){

          new DownloadVerses().execute(Mp3s.get(i), Titles.get(i),progressString);


              if(progress < 100){

                  if((progress + increment) > 100){
                      progress = 100;
                  }
                  else{
                      progress += increment;
                  }

              }
              i++;
      }     
  }

更新您的代码,如下所示......

onProgressUpdate()

<强>更新

您可以使用{{1}}方法更新进度更新。有关详细信息,您可以在Android开发者网站上查看AsyncTask文档。