欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 7.0行为变更 FileUriExposedException解决方法

程序员文章站 2023-11-17 08:57:46
android 7.0行为变更 fileuriexposedexception解决方法 当我们开发关于【在应用间共享文件】相关功能的时候,在android 7.0上经常会...

android 7.0行为变更 fileuriexposedexception解决方法

当我们开发关于【在应用间共享文件】相关功能的时候,在android 7.0上经常会报出此运行时异常,那么android 7.0以下没问题的代码,为什么跑到android 7.0+的设备上运行就出问题了呢?,这主要来自于android 7.0的一项【行为变更】!

对于面向 android 7.0 的应用,android 框架执行的 strictmode api 政策禁止在您的应用外部公开 file:// uri。如果一项包含文件 uri 的 intent 离开您的应用,则应用出现故障,并出现 fileuriexposedexception 异常。如图:

Android 7.0行为变更 FileUriExposedException解决方法

要在应用间共享文件,您应发送一项 content:// uri,并授予 uri 临时访问权限。进行此授权的最简单方式是使用 fileprovider 类。

fileprovider 类的用法:

第一步:为您的应用定义一个fileprovider清单条目,这个条目可以声明一个xml文件,这个xml文件用来指定应用程序可以共享的目录。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.myapp">
  <application
    ...>
    <provider
      android:name="android.support.v4.content.fileprovider"
      android:authorities="com.example.myapp.fileprovider"
      android:granturipermissions="true"
      android:exported="false">
      <meta-data
        android:name="android.support.file_provider_paths"
        android:resource="@xml/filepaths" />
    </provider>
    ...
  </application>
</manifest>

在这段代码中, android:authorities 属性应该是唯一的,推荐使用【应用包名+fileprovider】,推荐这样写

android:authorities=”${applicationid}.file_provider”,可以自动找到应用包名。

meta-data标签指定了一个路径,这个路径使用resource指定的xml文件来指明是那个路径:

xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-files-path name="bga_upgrade_apk" path="upgrade_apk" />
</paths>

uri的获取方式也要根据当前android系统版本区分对待:

  file dir = getexternalfilesdir("user_icon");
    if (build.version.sdk_int > build.version_codes.m) {
      icon_path = fileprovider.geturiforfile(getapplicationcontext(),
          "com.mqt.android_headicon_cut.file_provider", new file(dir, temp_file_name));
    } else {
      icon_path = uri.fromfile(new file(dir, temp_file_name));
    }

这样问题就解决了。贴上一个安装apk适配7.0的例子:

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!