添加权限
<!--安卓8.0打开apk安装更新-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
调用安装前先判断系统版本,8.0以上系统提示开启 “允许未知来源权限”,无此权限时 一般系统会自动弹框提示开启
private void openFile(final Context context) {
//判读版本是否在8.0以上
if (Build.VERSION.SDK_INT >= 26) {
//来判断应用是否有权限安装apk
boolean installAllowed= context.getPackageManager().canRequestPackageInstalls();
if(installAllowed){
installApk(context);
}else {
installApk(context);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
ToastUtil.ToastShort(context,"请设置开启允许安装未知应用");
//此处只做提示,系统会自动弹框提醒,并可跳转开启
// Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.getPackageName()));
// context.startActivity(intent);
}
});
}
} else {
installApk(context);
}
}
安装APK:
private void installApk(Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
Uri uri=FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", new File(mPath + zipFileName));
//context.grantUriPermission(BuildConfig.APPLICATION_ID,uri,Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//允许临时的读和写
intent.setDataAndType(uri,
"application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.fromFile(new File(mPath + zipFileName)),
"application/vnd.android.package-archive");
}
context.startActivity(intent);
}