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.
Android 10 enforced scoped storage rules on file accesses by MediaProvider, but not for direct file path access (for example, using File API and NDK APIs) due to the effort required in intercepting kernel calls.
To enable scoped storage in your app, regardless of your app's target SDK version and manifest flag values, enable the following app compatibility flags: DEFAULT_SCOPED_STORAGE (enabled for all apps by default) FORCE_ENABLE_SCOPED_STORAGE (disabled for all apps by default)
Add line in Manifest
<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>
you must add this line in your AndroidManifest.xml
android:requestLegacyExternalStorage="true"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With