我知道图像的绝对路径(例如,/sdcard/cats.jpg)。是否有任何方法获得这个文件的内容uri ?

实际上,在我的代码中,我下载了一张图像并将其保存在特定的位置。为了在ImageView实例中设置图像,目前我使用路径打开文件,获取字节并创建位图,然后在ImageView实例中设置位图。这是一个非常缓慢的过程如果我能得到内容uri那么我就可以很容易地使用imageview。setimageuri (uri)方法


当前回答

试一试:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));

或:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));

其他回答

对于你的目的,公认的解决方案可能是最好的选择,但实际上要在主题行中回答问题:

在我的应用程序中,我必须从URI中获取路径,从路径中获取URI。前:

/**
 * Gets the corresponding path to a file from the given content:// URI
 * @param selectedVideoUri The content:// URI to find the file path from
 * @param contentResolver The content resolver to use to perform the query.
 * @return the file path as a string
 */
private String getFilePathFromContentUri(Uri selectedVideoUri,
        ContentResolver contentResolver) {
    String filePath;
    String[] filePathColumn = {MediaColumns.DATA};

    Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    filePath = cursor.getString(columnIndex);
    cursor.close();
    return filePath;
}

后者(我用于视频,但也可以用于音频或文件或其他类型的存储内容,通过替换MediaStore。音频(等)MediaStore.Video):

/**
 * Gets the MediaStore video ID of a given file on external storage
 * @param filePath The path (on external storage) of the file to resolve the ID of
 * @param contentResolver The content resolver to use to perform the query.
 * @return the video ID as a long
 */
private long getVideoIdFromFilePath(String filePath,
        ContentResolver contentResolver) {


    long videoId;
    Log.d(TAG,"Loading file " + filePath);

            // This returns us content://media/external/videos/media (or something like that)
            // I pass in "external" because that's the MediaStore's name for the external
            // storage on my device (the other possibility is "internal")
    Uri videosUri = MediaStore.Video.Media.getContentUri("external");

    Log.d(TAG,"videosUri = " + videosUri.toString());

    String[] projection = {MediaStore.Video.VideoColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(projection[0]);
    videoId = cursor.getLong(columnIndex);

    Log.d(TAG,"Video ID is " + videoId);
    cursor.close();
    return videoId;
}

基本上,MediaStore的DATA列(或您正在查询的任何子部分)存储文件路径,因此您可以使用该信息来查找它。

最好使用验证来支持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

//此代码适用于2.2上的图像,不确定是否有任何其他媒体类型

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };

无需编写任何代码,只需使用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]+"

虽然已经晚了,但将来可能会对别人有所帮助。

要获取文件的内容URI,您可以使用以下方法:

FileProvider。getUriForFile(上下文上下文,字符串权限,文件文件)

它返回内容URI。

看看这个来学习如何设置一个FileProvider