Android更新apk兼容7.0和8.0
作者:互联网
/**
* 判断版本
*/
private void checkVersionUpdate(final Context mContext, final File file) {
if (Build.VERSION.SDK_INT >= 26) {
boolean b = getPackageManager().canRequestPackageInstalls();
if (b) {
installApk(mContext, file);
} else {
//请求安装未知应用来源的权限
String[] permissions = {Manifest.permission.REQUEST_INSTALL_PACKAGES};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, 11);
}
}
} else {
installApk(mContext, file);
}
}
public void installApk(Context mContext, File file) {
Uri fileUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//通过FileProvider创建一个content类型的Uri用于适配7.0
fileUri = FileProvider.getUriForFile(mContext, "com.bingding.richtext.app.fileprovider", file);
} else {
fileUri = Uri.fromFile(file);
}
Intent it = new Intent();
it.setAction(Intent.ACTION_VIEW);
it.setDataAndType(fileUri, "application/vnd.android.package-archive");
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 防止打不开应用
it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 兼容7.0
startActivityForResult(it,111);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
List<String> deniedPermissions = getDeniedPermissions(permissions, grantResults);
boolean agreeAll = deniedPermissions.isEmpty();
if (requestCode == 11) {
if (permissions.length > 0 && grantResults.length > 0 && agreeAll) {
installApk(MainActivity.this, newApkFile);
} else {
showToast("请设置允许安装应用");
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent, 1122);
}
}
}
记得配置清单文件
file_paths文件
标签:8.0,mContext,apk,7.0,VERSION,Intent,Build,file,permissions 来源: https://blog.csdn.net/SMITHKANG/article/details/97113711