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?
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.
The method getExternalStorageState() on much new age Android devices with SD card checks the internal memory but not SD card. The more simple option would be to use getExternalMediaDirs() method within Context class. It returns an array of files with absolute path and can be used to detect the presence of SD card.
Insert the Micro SD card into the SD card slot on your Android device. On most newer phones, the SD card is inserted in the SIM card tray. To install a SIM card, locate the SIM card tray on the side of the phone. It's a small oval-shaped compartment with a pinhole on the side.
Some more modern smartphones automatically mount your SD card without asking, while on others you may need to go to “Settings -> Storage -> SD card” and follow the prompt to mount it from there. Once your SD card is mounted, it's ready to use with your Android device.
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;
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With