繁体   English   中英

Android下载长文件并带有取消选项

[英]Android download long file with options to cancel

我正在使用Android下载管理器。 然后,我看到了很多错误,所以基本上我去了一个意图服务来下载文件,并且从意图服务中我正在使用处理程序更新进度对话框。

在Intent服务中,我正在接受输入流,并使用输出流将输出文件写入下载文件夹中。

现在一切都OK,但是我的问题是如何为用户提供取消中间下载的选项? 我在onHandleIntent中的代码如下。

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(footyDirectory.toString()+"/demo.mp4");

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress" ,(int) (total * 100 / fileLength));
            receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();

在您的intentService中取消一个变量。 当用户想要取消时,将canceled设置为true。 在您的while循环中,检查canceled的值。 如果为true,请退出循环并进行清理,然后执行需要删除部分文件,删除通知等的所有清理工作。

声明一个boolean vairable isCanceled到您的循环内使用,并设置为true,当用户取消下载。

 while ((count = input.read(data)) != -1) {
        if(isCanceled){
           //Do your work here (close stream, delete temp file, send broadcast...)
           break;
        }
        total += count;
        // publishing the progress....
        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,(int) (total * 100 / fileLength));
        receiver.send(UPDATE_PROGRESS, resultData);
        output.write(data, 0, count);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM