Android 7.0 FileUriExposedException 解决

从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。


    ... 
    
        ...
        
            
        
        ...
    

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


    
    ...

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 FileUriExposedException 解决)