版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40391500/article/details/87882867
1、安装权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
2、在AndroidManifest.xml中添加
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="包名.fileprovider"
android:grantUriPermissions="true"
android:exported="false"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
3、在res/xml下新建file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<!--
path:需要临时授权访问的路径(.代表所有路径)
name:就是你给这个访问路径起个名字
-->
<!-- 拍照获取图片 -->
<external-path path="external_files" name="headIcon" />
<root-path path="." name="root_path"/>
<!-- 安装apk -->
<external-path path="Android/data/com.ovo.bbj.bbj/" name="apk_file"/>
<external-path path="." name="external_storage_root"/>
</paths>
</resources>
4、安装APK文件
public void installApk(File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(MyApplication.context,"包名.fileprovider", file);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(contentUri,"application/vnd.android.package-archive");
}else{
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
}
MyApplication.context.startActivity(intent);
}