Android N(7.0) 遇到 android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()

用Android7.0测试拍照的时候,出现异常android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()
是因为从Android N开始,要在应用间共享文件,需要发送一项 content://URI,并授予 URI 临时访问权限。
Android提供FileProvider来简单实现
实现方法:
1.在manifest中添加provider

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...>
    <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/mis_provider_paths"/>
        </provider>
    </application>
</manifest>

2.在res目录下新建一个xml文件夹,并且新建一个mis_provider_paths的xml文件

Paste_Image.png
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="camera_photos" path="."/>
</paths>

上面代表可以用外部存储的任意位置
如果只想在picture文件夹下读写

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="camera_photos" path="picture"/>
</paths>

3.代码中调用相机

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", file);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, code);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,595评论 25 708
  • 大家好,一直想着写点什么来在记叙开发中遇到的问题和解决方案,激励自己,分享给需要的小伙伴! 话说自从google出...
    Cui_IT阅读 1,115评论 0 1
  • Android7.0发布已经有一个多月了,Android7.0在给用户带来一些新的特性的同时,也给开发者带来了新的...
    东经315度阅读 1,382评论 0 14
  • 一、写在前面 在我的iOS开发学习过程中,阅读过许多同学的高仿项目文章、源码,对我助益颇深。但是许许多多的高仿项目...
    halohily阅读 9,368评论 30 282
  • “多么想和你见一面,在街角的咖啡店,我会带着笑脸,挥手寒暄,和你坐着聊聊天…”耳朵里回荡着听了一遍又一遍的歌词,...
    在下公孙阅读 273评论 0 0