Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving files in Android 11 to external storage(SDK 30)

I am writing a new Application on Android 11 (SDK Version 30) and I simply cannot find an example on how to save a file to the external storage.

I read their documentation and now know that they basicly ignore Manifest Permissions (READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE). They also ignore the android:requestLegacyExternalStorage="true" in the manifest.xml application tag.

In their documentation https://developer.android.com/about/versions/11/privacy/storage they write you need to enable the DEFAULT_SCOPED_STORAGE and FORCE_ENABLE_SCOPED_STORAGE flags to enable scoped storage in your app.

Where do I have to enable those? And when I've done that how and when do I get the actual permission to write to the external storage? Can someone provide working code?
I want to save .gif, .png and .mp3 files. So I don't want to write to the gallery.

Thanks in advance.

like image 793
Robert Avatar asked Jan 08 '21 23:01

Robert


People also ask

Why does Android 11 have restrictions file manager?

The reason while the android 11 OBB folder was restricted from being accessed was due to the fact that android wanted to stop files from interacting with each other, basically separating them in a container, while also stopping the user from manually making changes to files or app data.

How do I get storage permissions in Android 11?

On the Settings > Privacy > Permission manager > Files and media page, each app that has the permission is listed under Allowed for all files. If your app targets Android 11, keep in mind that this access to "all files" is read-only.


2 Answers

Corresponding To All Api, included Api 30, Android 11 :

public static File commonDocumentDirPath(String FolderName)
{
    File dir = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
    {
        dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + FolderName);
    }
    else
    {
        dir = new File(Environment.getExternalStorageDirectory() + "/" + FolderName);
    }

    // Make sure the path directory exists.
    if (!dir.exists())
    {
        // Make it, if it doesn't exit
        boolean success = dir.mkdirs();
        if (!success)
        {
            dir = null;
        }
    }
    return dir;
}

Now, use this commonDocumentDirPath for saving file.

A side note from comments, getExternalStoragePublicDirectory with certain scopes are now working with Api 30, Android 11. Cheers! Thanks to CommonsWare hints.

like image 52
Noor Hossain Avatar answered Sep 24 '22 13:09

Noor Hossain


You can save files to the public directories on external storage.

Like Documents, Download, DCIM, Pictures and so on.

In the usual way like before version 10.

like image 28
blackapps Avatar answered Sep 21 '22 13:09

blackapps