Reputation: 81
I want to write on sdcard (External sdcard) on android +6.
When I use this runtime permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
It just works for internal storage but on sdcard i get:
java.io.IOException: Permission denied
How can other apps write on sdcard?
Thanks.
Upvotes: 1
Views: 1920
Reputation: 81
Solved 1. in android +6 the Runtime Permissions just work for Device Storage and not for Sd Card (External SD)
2.For External SD you must Use SAF (Storage Access Framwork) and select sdCard Directory
via this Code you can run SAF (Storage Access Framwork)
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), 42);
After select the sdcrd directory the onActivityResult method was run
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
else {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
preferences = getSharedPreferences("MyShared" , MODE_PRIVATE) ;
SharedPreferences.Editor editor = preferences.edit() ;
editor.putString("Dir" , treeUri.toString());
editor.commit() ;
}
}
the SAF return intent of selected Directory
and we get intent data as a Intent treeUri
(Very Important)→→ for write on sd card in android 6+ you must use From DocumentFile instead of File
and DocumentFile get sd card Directory
Dont Forget to save treeUri in the SharedPreferences , Because you need to save the Directory of Sd Card and every time you need can get it from SharedPreferences
and now pickedDir is the Sdcard directory , you can use it
Upvotes: 4
Reputation: 333
https://github.com/nabinbhandari/Android-Permissions
Storage permission error in Marshmallow
Upvotes: -1
Reputation: 468
For API 23 and above, you need to explicitly request permission from the user AND include the uses permission tag in your android manifest: https://developer.android.com/training/permissions/requesting.html
Upvotes: 0