Skip to content

Instantly share code, notes, and snippets.

@NightOwlCoder
Created February 20, 2018 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NightOwlCoder/bb2c6a2daf1f15aba6eab943762ea11f to your computer and use it in GitHub Desktop.
Save NightOwlCoder/bb2c6a2daf1f15aba6eab943762ea11f to your computer and use it in GitHub Desktop.
Android Foolproof SD card path
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;
}
@NightOwlCoder
Copy link
Author

There is one caveat here:

my app's sd card will always have one file, that I check above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment