Issue
I'm trying to copy an image from user storage
File(userStorageImagePath).copyTo(userProfileImage, overwrite = true)
but then user chose the image the exception appears:
open failed: EACCES (Permission denied) /storage/emulated/0/Download/....
all access granted read/write and exception appears only on android 10
android:requestLegacyExternalStorage="true"
solve issue,
but how can I replace requestLegacyExternalStorage to something suitable for google?
Solution
Resolved:
val inputStream: InputStream? = getMediaUriFromPath(ctx, userStorageImagePath)?.let { ctx.contentResolver.openInputStream(it) }
Files.copy(inputStream, imageDestinationPath, StandardCopyOption.REPLACE_EXISTING)
fun getMediaUriFromPath(context: Context, path: String): Uri? {
val mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor? = context.contentResolver.query(
mediaUri,
null,
MediaStore.Images.Media.DISPLAY_NAME + "= ?",
arrayOf(path.substring(path.lastIndexOf("/") + 1)),
null
)
var uri: Uri? = null
if (cursor != null) {
if (cursor.moveToFirst()) {
uri = ContentUris.withAppendedId(
mediaUri,
cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID))
)
}
}
cursor?.close()
return uri
}
Answered By - Slava Vir
Answer Checked By - Marilyn (JavaFixing Volunteer)