Android N 应用间共享文件

今天在测试时发现调用播放器打开Android/data/com.myself.suifeng.app/cache下的视频文件时报错:android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.myself.suifeng.app/cache/abc.mp4 exposed beyond app through Intent.getData(),模拟器中又是正常的,查了资料后发现是Android N 中有新的要求,在Stack Overflow找到了解决方法,解决完问题记录一下,希望能帮到有用的朋友

下面贴上我自己的解决过程:

1.在AndroidManifest中添加provider节点

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

android:authorities的值是包名.FileProvider
android:exported 必须为false
android:grantUriPermissions 表示临时授予访问权限

2.在res的xml目录下创建file_paths.xml

Android N共享文件报错:android.os.FileUriExposedException_第1张图片

内容如下:

这里写图片描述

这里的external-path表示外部存储设备,具体的解释可以看这里
如果要共享的文件在SD卡上可以这样写

<external-path name="external_files" path="."/>

或者在某个目录下可以这样写

<external-path path="images/" name="myimages" />

而且官方提到这个xml文件可以包含多条内容这里写图片描述

3.修改代码

Intent intent = new Intent();intent.setAction("android.intent.action.VIEW");Uri videoUri ;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {    //申请权限    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);    //getUriForFile的第二个参数就是Manifest中的authorities    videoUri = FileProvider.getUriForFile(context, "com.myself.suifeng.qqredpoint.FileProvider", file);} else {    videoUri = Uri.fromFile(file);}intent.setDataAndType(videoUri, "video/*");context.startActivity(intent);

搞定!

仓促写完,如果有不对的地方还请大神指点!

更多相关文章

  1. Android 扫描SDCard上的音乐文件以及监听扫描事件
  2. android文件下载
  3. android界面xml文件中导入另一个xml文件的方法include
  4. Unity各平台上读写文件-Android例子
  5. ionic 发布android,并查看签名文件。
  6. Android Studio:正确引入so文件的方法
  7. SAX解析XML文件

随机推荐

  1. Android Intent多种传值方式
  2. android标题栏去除和全屏
  3. android实现ftp上传、下载,支持文件夹
  4. Android Q 使用通知栏消息
  5. viewPager的简单实现
  6. Android使用Retrofit上传单个文件以及多
  7. Android反射机制
  8. Using Android Volley With Self-Signed
  9. Flutter在Android(安卓)Studio上的初启动
  10. android如何在子线程中更新UI