我從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