所需权限:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /><!-- 安装应用请求,Android8.0需要 --><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
AndroidManifest.xml 文件里设置provider
<!-- android:grantUriPermissions 必须设置为true --><providerandroid:name="androidx.core.content.FileProvider"android:authorities="@string/file_provider"android:grantUriPermissions="true"><!-- 配置哪些路径是可以通过FileProvider访问的 --><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" /></provider>
res/xml/file_paths.xml
<paths><external-pathname="external_storage_download"path="Download" /></paths>
主要代码:
private void installApk() {String apkPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString() + "/study_android-release.apk";// 获取包应用管理器PackageManager pm = getPackageManager();// 获取apk文件的包信息PackageInfo pi = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);if (pi == null) {Log.d("AAAA", "包文件已损坏");return;}// installerUri uri = Uri.parse(apkPath);// 兼容Android7,把访问文件的Uri方式改为FileProviderif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// 通过FileProvider获得文件的Uri访问方式uri = FileProvider.getUriForFile(this, getString(R.string.file_provider), new File(apkPath));}Intent intent = new Intent(Intent.ACTION_VIEW);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 设置Uri的数据类型为APK文件intent.setDataAndType(uri, "application/vnd.android.package-archive");// 启动系统自带的应用安装程序startActivity(intent);}
案例代码