Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

后端 未结 19 2291
温柔的废话
温柔的废话 2020-11-22 02:44

Before KitKat (or before the new Gallery) the Intent.ACTION_GET_CONTENT returned a URI like this

content://media/external/images/media/39

相关标签:
19条回答
  • 2020-11-22 03:33

    I believe the responses already posted should get people going in the right direction. However here is what I did that made sense for the legacy code I was updating. The legacy code was using the URI from the gallery to change and then save the images.

    Prior to 4.4 (and google drive), the URIs would look like this: content://media/external/images/media/41

    As stated in the question, they more often look like this: content://com.android.providers.media.documents/document/image:3951

    Since I needed the ability to save images and not disturb the already existing code, I just copied the URI from the gallery into the data folder of the app. Then originated a new URI from the saved image file in the data folder.

    Here's the idea:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent), CHOOSE_IMAGE_REQUEST);
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        super.onActivityResult(requestCode, resultCode, data);
    
        File tempFile = new File(this.getFilesDir().getAbsolutePath(), "temp_image");
    
        //Copy URI contents into temporary file.
        try {
            tempFile.createNewFile();
            copyAndClose(this.getContentResolver().openInputStream(data.getData()),new FileOutputStream(tempFile));
        }
        catch (IOException e) {
            //Log Error
        }
    
        //Now fetch the new URI
        Uri newUri = Uri.fromFile(tempFile);
    
        /* Use new URI object just like you used to */
     }
    

    Note - copyAndClose() just does file I/O to copy InputStream into a FileOutputStream. The code is not posted.

    0 讨论(0)
提交回复
热议问题