这与我以前的帖子Problem with downloading multiple files using AsyncTask如何取回任务的完成状态中的AsyncTask
我试图下载两个视频文件,并在过程中表现出ProgressDialog。为此,我使用AsyncTask。我想要第一次下载完成,释放内存然后开始第二次下载。我写了下面的代码来实现这一点,但似乎从未开始第二次下载。
startDownload() {
DownloadFileAsync d1 = new DownloadFileAsync();
d1.execute(videoPath+fileNames[0],fileNames[0]);
if(d1.getStatus()==AsyncTask.Status.FINISHED) {
d1 = null;
DownloadFileAsync d2 = new DownloadFileAsync();
d2.execute(videoPath+fileNames[1],fileNames[1]);
}
}
有没有一种方法,我可以拿回我的第一个任务的完成状态&然后开始第二次?
以下是我DownloadFileAsync类的代码:
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
File root = android.os.Environment.getExternalStorageDirectory();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(root.getAbsolutePath() + "/videos/" + aurl[1]);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
tv.append("\n\nFile Download Completed!");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
}
但是在真正的应用程序中,我不得不下载几个文件,而不仅仅是2.那么,有没有其他的方式来实现这个目标? – Sourav 2011-02-24 11:24:19
我试着在while while(d1.getStatus()== AsyncTask.Status.RUNNING){...}放一个while循环,但整个应用程序停滞不前。所以,我想知道是否有更好的方法来做到这一点。 – Sourav 2011-02-24 11:35:31
我在onPostExecute()方法中保留了第二次下载的代码。但第二个任务继续执行无数次。请告诉我如何实现5个连续任务的逻辑(下载) – Sourav 2011-02-24 11:49:29