Search This Blog

Showing posts with label URLConnection. Show all posts
Showing posts with label URLConnection. Show all posts

Saturday, November 23, 2013

Download the large file from the server

Download the large file from the server asynchronously in android with the below code....

call this:

new DownloadFileAsync(YourActivity.this).execute();

And your DownloadFileAsync is as below:

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
int count;

try {

// URL url = new URL(DOWNLOAD URL);

URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
File filedir = new File(path);
// have the object build the directory structure, if needed.
filedir.mkdirs();
OutputStream output = new FileOutputStream(path + name + ".zip");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile),
name);
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
}
return null;

}

protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setMessage("Downloading " + progress[1] + ".....");
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
new UnzipFile(BookDownloadActivity.this, path + name + ".zip", path)
.execute();
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}


This is how you can download the whole file from the server or any other URLs.