我知道图像的绝对路径(例如,/sdcard/cats.jpg)。是否有任何方法获得这个文件的内容uri ?
实际上,在我的代码中,我下载了一张图像并将其保存在特定的位置。为了在ImageView实例中设置图像,目前我使用路径打开文件,获取字节并创建位图,然后在ImageView实例中设置位图。这是一个非常缓慢的过程如果我能得到内容uri那么我就可以很容易地使用imageview。setimageuri (uri)方法
我知道图像的绝对路径(例如,/sdcard/cats.jpg)。是否有任何方法获得这个文件的内容uri ?
实际上,在我的代码中,我下载了一张图像并将其保存在特定的位置。为了在ImageView实例中设置图像,目前我使用路径打开文件,获取字节并创建位图,然后在ImageView实例中设置位图。这是一个非常缓慢的过程如果我能得到内容uri那么我就可以很容易地使用imageview。setimageuri (uri)方法
当前回答
无需编写任何代码,只需使用adb shell CLI命令即可获得File ID:
adb shell content query --uri "content://media/external/video/media" | grep FILE_NAME | grep -Eo " _id=([0-9]+)," | grep -Eo "[0-9]+"
其他回答
无需编写任何代码,只需使用adb shell CLI命令即可获得File ID:
adb shell content query --uri "content://media/external/video/media" | grep FILE_NAME | grep -Eo " _id=([0-9]+)," | grep -Eo "[0-9]+"
试一试:
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
或:
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
最好使用验证来支持Android N之前的版本,例如:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = Uri.parse(filepath);
} else{
imageUri = Uri.fromFile(new File(filepath));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
} else{
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
}
https://es.stackoverflow.com/questions/71443/reporte-crash-android-os-fileuriexposedexception-en-android-n
你可以试试下面的代码片段
public Uri getUri(ContentResolver cr, String path){
Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME);
Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Files.getContentUri(VOLUME_NAME,id);
}
if(ca != null) {
ca.close();
}
return null;
}
从文件创建Content Uri内容://最简单、最健壮的方法是使用FileProvider。FileProvider提供的Uri也可以用于与其他应用程序共享文件。要从File的绝对路径获取File Uri,你可以使用DocumentFile.fromFile(new File(path, name)),它是在Api 22中添加的,对于以下版本返回null。
File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);