Android 如何在AsyncTask中恢复任务完成状态

Android 如何在AsyncTask中恢复任务完成状态,android,synchronization,android-asynctask,Android,Synchronization,Android Asynctask,这与我以前的帖子有关 我正在尝试下载两个视频文件,并在此过程中显示ProgressDialog。为此,我使用AsyncTask。我希望第一次下载完成,释放内存,然后开始第二次下载。我编写了以下代码来实现这一点,但第二次下载似乎从未开始 startDownload() { DownloadFileAsync d1 = new DownloadFileAsync(); d1.execute(videoPath+fileNames[0],fileNames[0]); if(d1.g

这与我以前的帖子有关

我正在尝试下载两个视频文件,并在此过程中显示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())));            
    }
}
class DownloadFileAsync扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
showDialog(对话框下载进度);
}
@凌驾
受保护的字符串背景(字符串…aurl){
整数计数;
试一试{
URL=新URL(aurl[0]);
URLConnection conexion=url.openConnection();
conexion.connect();
文件根=android.os.Environment.getExternalStorageDirectory();
int lenghtOfFile=conexion.getContentLength();
Log.d(“ANDRO_ASYNC”,“文件长度:“+lenghtOfFile”);
InputStream输入=新的BufferedInputStream(url.openStream());
OutputStream output=新文件OutputStream(root.getAbsolutePath()+“/videos/”+aurl[1]);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
出版进度(“+(int)((总计*100)/长度文档));
输出.写入(数据,0,计数);
}
output.flush();
output.close();
input.close();
}捕获(例外e){}
返回null;
}
受保护的void onProgressUpdate(字符串…进度){
Log.d(“ANDRO_ASYNC”,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@凌驾
受保护的void onPostExecute(字符串未使用){
dismissDialog(对话框下载进度);
追加(“\n\n文件下载完成!”);
sendBroadcast(新的Intent(Intent.ACTION\u MEDIA\u挂载,Uri.parse(“文件:/”+Environment.getExternalStorageDirectory()));
}
}

从第一个onPostExecute方法开始第二次下载

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())));            

        // Here you start your new AsyncTask...
    }
此代码:

if(d1.getStatus()==AsyncTask.Status.FINISHED) {
 d1 = null;
 DownloadFileAsync d2 = new DownloadFileAsync();
 d2.execute(videoPath+fileNames[1],fileNames[1]);
}


…将执行一次,并在第一个异步任务执行后立即执行,因此它将始终为false。如果你想走这条路,你需要在一个while循环中完成它——这就违背了任务异步的初衷。

正如DKIT Android建议的那样,你可以从onPostExecute开始第二次下载,但前提是download2为空

@Override
protected void onPostExecute(String unused) 
{

   if (d2 == null)
   {
       d2 = new DownloadFileAsync();
       d2.execute(videoPath+fileNames[1],fileNames[1]);    
   }    
}

如果需要开始更多下载,只需在asynctask之外编写方法,该方法将检查下一步应该开始哪个下载。

但在实际应用程序中,我必须下载多个文件,而不仅仅是2个文件。那么,有没有其他方法来实现这一点呢?我尝试在while(d1.getStatus()==AsyncTask.Status.RUNNING){…}处放置一个while循环,但是整个应用程序都停止了。因此,我想知道是否有更好的方法来实现这一点。我将第二次下载的代码保存在onPostExecute()方法中。但是第二个任务持续执行了无数次。请告诉我如何为5个连续任务(下载)实现此逻辑。您可以编写for循环来启动dowdload任务实例并开始批量下载。如果您希望第一次下载完成,请释放内存,然后开始第二次下载。