例如,我正在从服务器下载文件,在连接中断时,我的下载进度为30%,过了一段时间后,我重新连接。现在我想从30%开始下载,而不是从0%开始。如何在asynctask android中实现这一点。
如果有其他替代方法,请告诉我吗?
如果有其他替代方法,请告诉我吗?
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指出,您只能从一个来源获取信息,因此应该从下载的文件中读取进度。
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);
}