Recipe 10.5 Saving Files to External Storage

Android versions
Level 1 and above
Permissions
android.permission.WRITE_EXTERNAL_STORAGE
Source code to download from Wrox.com
ExternalStorage.zip

The previous recipes show you how to save data to the application’s filesystem on the device. In some cases, you might want to save the files to the device’s external storage, such as the SD card.

NOTE In the context of Android, external storage does not necessarily mean physically external storage such as the SD card. It may also refer to storage on the device that is separate from the protected internal storage. External storage can be mounted by a user as a filesystem, and it may not always be accessible when it is mounted or removed.

Solution

Before you write or read files from the external storage, it is always important to check whether it is available and writeable. The following method checks that:

package net.learn2develop.externalstorage;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public boolean IsExternalStorageAvailableAndWriteable() {
        boolean externalStorageAvailable = false;
        boolean externalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
 //---you ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.