Android更新APK
由于版本的不同导致跟新出问题
首先在AndroidManifest.xml里面添加:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
然后在Android--》res-->xml里面添加 file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<paths>
<!--external-path用来指定Uri共享的
name属性的值可以随便填
path属性的值表示共享的具体路径,这里设置为空代表将整个SD卡进行共享,当然你也可以共享存放的图片地址-->
<external-path name="my_apk" path="/"/>
</paths>
</resources>
其他的就是执行下载和安装的过程:
下载APK:
/**
* 下载更新APK
* @param path 新版本的APK下载链接地址
*/
private File apkFile;
public void downloadAPK(final String path) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
//准备用于保存apk文件的file对象 放在sd卡里面
apkFile = new File(Environment.getExternalStorageDirectory() + File.separator, "update.apk");
//启动分线程下载数据,显示下载进度
new Thread(new Runnable() {
@Override
public void run() {
try {
//1 得到链接对象
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) {
//设置dialog最大进度
dialog.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);
dialog.incrementProgressBy(len);
}
fos.close();
is.close();
}
connection.disconnect();
//主线程,移除dialog,启动安装
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
//安装下载好的APK
installAPK();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
下载完成后执行安装:
/**
* 启动安装apk
*/
private void installAPK() {
/**
* 允许安装未知来源的应用
*/
try {
android.provider.Settings.Global.putInt(this.getContentResolver(),
android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 1);
} catch (SecurityException e) {
//LogUtils.getInstance().d(e);
}
String fileName = apkFile.getName();
int index = fileName.lastIndexOf(".");
String nameExtra = fileName.substring(index + 1, fileName.length());
if (nameExtra.equals("apk")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 7) { //20200616 android10以上版本安装没有权限报错问题解决
Uri apkUri = FileProvider.getUriForFile(this, "com.sky.hs.hsb_whale_steward.provider", apkFile); //与manifest中定义的provider中的authorities保持一致
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
this.startActivity(intent);
}
}