I want to be able to open a http connection to a given file in Android and start downloading it. I also have to be able to pause the download at some point and resume it later. How is this achieved in Android? I don't want to start the download all over again.
Asked
Active
Viewed 9,679 times
7
-
1Have you see this http://stackoverflow.com/questions/6237079/resume-http-file-download-in-java – laxonline Jan 20 '13 at 09:14
-
@laxonline great thanks! If you post this as an answer I can accept it and close this one. – gop Jan 20 '13 at 09:38
1 Answers
1
Such a downloader has been posted here:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){
File file=new File(DESTINATION_PATH);
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);
progressBar.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;
progressBar.setProgress(downloaded);
}
-
3
-
code first check if there is downloaded bytes on storage as file, for example you downloaded 120 byte, it will set request for connection and only asked for 120 to end of file. another part is setting progress to connection length . thats easy part. – Vahab Ghadiri Apr 25 '20 at 10:31
-
what if there is download from other range? for example 120 to 240, and we dont want to have 2 connections ( to get from 0 to 121, 241 to end ) ??? this will happen in multi connection downloads. – Vahab Ghadiri Apr 25 '20 at 10:33