I am looking for a way to find if the SD card is mounted. Before anyone else says so, Environment.getExternalStorageState() is not the answer.
Environment.getExternalStorageState() will tell you if the primary external storage is mounted. This is not necessarily (in fact, not usually) the SD card.
EnvironmentCompat.getStorageState(File file) seems like it would work, but it returns MEDIA_UNKNOWN if the location is not the external storage - see here for proof.
My best idea so far is just trying to create a file and take the result (success or failure) as MEDIA_MOUNTED or MEDIA_UNMOUNTED, but I was wondering if anyone has a more elegant solution.
As a side note, is there any issue with the code I am currently using to find the SD card path?
public static File getExternalFilesDir(Context context) {
File extFiles[] = ContextCompat.getExternalFilesDirs(context, null);
File sd = null;
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP) {
// Use the isExternalStorageRemovable function added in Lollipop
for (File file : extFiles) {
if (Environment.isExternalStorageRemovable(file)) {
sd = file;
}
}
} else if (currentapiVersion >= android.os.Build.VERSION_CODES.KITKAT) {
// getExternalFilesDirs will return all storages on KitKat. Assume
// the second storage is the sd card
if (Environment.isExternalStorageRemovable()) {
sd = extFiles[0];
} else if (extFiles.length > 2) {
sd = extFiles[1];
}
} else if (currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD) {
// Use the secondary storage if the primary one is not removable
if (Environment.isExternalStorageRemovable()) {
sd = extFiles[0];
} else {
String secStore = System.getenv("SECONDARY_STORAGE");
String packageName = context.getPackageName();
if (secStore != null) {
sd = new File(secStore + "/Android/data/" + packageName + "/files");
}
}
} else {
// Froyo and Eclair do not have emulated storages
sd = extFiles[0];
}
if (sd != null && !sd.exists()) {
sd.mkdirs();
}
if (sd != null) {
Log.v("getExternalFilesDir", sd.getAbsolutePath());
}
return sd;
}