private void downloadFile(String apk){
//下载进度条设置
if(this.progress==null){
this.progress = new ProgressDialog(this);
this.progress .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.progress .setTitle("更新包下载");
this.progress.setMax(100);
//设置ProgressDialog 是否可以按退回按键取消
this.progress.setCancelable(true);
this.progress.setCanceledOnTouchOutside(false);
//显示
this.progress.show();
}
//url设置,okhttp设置
final String url =apk;
final long startTime = System.currentTimeMillis();
Log.i("DOWNLOAD","startTime="+startTime);
OkHttpClient okHttpClient = new OkHttpClient();
//CALL 请求
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
is = response.body().byteStream();
long total = response.body().contentLength();
File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
// 下载中
loading(progress);
}
fos.flush();
// 下载完成
loadingFinish(file.getPath());
} catch (Exception e) {
e.printStackTrace();
loadingFailure();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
public void loading(int progress) {
this.progress.setProgress( progress);
}
public void loadingFinish(String path) {
this.progress.dismiss();
String fileName = path;
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setDataAndType(Uri.fromFile(new File(fileName) ), "application/vnd.android.package-archive");
startActivity(i);
}
public void loadingFailure() {
this.progress.dismiss();
}
通过OKHTTP实现版本下载
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 这里对于App在微信开放平台上申请AppID和secret在这里就略过了,我们微信的授权登录流程,腾讯官网给的流程...
- 断点下载/续传 断点下载是针对下载大文件需求的一种优化机制,可以从上次下载的断点处继续下载。断点续传原理也相同,只...