上次笔记讲述了设计一个文件分享app的基本思路,今天从源码的角度具体解析被选中文件URI是如何生成的。
该方法源码为:
第一行代码是给PathStrategy变量strategy赋值,该变量有两个重要属性值,一个是mAuthority,赋值后为调用时的实参值;
另一个是mRoot,该变量是一个HashMap,赋值后拥有一个键值对,key值为xml文件中定义的name,value值为xml文件中定义的
文件夹位置,如xml文件定义如下:
则key值为mypicture,value值为设备终端的external-path/picture;
第二行代码则用来生成具体的URI,源码如下:
要生成文件URI,需调用getUriForFile()方法,如:
fileUri = FileProvider.getUriForFile(FileSelectActivity.this, "com.example.ludou.sharefile", requestFile);
第一个参数为context,第二个参数为定义的域名(authority),应该与manifest文件中定义的保持一致,requestFile则是用户点击的listview上的文件名称。
该方法源码为:
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
第一行代码是给PathStrategy变量strategy赋值,该变量有两个重要属性值,一个是mAuthority,赋值后为调用时的实参值;
另一个是mRoot,该变量是一个HashMap,赋值后拥有一个键值对,key值为xml文件中定义的name,value值为xml文件中定义的
文件夹位置,如xml文件定义如下:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path path="picture/" name="mypicture"/>
</paths>
则key值为mypicture,value值为设备终端的external-path/picture;
第二行代码则用来生成具体的URI,源码如下:
@Override
public Uri getUriForFile(File file) {
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
// Find the most-specific root path
Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) {
final String rootPath = root.getValue().getPath();
if (path.startsWith(rootPath) && (mostSpecific == null
|| rootPath.length() > mostSpecific.getValue().getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException(
"Failed to find configured root that contains " + path);
}
// Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
// Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build();
}
for循环中,mRoots就是上一行代码返回的strategy的mRoots属性值(HashMap),如果选择的文件是位于可分享文件夹下,则给mostSpecific赋值,
之后给path重新赋值,使其等于实参的文件名称(没有路径),之后下一句在path前面添加HashMap的key值(xml中的name属性值),最后return语句
组拼完整的Content URI,先加上content://协议,再添加域名(authority),最后加上path值,完成!