记录Android中FileProvider的基本使用方法

  1. 在res/xml目录(如没有xml目录请新建)下新建file_paths.xml文件(文件名自定义,这里以file_paths为例)。
  2. 在新建的file_paths.xml文件中,简单代码如下:
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="my_path"  //自定义
        path="" />
</paths>

<paths>中不仅有<external-path>,还有另外几种path,各自对应不同的存储目录。这里未做深究。在使用时还要注意对应权限的设置。

  1. 在AndroidManifest.xml清单文件中的<application></application>块中添加<provider></provider>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="应用包名"   //一般为应用包名
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/files_path" />    //与res/xml目录中新建的xml文件对应
    </provider>
  1. 代码中使用
 Uri uri = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, file);

其中,FILE_PROVIDER_AUTHORITY 与AndroidManifest.xml清单文件中<provider>的android:authorities属性值对应。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容