如何在异步任务(AsyncTask)中恢复下载进度

4
例如,我正在从服务器下载文件,在连接中断时,我的下载进度为30%,过了一段时间后,我重新连接。现在我想从30%开始下载,而不是从0%开始。如何在asynctask android中实现这一点。
如果有其他替代方法,请告诉我吗?

将您的值存储在共享首选项中,您的问题就会得到解决。 - Pankaj Lilan
2个回答

1
你需要先确定你已经下载了多少字节。我建议在文件下载时使用不同的名称保存,这样你就可以轻松地看到是否有未完成的下载。
首先检查文件状态,看看你已经下载了多少。
private long isIncomplete(){
        File from = new File(dir,fileName+"-incomplete");
        if(from.exists()){
            Log.d("status","download is incomplete, filesize:" + from.length());
            return from.length();
        }
        return 0;
}

当创建http请求时,您可以告诉服务器从哪个点开始为您提供文件,以便您可以恢复下载。

long downloaded = isIncomplete();
urlConnection.setRequestProperty("Range", "bytes="+(downloaded)+"-");

几年前,我写了一个完整的实现,请查看this class

更新: 我建议您不要使用Shared Preferences。 SSOT指出,您只能从一个来源获取信息,因此应该从下载的文件中读取进度。


0
您可以将目标文件路径存储在sharedpreferences中,并使用以下代码执行。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//Opening the url

    File file=new File(DESTINATION_PATH);
    if(file.exists()){    //check if file exists
         downloaded = (int) file.length();
         connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
    }
else{
    connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
pBar.setMax(connection.getContentLength());
 in = new BufferedInputStream(connection.getInputStream());
 fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
 bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
    bout.write(data, 0, x);
     downloaded += x;
     pBar.setProgress(downloaded);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接