How to tell if the sdcard is mounted in Android?
Asked Answered
C

8

18

I'm working on an Android application that needs to look at what images a user has stored. The problem is that if the user has the sdcard mounted via the USB cable, I can't read the list of images on the disk.

Does anyone know of a way to tell if the usb is mounted so that I could just pop up a message informing the user that it won't work?

Compliment answered 23/5, 2009 at 18:9 Comment(1)
Just for the record, plugging the USB cable is not the only way to get the sdcard volume unmounted - unmounting the card in the storage settings or physically removing card will do it too. Also, the 8GB sdcards supplied by t-mobile uk aren't properly preformatted so because of I/O they got unmounted all the time as long as they aren't reformatted properly. I'm only saying that because sometimes just telling the user to unplug the cable is not enough.Retrusion
G
41

If you're trying to access images on the device, the best method is to use the MediaStore content provider. Accessing it as a content provider will allow you to query the images that are present, and map content:// URLs to filepaths on the device where appropriate.

If you still need to access the SD card, the Camera application includes an ImageUtils class that checks if the SD card is mounted as follows:

static public boolean hasStorage(boolean requireWriteAccess) {
    //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
    String state = Environment.getExternalStorageState();
    Log.v(TAG, "storage state is " + state);

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (requireWriteAccess) {
            boolean writable = checkFsWritable();
            Log.v(TAG, "storage writable is " + writable);
            return writable;
        } else {
            return true;
        }
    } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}
Gaelan answered 23/5, 2009 at 22:50 Comment(3)
An lo, someone provides the android api way of doing things. Vote up!Cristacristabel
Where is the method checkFsWritable(); ?Grossman
Do we need <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> to make it works on external storage?Callimachus
C
9

Here is the checkFsWritable missing function in jargonjustin post

private static boolean checkFsWritable() {
        // Create a temporary file to see whether a volume is really writeable.
        // It's important not to put it in the root directory which may have a
        // limit on the number of files.
        String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM";
        File directory = new File(directoryName);
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                return false;
            }
        }
        return directory.canWrite();
    }
Contumacious answered 20/6, 2012 at 3:33 Comment(0)
I
3
public static boolean isSdPresent() {

return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

}
Infamous answered 27/9, 2011 at 7:3 Comment(1)
@MartinSmith the source there also is meInfamous
C
2

I apologise for posting a non-Android way of doing this, hopefully someone can provide an answer using the Android API.

You could list the files on the root of the sdcard. If there is none, the sdcard is either entirely blank (unusual, but possible) or it is unmounted. If you try to create an empty file on the sdcard and it fails, it means that you were trying to create a file in the mount-point of the sdcard which would be denied due to a permissions issue so you would know the sdcard was not mounted.

Yes, I know this is ugly....

Cristacristabel answered 23/5, 2009 at 20:38 Comment(0)
T
2

On jargonjustin's post:

File ImageManager.java

Method hasStorage -->

public static boolean hasStorage(boolean requireWriteAccess) {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (requireWriteAccess) {
                boolean writable = checkFsWritable();
                return writable;
            } else {
                return true;
            }
        } else if (!requireWriteAccess
                && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

Method checkFsWritable -->

 private static boolean checkFsWritable() {
        // Create a temporary file to see whether a volume is really writeable.
        // It's important not to put it in the root directory which may have a
        // limit on the number of files.
        String directoryName =
                Environment.getExternalStorageDirectory().toString() + "/DCIM";
        File directory = new File(directoryName);
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                return false;
            }
        }
        File f = new File(directoryName, ".probe");
        try {
            // Remove stale file if any
            if (f.exists()) {
                f.delete();
            }
            if (!f.createNewFile()) {
                return false;
            }
            f.delete();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }
Tiertza answered 11/8, 2013 at 15:29 Comment(0)
D
0

I was using cursor for retrieving the images from sd card and when no sd card was inserted in device the cursor was null. Actually this is the case when the sdcard volume was unmounted by physically removing card from device. This is the code I've used:

  Cursor mCursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
    if (mCursor == null || !mCursor .moveToFirst()) {
                /**
                 *mCursor == null:
                 * - query failed; the app don't have access to sdCard; example: no sdCard 
                 *
                 *!mCursor.moveToFirst():
                 *     - there is no media on the device
                 */
            } else {
                 // process the images...
                 mCursor.close(); 
    }

More info: http://developer.android.com/guide/topics/media/mediaplayer.html#viacontentresolver

Dominions answered 17/7, 2012 at 14:40 Comment(0)
B
0

Before you do any work with the external storage, you should always call getExternalStorageState() to check whether the media is available. The media might be mounted to a computer, missing, read-only, or in some other state. For example, here are a couple methods you can use to check the availability:

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

source: http://developer.android.com/guide/topics/data/data-storage.html

Brade answered 4/1, 2015 at 6:39 Comment(0)
S
-1
Cool....Check it out...
try {
            File mountFile = new File("/proc/mounts");
            usbFoundCount=0;
            sdcardFoundCount=0;
            if(mountFile.exists())
             {
                Scanner usbscanner = new Scanner(mountFile);
                while (usbscanner.hasNext()) {
                    String line = usbscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/usbcard1")) {
                        usbFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
                    }
            }
         }
            if(mountFile.exists()){
                Scanner sdcardscanner = new Scanner(mountFile);
                while (sdcardscanner.hasNext()) {
                    String line = sdcardscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/sdcard1")) {
                        sdcardFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
                    }
            }
         }
            if(usbFoundCount==1)
            {
                Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
                Log.i("-----USB--------","USB Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"USB not found!!!!", 7000).show();
                Log.i("-----USB--------","USB not found!!!!" );

            }
            if(sdcardFoundCount==1)
            {
                Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
                Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"SDCard not found!!!!", 7000).show();
                Log.i("-----SDCard--------","SDCard not found!!!!" );

            }
        }catch (Exception e) {
            e.printStackTrace();
        } 
Southland answered 9/6, 2014 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.