public class DownloadTask extends AsyncTask<Void, Integer, String> {
ProgressDialog progressDialog;
Context ctx;
String downUrl;
public DownloadTask(Context ctx, String downUrl) {
this.ctx = ctx;
this.downUrl = downUrl;
progressDialog = new ProgressDialog(ctx);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
}
@Override
protected String doInBackground(Void... params) {
String returnDownloadFileName = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 15000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet get = new HttpGet(downUrl);
InputStream is = null;
FileOutputStream fileOutputStream = null;
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null && entity.getContentLength() > 512) {
long length = entity.getContentLength();
is = entity.getContent();
if (is != null) {
fileOutputStream = ctx.openFileOutput(FileUtil.getFileName(downUrl),Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);
returnDownloadFileName = ctx.getFilesDir().getPath() + "/"+ FileUtil.getFileName(downUrl);
byte[] buf = new byte[2048];
int len = -1;
int byteReadCount = 0;
while ((len = is.read(buf)) != -1) {
byteReadCount += len;
fileOutputStream.write(buf, 0, len);
publishProgress((int) ((byteReadCount / (float) length) * 100));
}
fileOutputStream.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
if (is != null)
is.close();
client.getConnectionManager().shutdown();
} catch (IOException ex) {
}
}
return returnDownloadFileName;
}
@Override
protected void onPostExecute(String result) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
install(result);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
public void install(String path)throws Exception {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
ctx.startActivity(intent);
}
Android代码工具集——apk的下载和进度条的显示
最新推荐文章于 2022-04-02 17:39:35 发布