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

相关推荐
沙振宇8 分钟前
【HarmonyOS】ArkTS开发应用的横竖屏切换
android·华为·harmonyos
橙子199110162 小时前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin2 小时前
Kotlin 懒初始化值
android·开发语言·kotlin
枣伊吕波3 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
萧然CS3 小时前
使用ADB命令操作Android的apk/aab包
android·adb
_extraordinary_7 小时前
MySQL 事务(二)
android·数据库·mysql
鸿蒙布道师11 小时前
鸿蒙NEXT开发动画案例5
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
橙子1991101616 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin
androidwork16 小时前
Kotlin Android LeakCanary内存泄漏检测实战
android·开发语言·kotlin
笨鸭先游17 小时前
Android Studio的jks文件
android·ide·android studio