我从Web服务获取文件列表,然后使用AsyncTask处理所有文件的下载。每个任务中的回路形成:如果我在循环中调用它100次以上,AsyncTask会崩溃吗?
for(int i = 0; i < arraySize; i++) {
//Omitted all code except for the portion that fires the asynctask
//Download the PDF
DownloadHandler dhpdf = new DownloadHandler(cleanLink, fileName, p1, DownloadPosters.this, "pdf");
dhpdf.startDownload();
//Download the PNG
DownloadHandler dhpng = new DownloadHandler(cleanLink, fileName, p1, DownloadPosters.this, "png");
dhpng.startDownload();
}
的下载类
public class DownloadHandler extends Activity {
private Context mContext;
//File ======================
public String filename;
private String remotePath;
private File file;
private String ext;
//Progress bar ==============
private ProgressBar progressBar;
private int progressStatus = 0;
//private Handler handler = new Handler();
private TextView mTextView;
//ProgressDialog ============
ProgressDialog mProgress;
private int mProgressDialog=0;
public DownloadHandler(String rp, String f, ProgressBar progressBar, Context c, String extension, TextView textview) throws Exception {
mContext = c;
remotePath = rp;
filename = f;
file = new File(mContext.getFilesDir(), filename+"."+extension);
ext = extension;
this.progressBar = progressBar;
mTextView = textview;
}
//our method
public void startDownload() {
String url = "http://examplesite.com/"+remotePath+"/"+filename+"."+ext;
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, Integer, String> {
@Override
public void onPreExecute() {
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
mTextView.setText("Downloading: "+ext);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in internal storage
OutputStream output = new BufferedOutputStream(new FileOutputStream(file));
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress which triggers onProgressUpdate method
publishProgress((int) ((total * 100)/lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {mTextView.setText("ERROR:"+e.toString());}
return null;
}
@Override
protected void onPostExecute(String unused) {
mTextView.setText("Complete");
}
}
现在我只能测试大约6个文件,它似乎运作良好。
我的问题是,如果这是排队多个下载的正确方法,并且这可以处理100多个文件,而不会崩溃?
对不起,但我看不到AsyncTask。并且您在该循环中没有使用参数“i”。所以你在做什么是非常模糊的。 – greenapps 2014-12-05 22:57:41