简体   繁体   中英

java.io.FileNotFoundException: /storage/emulated/0/Download/myFile.pdf: open failed: EACCES (Permission denied)

Since Android Q came out there are some privacy changes in the permissions about read from external storage. I have a chat application that the user can choose a photo from Downloads etc... and send it. So i need to have access to that files. The way i did this is by using contentProvider.

context.contentResolver.openInputStream(uri)?.use { inputStream ->
    while (true) {
       numBytesRead = inputStream.read(buffer)
       // .. do stuff
   }
}


The uri that is available at that time is ->

However i get a FileNotFoundException but the file trully exists.

I have set all the permissions in the manifest and granted them on the launch of the app. From Android <= 9 it works properly. So what do i have to do...?

I have a chat application that the user can choose a photo from Downloads etc... and send it

That will not be possible on Android 10 and higher. You need to switch to something else. For example, you could use ACTION_OPEN_DOCUMENT to allow the user to choose content from anywhere the user wants. Then, use the resulting Uri to upload it to your chat server, akin to how you are using the Uri in your code snippet. Or, better yet, don't read it all into memory — use something like this OkHttp InputStreamRequestBody implementation .

For Android 10, you can add android:requestLegacyExternalStorage="true" to your <application> element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work. That will not work on Android R and higher, though, so this is only a short-term fix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM