Get a Content URI from a File URI?

后端 未结 3 659
执笔经年
执笔经年 2021-02-09 06:36

I am using the DownloadManager to download an image to the system\'s gallery and then in the Broadcast receiver (once the download succeeds) using an Intent to set the image as

3条回答
  •  情歌与酒
    2021-02-09 07:20

    I was able to figure it out. It was a combination of the code found here: Converting android image URI and scanning the media file after downloading.

    So after the file finished downloading I get the path and do the following:

    String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    
    //Update the System
    Uri u = Uri.parse(uriString);                       
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, u));
    
    //Get the abs path using a file, this is important          
    File wallpaper_file = new File(u.getPath());
    Uri contentURI = getImageContentUri(context, wallpaper_file.getAbsolutePath());
    

    For some reason starting the media scanner, newing the file, and getting the absolute path are important, I'm not exactly sure why but I can't spend any more time on this!

    The way to convert from a file URI to a content URI is as follows (taken from the linked StackOver flow post:

    public static Uri getImageContentUri(Context context, String absPath) {
        Log.v(TAG, "getImageContentUri: " + absPath);
    
        Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            , new String[] { MediaStore.Images.Media._ID }
            , MediaStore.Images.Media.DATA + "=? "
            , new String[] { absPath }, null);
    
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , Integer.toString(id));
    
        } else if (!absPath.isEmpty()) {
             ContentValues values = new ContentValues();
             values.put(MediaStore.Images.Media.DATA, absPath);
             return context.getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
    

    Maybe this will help someone in the future.

提交回复
热议问题