brian
brian

Reputation: 6912

Some download troubles in Android

I use below code to download file:

URL u = new URL(one.getSrcPath());
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setReadTimeout(10000);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + SavePath, FileName);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int finishbyte = 0;
long total = 0;
while((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
f.write(buffer, 0, len1);
finishbyte++;
}
f.close();

I have two problems: First, why my download task download fail very high frequency? Second, if I want my download task resume from break point. I have get the finishbyte. How can I modify?

Upvotes: 1

Views: 314

Answers (2)

njzk2
njzk2

Reputation: 39386

finishbyte both does not represent any information (except the number of calls to the read method, but certainly not the size of the downloaded file), and is not relevant, since you have written to a file and can use the File.length() method to know how much you got so far.

To resume a download:

Open your file, check the size, request a range using the http header that is:

Range: <file.length()>-

(example, if you have downloaded 234 bytes:

Range: 234-

If the response code from the server is 206 Partial Content, you can append to your file, if it is 200, you have to overwrite your file (content have changed or Range is not supported)

Upvotes: 1

zrgiu
zrgiu

Reputation: 6322

To start downloading a file starting with finishbyte position, you will have to use the Range HTTP header. As for the failed downloads problem, it's probably a network issue or phone sleep issue, in which case you should check out the wifi lock

Upvotes: 1

Related Questions