androidandroidx

Why aren't photo editors accepting URIs from the photo picker?


I want to request a photo from the user using the system photo picker (i.e. with a PickVisualMedia request), then send another Intent for a photo editor to crop the photo. If I just send the URI received from the photo picker with the intent, Google Photos shows "Error, could not load media" and quits. Other photo editors I have either show a similar warning or just crash.

The code that registers the launchers for the media picker and crop activity:

mediaPickerLauncher = activity.registerForActivityResult(
    ActivityResultContracts.PickVisualMedia()
) { uri ->
    pickerCallback(uri)
}

cropResultLauncher = activity.registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()
) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        val data: Intent? = result.data
        Log.d("Crop", "Photo received")
    }
    else {
        Log.d("Crop", "Cancelled!")
    }
}

pickerCallback checks if the URI is null, and if it isn't, runs this:

val intent = Intent("com.android.camera.action.CROP")
intent.setData(uri)
intent.putExtra("crop", "true")
// Set the aspect ratio to 1:1 (square)
intent.putExtra("aspectX", 1)
intent.putExtra("aspectY", 1)
// Set the resolution to 500x500
intent.putExtra("outputX", 500)
intent.putExtra("outputY", 500)
// Set a few more flags
intent.putExtra("return-data", true)
cropResultLauncher!!.launch(intent)

I tried using takePersistableUriPermission, as described in the media picker article, but it didn't help.


Solution

  • In the end, Rashid Bilal's answer worked, but I had to add this line to pickerCallback after the line that creates the intent:

    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)