记录一下
如果Scheme类型是content,那么直接ContentResolver查询,但是会发现有些文件查不到,比如一个文件在微信的缓存路径下,我们就不能通过ContentResolver拿到他的data字段。那么怎么办呢?复制一份到自己目录下不就好了?代码如下:
if (ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())) {
ContentResolver contentResolver = BaseApplication.getInstance().getContentResolver();
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
int pathIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (pathIndex == -1) {
path = contentUriToPath(contentResolver, uri, nameIndex == -1 ? null : cursor.getString(nameIndex));//解析失败时,path转file会报错,会被外部catch抓住
} else {
//查找成功
path = cursor.getString(pathIndex);
}
}
cursor.close();
if (path != null) {
return new File(path);
}
}
private static String contentUriToPath(ContentResolver contentResolver, Uri uri, String displayName) {
try {
if (contentResolver == null) {
return null;
}
if (uri == null) {
return null;
}
InputStream inputStream = contentResolver.openInputStream(uri);
if (inputStream == null) {
return null;
}
if (TextUtils.isEmpty(displayName)) {
displayName = System.currentTimeMillis() + "_share_file";
}
File cacheDir = BaseApplication.getInstance().getCacheDir();
File file = new File(cacheDir, displayName);
//将文件复制到自己缓存目录下
boolean b = FileUtils.copyFileStream(inputStream, new FileOutputStream(file));
return b ? file.getAbsolutePath() : null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
如果Scheme类型是file类型,那么我们就要用ContentResolver查询INTERNAL_CONTENT_URI和EXTERNAL_CONTENT_URI查询文件下面是EXTERNAL_CONTENT_URI查询代码。
if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())) {
path = uri.getEncodedPath();//防止乱码
if (path != null) {
path = Uri.decode(path);
ContentResolver cr = BaseApplication.getInstance().getContentResolver();
StringBuffer buff = new StringBuffer();
buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
int dataIdx;
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cur.getString(dataIdx);
}
cur.close();
}
if (path != null) {
return new File(path);
}
}
网友评论