Android FileProvider使用教程

 更新时间:2023年03月22日 17:25:40   作者:Dormiveglia-flx  
主要摘要关键知识点和记录我的学习思路及验证结论,可以帮助读者比较全面的认识FileProvider,FileProvider是特殊的ContentProvider,目标是在为保护隐私和数据安全而加强应用沙箱机制的同时,支持在应用间共享文件

Android基础--FileProvider

Android 7.0之前,文件的Uri以file:///形式提供给其他app访问。

Android 7.0之后,为了安全起见,file:///形式的Uri不能正常访问,官方提 供了FileProvider,FileProvider生成的Uri会以content://的形式分享给其他app使用。

那如何使用FileProvider?

在manifest 中声明provider

	<provider
            android:authorities="${packagename}.provider"
            android:name="com.flx.cn.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider" />
	</provider>
  • authorities:相当于一个用于认证的暗号,在分享文件生成Uri时,会通过它的值生成对应的Uri。
  • exported:的值为false,表示该FileProvider只能本应用使用
  • meta-data:别的配置信息
  • grantUriPermissions:让接收端的app临时有权限进行操作了。

设置共享目录

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <paths>
    <!--<root-path/> 代表设备的根目录new File("/");-->
    <root-path
        name = ""
        path=""/>
    <!-- Context.getFilesDir() + "/path/" -->
    <files-path
        name="my_files"
        path="test/"/>
    <!-- Context.getCacheDir() + "/path/" -->
    <cache-path
        name="my_cache"
        path="test/"/>
    <!-- Context.getExternalFilesDir(null) + "/path/" -->
    <external-files-path
        name="external-files-path"
        path="test/"/>
    <!-- Context.getExternalCacheDir() + "/path/" -->
    <external-cache-path
         name="name"
         path="test/" />
    <!-- Environment.getExternalStorageDirectory() + "/path/" -->
    <external-path
        name="my_external_path"
        path="test/"/>
    <!-- Environment.getExternalStorageDirectory() + "/path/" -->
    <external-path
        name="files_root"
        path="Android/data/<包名>/"/>
    <!-- path设置为'.'时代表整个存储卡 Environment.getExternalStorageDirectory() + "/path/"   -->
    <external-path
        name="external_storage_root"
        path="."/>
  </paths>
</resources>

最终生成的代码效果

以第二个为例:
content://com.flx.cn.fileprovider/my_files/filexxx.jpg

生成Content Uri文件,供其他app使用

File filePath = new File(Context.getFilesDir(), "my_log");
File newFile = new File(filePath, "my_log.log");
// 生成Uri
Uri contentUri = FileProvider.getUriForFile(getContext(), "com.flx.cn.fileprovider", newFile);

授权,一般就读取和写入2种权限,并分享

// 这里用的是发送文件。
Intent intent = new Intent(Intent.ACTION_SEND);
// 设置读写权限
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//Uri传入Intent
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(intent)

到此这篇关于Android FileProvider使用教程的文章就介绍到这了,更多相关Android FileProvider内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论