In Android 10 apps that need to access storage need to ask permission to access a concrete path. But apps like file explorer can ask permission for access to the root storage and gain permission to read/write to all storage. That is what I am trying to do.
According to Android we must use ACTION_OPEN_DOCUMENT_TREE
for this. The problem I have is that everything seems correct, but the permission is not granted to the app.
private void askAndroid10Perm()
{
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(
Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
| Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
}
Here the user can see Android file tree and, with main storage selected, click to grant permission. "It will allow - app name - to have full access to all files currently store under this location, and any future content stored here" -> Allow
Then:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_OPEN_DOCUMENT_TREE:
if (resultCode == Activity.RESULT_OK) {
Uri treeUri = data.getData();
int takeFlags = data.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Log.i("TAG", "takePersistableUriPermission: " + treeUri);
this.getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
}
}
}
}
Log:
takePersistableUriPermission: content://com.android.externalstorage.documents/tree/primary%3A
Then the app will still not have permission to access to root.
open failed: EACCES (Permission denied)
Of course I have:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Granted by the user.
Scoped Storage not accept by PlayConsole so now its not Worked.
For Work Android 11 or Up.
in Android Q If you giving permission and its granted or not working so go to Manifest and add
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:requestLegacyExternalStorage="true" //Add this Line
android:label="@string/app_name">
---------<Activity, Sevices or Recivers>----------
</application>
and in build.gradle
compileSdkVersion 29 //SDK Version don't update to 30
defaultConfig {
applicationId 'com.example.application'
minSdkVersion 16
targetSdkVersion 29 //SDK Version don't update to 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}