在8.0的系统版本中,安装apk时有一层膜,现在就要捅了它,不然就是一闪而过,安装不上。这层膜就是
允许安装未知应用
在8.0中这个选项默认是false,只需要打开一次即可
1、manifest中添加权限
代码语言:javascript复制 <!-- 8.0安装未知应用来源 -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
2、判断是不是8.0
代码语言:javascript复制if (Build.VERSION.SDK_INT >= 26) {
boolean b = context.getPackageManager().canRequestPackageInstalls();
if (b) {
installApk();//安装应用
} else {
//请求安装未知应用来源的权限
ActivityCompat.requestPermissions(ActivityUtil.getCurrentActivity(), new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);
dialog.dismiss();
} else {
installApk();
dialog.dismiss();
}
处理回调
代码语言:javascript复制 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case INSTALL_PACKAGES_REQUESTCODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
installApk();
} else {
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GET_UNKNOWN_APP_SOURCES:
installApk();
break;
}
}