注:本人已经在android 4.4、Android7.1、Android 9.0测试已通过!
1、最终安装apk的代码
public static void installApk(Context context, String apkPath) {
if (context == null || TextUtils.isEmpty(apkPath)) {
return;
}
File file = new File(apkPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
//判读版本是否在7.0以上
if (Build.VERSION.SDK_INT >= 24) {
Log.v(TAG,"7.0以上,正在安装apk...");
//provider authorities
Uri apkUri = FileProvider.getUriForFile(context, "com.luminal.mjptouch.fileprovider", file);
//Granting Temporary Permissions to a URI
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
Log.v(TAG,"7.0以下,正在安装apk...");
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
2、Android8.0、9.0需要请求未知来源应用安装权限
在AndroidManifest添加权限
<!--安卓8.0打开apk安装更新-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
参考文章: