Android开发经验谈Android开发android学习

android 7.0 文件获取正确姿势

2018-10-23  本文已影响23人  androidman
android快速开发工具类

关于

Fastandrutils 是一套整理修改整合的android开发常用的工具类。
这样可以减少复制粘贴代码,从而减少重复代码,也不用为了一个常用的功能去谷歌百度,让代码更简洁,让开发更高效。
同时希望您的添加完善,让android开发变得更简单。

github地址,感兴趣的话,不妨点赞支持下
个人博客

在SDK升级到Android N,通过Uri.fromFile(file)获取Uri报 android.os.FileUriExposedException异常,因为在Android 7.0系统上,Android框架强制执行了StrictMode API政策禁止向应用外公开file:// URI, 如果Intent包含了file://类型的URI离开应用,抛出异常,退出程序。

正确姿势一

粗暴解决问题

 // 置入一个不设防的VmPolicy(不设置的话 7.0以上一调用拍照功能就崩溃)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

正确姿势二

正常流程
使用FileProvider

1.配置AndroidManifest.xml

添加

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" /><!-- 对应xml文件夹下的provider_paths.xml -->
        </provider>

2.在res文件夹下插件xml文件夹

  1. xml文件夹下创建provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <root-path name="root" path="" />
</paths>
  1. 代码获取Uri
Uri uri = null;
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getContext(), authorities, new File(filePath));
            } else {
                uri = Uri.fromFile(new File(filePath));
            }

完毕

上一篇 下一篇

猜你喜欢

热点阅读