public void downloadFile() {
//下载地址
final String url = HttpClient.baseUrl + "/Public/reception_android/youApp.apk";
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Call call = client.newCall(request);
Response response = null;
try {
response = call.execute();
//获取下载的内容输入流
ResponseBody body = response.body();
InputStream inputStream = body.byteStream();
final long lengh = body.contentLength();
// 文件保存到本地
File file = new File(dir, "youApp.apk");
FileOutputStream outputStream = new FileOutputStream(file);
int lien = 0;
int losing = 0;
byte[] bytes = new byte[1024];
while ((lien = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, lien);
losing += lien;
final float i = losing * 1.0f / lengh;
int ii = (int) (i * 100);
Message msg = handler.obtainMessage();
msg.arg1 = ii;
msg.what = 1;
handler.sendMessage(msg);
}
outputStream.flush();
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
//进度条
progressBar.setProgress(msg.arg1);
tvLoading.setText("加载进度:" + msg.arg1 + "%");
if (msg.arg1 == 100) {
installAPK();
}
}
}
};
/**
* 下载本地后执行安装
*/
private void installAPK() {
File apkFile = new File(dir, "youApp.apk");
if (!apkFile.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", apkFile);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
Uri uri = Uri.parse("file://" + apkFile.toString());
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
getContext().startActivity(intent);
}