Created
February 20, 2018 06:49
-
-
Save NightOwlCoder/bb2c6a2daf1f15aba6eab943762ea11f to your computer and use it in GitHub Desktop.
Android Foolproof SD card path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String getSdCardPath() | |
{ | |
if (sdCardPath == null) | |
{ | |
ArrayList<String> list = new ArrayList<String>(); | |
String[] dirs = com.rhythminteractive.Util.FileUtil.getStorageDirectories(); | |
for (String dir : dirs) | |
{ | |
Timber.d("SDCard", "trying path '%s'", dir); | |
try | |
{ | |
File folderName = new File(dir); | |
folderName.mkdirs(); | |
Timber.d("SDCard", "path good '%s'", dir); | |
list.add(dir); | |
} | |
catch (Exception ex) | |
{ | |
} | |
} | |
File fileList[] = new File("/storage/").listFiles(); | |
for (File file : fileList) | |
{ | |
if (!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) | |
{ | |
String dir = file.getAbsolutePath(); | |
Timber.d("SDCard", "trying path '%s'", dir); | |
try | |
{ | |
File folderName = new File(dir); | |
folderName.mkdirs(); | |
Timber.d("SDCard", "path good '%s'", dir); | |
list.add(dir); | |
} | |
catch (Exception ex) | |
{ | |
} | |
} | |
} | |
// now we have a list with all possible candidates | |
// the real SDCard will have the DYNAMIC_ASSET_IMAGE_DASHBOARD_FILENAME file | |
for (String dir : list) | |
{ | |
Timber.d("SDCard", "validating path '%s'", dir); | |
File dashBoardLogo = new File(dir, Constants.DYNAMIC_ASSET_IMAGE_DASHBOARD_FILENAME + ".png"); | |
if (dashBoardLogo.exists()) | |
{ | |
Timber.d("SDCard", "found logo on '%s'", dir); | |
sdCardPath = dir; | |
break; | |
} | |
} | |
if (sdCardPath == null) | |
{ | |
// usually on emulators, above code does not work, hard code value that does here | |
sdCardPath = "/mnt/sdcard"; | |
} | |
Timber.d("SDCard", "SDCard path is '%s'", sdCardPath); | |
} | |
return sdCardPath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is one caveat here:
my app's sd card will always have one file, that I check above.