如何在AsyncTask中获取任务完成状态

发布于 2024-10-19 01:03:17 字数 2496 浏览 0 评论 0原文

这与我之前的帖子使用 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())));            
    }
}

This is related to my previous post Problem with downloading multiple files using AsyncTask

I'm trying to download two video files and also show a ProgressDialog during the process. For this I'm using AsyncTask. I want the 1st download to complete, free up memory then start the 2nd download. I wrote the following code to achieve this, but it seems the 2nd download never begins.

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]);
   }
}

Is there a way that I can get back the completion status of my 1st task & then start the 2nd ?

The following is the code of my DownloadFileAsync class:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素染倾城色 2024-10-26 01:03:17

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

@Override
protected void onPostExecute(String unused) 
{

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

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

As DKIT Android suggested, you could start the second download from onPostExecute, but only if for example download2 is null

@Override
protected void onPostExecute(String unused) 
{

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

If you need to start more downloads, just write the method outside of your asynctask, which will check which download should be started next.

雨巷深深 2024-10-26 01:03:17

从第一个 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]);

}

...将执行一次,并在第一个 AsyncTask 执行后立即执行,因此它始终为 false。如果你想走这条路,你需要在 while 循环中完成它 - 这违背了首先使任务异步的目的。

Start your second download from within your first onPostExecute-method.

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...
    }

This code:

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

}

...will execute once, and immediately after the first AsyncTask is executed, thus it will always be false. If you want to go that route, you need to do it in a while loop - which kind of defeats the point of making the task Async in the first place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文