1.简单的示例
//点击下载apk并安装
public void button_apk(View view) {
//主线程显示提示视图
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
//file对象存放在sd卡中(公有的)
apkFile = new File(getExternalFilesDir(null), "update.apk");
//启动子线程 下载apk 并显示进度
new Thread(new Runnable() {
@Override
public void run() {
try {
String path = "http://192.168.1.5:8080/20190313/app-debug.apk";
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
connection.connect();
//得到响应
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
progressDialog.setMax(connection.getContentLength());//文件大小
InputStream is = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(apkFile);
//边读边写
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
//显示下载进度
progressDialog.incrementProgressBy(len); //注意设置他的最大值(最大值等于文件大小//
SystemClock.sleep(50);
}
is.close();
fos.close();
}
//下载完成 关闭
connection.disconnect();
//切换到主线程 启动安装
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.dismiss(); //取消精度条
//安装apk
installApk();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//安装apk
private void installApk() {
Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);
}
动态获取权限的问题 更美的进度条 等等 这只是个最基础的示例。