'Write on sdcard permission android +6
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.
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
USE this library to get permission in android phone
https://github.com/nabinbhandari/Android-Permissions
Also see this link you get possible information for the solution
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sbr |
Solution 2 | Steven |
Solution 3 | moon |