解决 Android N 上 安装Apk时报错:android.os.FileUriExposedException: file:///storage/emulated/0/Download/appN
2023-09-27 14:27:47 时间
解决方法:、
1、在AndroidManifest.xml中添加如下代码
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="app的包名.fileprovider"
android:grantUriPermissions="true"
android:exported="false"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
注意: authorities:app的包名.fileProvider grantUriPermissions:必须是true,表示授予 URI 临时访问权限 exported:必须是false resource:中的@xml/file_paths是我们接下来要添加的文件
2、在res目录下新建一个xml文件夹,并且新建一个file_paths的xml文件(如下图)
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/app的包名/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
path:需要临时授权访问的路径(.代表所有路径) name:就是你给这个访问路径起个名字
4、修改代码适配Android N
public static void installApkFile(Context context, String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, "com.yuneec.android.saleelfin.fileprovider", new File(filePath));
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
1、首先我们对Android N及以上做判断; 2、然后添加flags,表明我们要被授予什么样的临时权限 3、以前我们直接 Uri.fromFile(apkFile)构建出一个Uri,现在我们使用FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", apkFile); 4、BuildConfig.APPLICATION_ID直接是应用的包名
再贴一个启动相机的
public static void startCamera(Activity activity) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//适配7.0拍照取uri的处理
if(Build.VERSION.SDK_INT < 24){
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
Environment.getExternalStorageDirectory(), TMP_PATH)));
}else{
Uri uri= FileProvider.getUriForFile(activity,"com.huikeyun.teacher.fileprovider",new File(
Environment.getExternalStorageDirectory(), TMP_PATH));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION );//添加这一句表示对目标应用临时授权该Uri所代表的文件
}
activity.startActivityForResult(intent, CAMERA_WITH_DATA);
}
相关文章
- Android 异常 android.os.NetworkOnMainThreadException
- Android LayoutInflater 使用详解 View.inflate 的加载原理
- 精通Android自定义View(十七)自定义圆形鸟巢加载转圈效果
- Android匿名共享内存(Ashmem)原理
- Android surfaceview详解
- android中的string.xml
- Android视图动画集合AndoridViewAnimations
- android颜色值的表示方法android:background="#FFFFFFFF"的意思
- android 事件处理机制之requestDisallowInterceptTouchEvent
- Android图像滤镜框架GPUImage从配置到应用
- Android应用开发之(通过ClipboardManager, ClipData进行复制粘贴)
- android开发设置dialog的高宽
- android技术牛人的博客[转]
- android中常见的内存泄漏和解决的方法
- android 自己定义控件
- Android 事件分发机制具体解释
- 【转载】 Android ListView性能优化之视图缓存