Android异步任务完成



代码爆炸。我需要在循环中调用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++;
      }     
}

删除这一行…

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()方法更新进度更新。要了解更多细节,您可以查看Android Developer站点的AsyncTask文档。

相关内容

  • 没有找到相关文章

最新更新