android 7.0 抛出 FileUriExposedException异常

官方解释

参考官方解释 https://developer.android.com/reference/android/os/FileUriExposedException.html

解决办法 https://developer.android.com/reference/android/support/v4/content/FileProvider.html

大致处理步骤:

1. 在mainfest中加入FileProvider注册
<manifest>
    ...
    <application>
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="App包名.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
             <meta-data
                   android:name="android.support.FILE_PROVIDER_PATHS"
                   android:resource="@xml/file_paths" />
        </provider>
        ...
    </application>
</manifest>
2. 新建res/xml/file_paths.xml文件
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
    <files-path name="my_docs" path="docs/"/>
</paths>
<paths> 中可以定义以下子节点
子节点对应路径示例
files-pathContext.getFilesDir()<files-path name="name" path="path" />
cache-pathContext.getCacheDir()<cache-path name="name" path="path" />
external-pathEnvironment.getExternalStorageDirectory()<external-path name="name" path="path" />
external-files-pathContext#getExternalFilesDir(String) Context.getExternalFilesDir(null)<external-files-path name="name" path="path" />
external-cache-pathContext.getExternalCacheDir()<external-cache-path name="name" path="path" />

3. 使用示例

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "App包名.fileprovider", newFile);

4. 遇到的问题

Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

原因:mainfest中 android:authorities 与 代码 FileProvider.getUriForFile(getContext(), "App包名.fileprovider", newFile);App包名.fileprovider不一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值