public class DownloadFileFromURL extends AsyncTask<String, String, String> {
public String url;
public String pathLoc;
public String imgName;
private OnPreExecute mPreExecute;
private OnProgressUpdated mProgress;
private OnResultCompleted mProgCompleted;
public DownloadFileFromURL(String url, String pathLoc, String imgName, OnPreExecute preExecute, OnProgressUpdated progressUpdated, OnResultCompleted progressCompleted) {
this.setUrl(url);
this.setPathLoc(pathLoc);
this.setImgName(imgName);
this.mPreExecute = preExecute;
this.mProgress = progressUpdated;
this.mProgCompleted = progressCompleted;
}
protected void onPreExecute() {
super.onPreExecute();
if (mPreExecute != null) mPreExecute.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(getUrl());
URLConnection conection = url.openConnection();
conection.connect();
OutputStream output = null;
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 819200);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + getPathLoc();
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
// Output stream
output = new FileOutputStream(path + "/" + getImgName());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (mProgCompleted != null) mProgCompleted.onResult(result);
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
if (mProgress != null) mProgress.onProgress(progress[0]);
}
public interface OnPreExecute {
public void onPreExecute();
}
public interface OnProgressUpdated {
public void onProgress(String... progress);
}
public interface OnResultCompleted {
public void onResult(String result);
}
/* Setter Getter*/
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPathLoc() {
return pathLoc;
}
public void setPathLoc(String pathLoc) {
this.pathLoc = pathLoc;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
}