Android 7.0 分享崩溃:android.os.FileUriExposedException

 原来的分享是这样的

Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(sourceDir)));
intent.setType("*/*");
startActivity(Intent.createChooser(intent, "分享"));

因为适配全面屏导航栏背景,targetSdkVersion 改成了24,然后分享的时候就报这个错误了。 

根据 https://blog.csdn.net/xiaoyu940601/article/details/54406725 所说,是安全策略不允许分享 file:// 开头的路径。

方法一

1.AndroidManifest.xml 增加:

<application>
    ...
   <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="完整包名"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
   </provider>
</application>

2.新建文件 res/xml/filepaths.xml:

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

 3.分享:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getApplicationContext(),"完整包名", new File(sourceDir)));
intent.setType("*/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "分享"));

方法二

他说在Application中的onCreate加上我这没成功,在Activity的onCreate后面加上成功了。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
}

方法二更简单。

最好写在 MainApplication.onCreate 中,并注册: <application android:name=".MainApplication",不注册不会运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值