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

相关推荐
浩浩乎@18 分钟前
【openGLES】安卓端EGL的使用
android
Kotlin上海用户组2 小时前
Koin vs. Hilt——最流行的 Android DI 框架全方位对比
android·架构·kotlin
zzq19962 小时前
Android framework 开发者模式下,如何修改动画过度模式
android
木叶丸2 小时前
Flutter 生命周期完全指南
android·flutter·ios
阿幸软件杂货间2 小时前
阿幸课堂随机点名
android·开发语言·javascript
没有了遇见2 小时前
Android 渐变色整理之功能实现<二>文字,背景,边框,进度条等
android
没有了遇见4 小时前
Android RecycleView 条目进入和滑出屏幕的渐变阴影效果
android
站在巨人肩膀上的码农4 小时前
去掉长按遥控器power键后提示关机、飞行模式的弹窗
android·安卓·rk·关机弹窗·power键·长按·飞行模式弹窗
呼啦啦--隔壁老王4 小时前
屏幕旋转流程
android
人生何处不修行5 小时前
实战:Android 15 (API 35) 适配 & 构建踩坑全记录
android