class DownloadAsyncTask extends AsyncTask<String[], Integer, String> {
private String fileName;
private long length;
DownloadAsyncTask(String fileName) {
this.fileName = fileName;
}
@Override
protected void onPreExecute() {
mProgressLayout.setVisibility(View.VISIBLE);
mBtnUpdate.setVisibility(View.GONE);
mBtnBack.setVisibility(View.GONE);
mProgressBar.setIndeterminate(false);
mBtnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DownloadAsyncTask.this.cancel(true);
mProgressLayout.setVisibility(View.GONE);
mBtnUpdate.setVisibility(View.VISIBLE);
mBtnBack.setVisibility(View.VISIBLE);
mBtnUpdate.setText(R.string.upgrade_now);
}
});
super.onPreExecute();
}
@Override
protected String doInBackground(String[]... params) {
InputStream is = null;
String[] fileInfos = params[0];
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(fileInfos[0]);
HttpResponse response;
response = client.execute(get);
HttpEntity entity = response.getEntity();
length = entity.getContentLength();
mProgressBar.setMax((int) (length / 1024));
is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(fileInfos[1], fileInfos[2]);
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
if (isCancelled()) {
break;
}
fileOutputStream.write(buf, 0, ch);
count += ch;
publishProgress((int) (count / 1024));
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileInfos[2];
}
@Override
protected void onProgressUpdate(Integer... values) {
String size = FileManager.formartFileSize(length);
String downloadSize = FileManager.formartFileSize(values[0] * 1024);
mProgressBar.setProgress(values[0]);
mProgressPersent.setText(values[0] * 1024 * 100 / length + "%");
mProgressSize.setText(downloadSize + "/" + size);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Message msg = Message.obtain(mHandler,
MessageWhat.ACTION_DOWNLOAD_COMPLETED, this.fileName);
mHandler.sendMessage(msg);
super.onPostExecute(result);
}
}