Using External Storage

suggest change

“External” Storage is another type of storage that we can use to save files to the user’s device. It has some key differences from “Internal” Storage, namely:

To use External Storage, we need to first obtain the proper permissions. You will need to use:

To grant these permissions, you will need to identify them in your AndroidManifest.xml as such

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
NOTE: Since they are Dangerous permissions if you are using API Level 23 or above, you will need to request the permissions at runtime.

Before attempting to write or read from External Storage, you should always check that the storage medium is available.

String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
    // Available to read and write
}
if (state.equals(Environment.MEDIA_MOUNTED) || 
        state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
    // Available to at least read
}

When writing files to the External Storage, you should decide if the file should be recognized as Public or Private. While both of these types of files are still accessible to the user and other applications on the device, there is a key distinction between them.

Public files should remain on the device when the user uninstalls the app. An example of a file that should be saved as Public would be photos that are taken through your application.

Private files should all be removed when the user uninstalls the app. These types of files would be app specific, and not be of use to the user or other applications. Ex. temporary files downloaded/used by your application.

Here’s how to get access to the Documents directory for both Public and Private files.

Public

// Access your app's directory in the device's Public documents directory
File docs = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOCUMENTS), "YourAppDirectory");
// Make the directory if it does not yet exist
myDocs.mkdirs();

Private

// Access your app's Private documents directory
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), 
        "YourAppDirectory");
// Make the directory if it does not yet exist
myDocs.mkdirs();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents