Android 7.0以上拍照引发的血案

作者: 吴蜀黍 | 来源:发表于2017-12-28 14:03 被阅读114次

前言

在一个风和日丽的上午,我开心的码着我的代码.......功能:修改用户信息,上传头像,balabalabala完工,在测试机跑一把[5.0],完美。装自己手机[7.0]上看下UI效果,嗯~~不错,来换个头像,点相机,崩了!!!不信邪?再点,在崩!有点懵逼,最后一看日志如下:


图片.png

就google了一把,了解到是从Android 7.0开始,一个应用提供自身文件给其它应用使用时,如果给出一个file://格式的URI的话,应用会抛出FileUriExposedException,就是我上面的那张图。

解决办法如下

  • 在AndroidManifest.xml中添加如下代码
<application />
    ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>
    ...
</application>
  • 在res目录下新建一个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="" />
    <files-path
        name="files"
        path="." />

    <cache-path
        name="cache"
        path="." />

    <external-path
        name="external"
        path="." />

    <external-files-path
        name="external_file_path"
        path="." />
    <external-cache-path
        name="external_cache_path"
        path="." />
</paths>
  • 使用
    public static Uri getUriForFile(Context context, File file) {
        Uri fileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

相关文章

网友评论

    本文标题:Android 7.0以上拍照引发的血案

    本文链接:https://www.haomeiwen.com/subject/gtzmgxtx.html