这篇文章主要介绍“Android FileProvider如何使用”,在日常操作中,相信很多人在Android FileProvider如何使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Android FileProvider如何使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
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如何使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://feilx.blog.csdn.net/article/details/129429761