Home > Net >  Android SDK 30, write to the root of external storage
Android SDK 30, write to the root of external storage

Time:01-27


I have a problem that I am sure I am not the only one to encounter. Today I use a file export system for my Android application. I write my export files in a folder at the same level as the system folders :

|-Android
|-Documents
|-Music
|-Downloads
|-MyApp
|- etc.

With the new storage system for SDK 30, I can no longer access this folder. So I am stuck in SDK 29 with the flag "requestLegacyExternalStorage".

Is it possible to create a shortcut to the Android/data/com.mypackage folder to this folder at root level?

Is there a package to work around this problem? I've been looking for a solution to this problem for two years without success. I would like to keep this folder in the root, because it is easy to access especially during USB transfers.

I know the Privacy Policy, but this is for a professional App, they doesn't carry about this thing.

CodePudding user response:

You can target SDK 30 and add MANAGE_EXTERNAL_STORAGE permission to the manifest:

 <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />

Do note it's a dangerous permission so you'll need to request it differently, like this:

if (!Environment.isExternalStorageManager()) {
        requestManageAllPermission();
        return;
    }
private void requestManageAllPermission() {
    try {
        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
        startActivityForResult(intent, REQ_MANAGE_EXTERNAL);
    } catch (Exception e) {
       
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
        startActivityForResult(intent, REQ_MANAGE_EXTERNAL);
    }
}

And you need to handle the results in:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_MANAGE_EXTERNAL) {
        if (!Environment.isExternalStorageManager())
            finish();
    }
}

REQ_MANAGE_EXTERNAL is a int constant, can be any number you want, in my case its 2296

  •  Tags:  
  • Related