There are many similar questions here on stackoverflow, but I still couldn't find a solution to my particular problem:
I have an app with the WRITE_EXTERNAL_STORAGE
permission and a non-exported file provider
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cgogolin.library"
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="23" />
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.cgogolin.library.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
which is further specified in provider_paths.xml
as
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<root-path name="external_files2" path="/storage/"/>
</paths>
and which I want to use to serve files from the sdcard to other apps (My app acts more or less as a file browser in this case, but not quite...).
As I am using API level 23 I also dynamically request the permissions by calling
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_PERMISSION_REQUEST);
The dialog window is shown, and after I click "Allow" (and restart the app due to the bug described in Can't write to external storage unless app is restarted after granting permission) the App correctly obtains the permissions, which I can verified by testing whether
android.support.v4.content.ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
and it is indeed true. I can also obtain a Uri
to a File
file from the sdcard with something like
Uri uri = android.support.v4.content.FileProvider.getUriForFile(context, "com.cgogolin.library.fileprovider", file);
I can read from that file and I can for example successfully start an Intent.ACTION_VIEW
to open the file in an external App.
But: Despite having write permissions, I can not write to the file. All attempts to open an OutputStream
or ParcelFileDescriptor
to uri
with either of the following
context.getContentResolver().openOutputStream(uri, "wa");
context.getContentResolver().openFileDescriptor(uri, "wa");
either directly from my App or from an App opened via Intent
result in a
java.io.FileNotFoundException: Permission denied
Where is my mistake? I thought that after checkSelfPermission()
tells me I have WRITE_EXTERNAL_STORAGE
I should actually be able to do so.