bug exposed beyond app through Intent.getData()

转载大神,用于自己学习

今天在做项目功能的时候遇到一个bug exposed beyond app through Intent.getData()

在项目中点击文件路径跳转过去,编译器报错android os FileUriExposedException

导致错误的原因是没有使用FileProvider

在应用间共享文件

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

解决方法

在AndroidManifest中配置 FileProvider

复制代码
<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths_public" />
        </provider>

其中${applicationId}一般指向包名

不是androidx的可以参考

复制代码
<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/file_paths_public" />
</provider>

还需要res下创建xml文件夹,并在xml文件夹下创建file_paths_public.xml

复制代码
 <!--1、对应内部内存卡根目录:Context.getFileDir()-->
    <files-path
        name="int_root"
        path="/" />
    <!--2、对应应用默认缓存根目录:Context.getCacheDir()-->
    <cache-path
        name="app_cache"
        path="/" />
    <!--3、对应外部内存卡根目录:Environment.getExternalStorageDirectory()-->
    <external-path
        name="ext_root"
        path="pictures/" />
    <!--4、对应外部内存卡根目录下的APP公共目录:Context.getExternalFileDir(String)-->
    <external-files-path
        name="ext_pub"
        path="/" />
    <!--5、对应外部内存卡根目录下的APP缓存目录:Context.getExternalCacheDir()-->
    <external-cache-path
        name="ext_cache"
        path="/" />

使用方法

复制代码
 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
  Uri contentUri = FileProvider
  .getUriForFile(OrderManagerActivity.this, "com.jk.house", file);
  intent.setDataAndType(contentUri, "*/*");

作者:吕氏春秋

链接:https://juejin.cn/post/6939823618918449166

相关推荐
vocal2 小时前
【我的安卓第一课】Android 多线程与异步通信机制(1)
android
顾林海2 小时前
ViewModel 销毁时机详解
android·面试·android jetpack
恋猫de小郭4 小时前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
@Ryan Ding4 小时前
MySQL主从复制与读写分离概述
android·mysql·adb
移动开发者1号5 小时前
Android 同步屏障(SyncBarrier)深度解析与应用实战
android·kotlin
移动开发者1号5 小时前
深入协程调试:协程调试工具与实战
android·kotlin
雨白13 小时前
Jetpack系列(三):Room数据库——从增删改查到数据库平滑升级
android·android jetpack
花王江不语16 小时前
android studio 配置硬件加速 haxm
android·ide·android studio
江太翁18 小时前
mediapipe流水线分析 三
android·mediapipe
与火星的孩子对话19 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip