/** * 安装apk * * @param context * @param apkPath */ public static void installApk(Context context, String apkPath) { try { /** * provider * 处理android 7.0 及以上系统安装异常问题 */ File file = new File(apkPath); Intent install = new Intent(); install.setAction(Intent.ACTION_VIEW); install.addCategory(Intent.CATEGORY_DEFAULT); install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Uri apkUri = FileProvider.getUriForFile(context, "com.jxzg.jxzgapp.fileprovider", file);//在AndroidManifest中的android:authorities值 Log.d("======", "apkUri=" + apkUri); install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件 install.setDataAndType(apkUri, "application/vnd.android.package-archive"); } else { install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); } context.startActivity(install); } catch (Exception e) { Log.d("======", e.getMessage()); Toast.makeText(context, "文件解析失败", Toast.LENGTH_SHORT).show(); deleteFile(apkPath); } }
androidManifest.xml 里面注册provider
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.chao.app.fileprovider" android:grantUriPermissions="true" android:exported="false"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
需要添加权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
在/res/xml/下新建 file_paths.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <paths> <external-path path="" name="download" /> </paths> </resources>
原文地址:https://www.cnblogs.com/rchao/p/9200774.html
时间: 2024-11-09 00:42:23