美文网首页7.0Android知识Android开发
Android 7.0 FileUriExposedExcept

Android 7.0 FileUriExposedExcept

作者: sirai | 来源:发表于2017-04-12 14:26 被阅读220次

从Android 7.0开始,一个应用提供自身文件给其它应用使用时,如果给出一个file://格式的URI的话,应用会抛出FileUriExposedException。这是由于谷歌认为目标app可能不具有文件权限,会造成潜在的问题。所以让这一行为快速失败。

http://www.jianshu.com/p/3f9e3fc38eae

1 FileProvider方式

这是谷歌官方推荐的解决方案。即使用FileProvider来生成一个content://格式的URI。具体实现方式如下:
manifest声明
在manifest中声明一个provider。name(即类名)为android.support.v4.content.FileProvider。

<manifest>
    ... 
    <application>
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xx.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
        ...
    </application>
</manifest>

其中authorities可以自定义。为了避免和其它app冲突,最好带上自己app的包名。file_paths.xml中编写该Provider对外提供文件的目录。文件放置在res/xml/下。
2.编写file_paths.xml
文件格式如下:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
    ...
</paths>

3.在Java代码当中使用
以分享一个图片为例:

 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            phonePath=getImageTempPath();
            //为了防止华为 酷派等一些手机 不能拍照的问题
            File file=new File(phonePath);
            file.createNewFile();
            //7.0  FileUriExposedException  问题
            Uri uri;
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(getContext(), "org.xx.fileprovider", file);
            } else {
                uri = Uri.fromFile(file);
            }
            // 下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CAMERA);

通过FileProvider解决,实例下载:https://github.com/honjane/fileProviderDemo

相关文章

网友评论

本文标题:Android 7.0 FileUriExposedExcept

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