today I'm trying to implement a file download, with a notification about how many bytes are downloaded already (Like "1Mb of 150Mb downloaded"). However, I'm stuck in some maths.
class DescarregarFitxer extends AsyncTask<String,String,String>{
final String rutaDesti;
final String urlOrigen;
URLConnection urlConnect;
View v;
byte[] buffer = new byte[8 * 1024];
public DescarregarFitxer(String rutaDesti, String urlOrigen, View v){
this.rutaDesti = rutaDesti;
this.urlOrigen = urlOrigen;
this.v = v;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
try{
int size = 0;
int counter = 0;
URL url = new URL(urlOrigen);
urlConnect = url.openConnection();
size = urlConnect.getContentLength();
productView.this.callBackDownload(v, "{'action':'start','size':'"+size+"'}");
InputStream input = urlConnect.getInputStream();
try {
OutputStream output = new FileOutputStream(rutaDesti);
try {
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
counter+=buffer.length;
productView.this.callBackDownload(v, "{'action':'update','size':'"+size+"','counter':'"+counter+"'}");
}
} finally {
output.close();
}
} finally {
input.close();
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
productView.this.callBackDownload(v, "{'action':'done'}");
}
}
As you can see in the above code, several things must be noted:
- As soon as download starts, I get the lenght of the file to be downloaded.
- Every loop on the while, I've a callback to update a TextView with the size downloaded.
I've everything I need, but I am not sure what do now.
Example:
- File size: 9383138 bytes
- Every Loop: 8192 bytes
However, I did this in the callback:
Log.d("debugging","we downloaded: "+counter+" of "+size);
And when it ends, it says:
we downloaded : 26206208 of 9383138
As you can see, some of my calculations are wrong. Maybe I'm doing maths with different kind of units.
Can you help me?
Thanks!!