1.在AndroidManifest.xml文件中,添加REQUEST_INSTALL_PACKAGES权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
2.在打开安装包的代码中添加兼容Android 8.0的代码。
/**
* 打开安装包
*
* @param mContext
* @param fileUri
*/
public void openAPKFile(Activity mContext, String fileUri) {
// 核心是下面几句代码
if (null != fileUri) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
File apkFile = new File(fileUri);
//兼容7.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", apkFile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//兼容8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
if (!hasInstallPermission) {
ToastUtil.makeText(MyApplication.getContext(), MyApplication.getContext().getString(R.string.string_install_unknow_apk_note), false);
startInstallPermissionSettingActivity();
return;
}
}
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
mContext.startActivity(intent);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
/**
* 跳转到设置-允许安装未知来源-页面
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private void startInstallPermissionSettingActivity() {
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}