Search code examples
javaandroidfilepathandroid-external-storage

Why does the recommended `getExternalStorageState()` to replace deprecated `getExternalStorageDirectory()` not work correctly?


Problem: When I use the recommended getExternalStorageState() to replace the deprecated getExternalStorageDirectory(), the recommended replacement returns the wrong path. I discovered the issue when the FileInputStream crashed, which it wasn't before.

The following is deprecated but correctly returns: /storage/emulated/0/Download/alaina.jpg

return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;

The following is recommended and returns: mounted/download/alaina.jpg

return Environment.getExternalStorageState() + "/Download/" + fileName;

What I have done: I've imported and using the class RealPathUtil by tatocaster found here and it works great. However, some methods of the Environment and MediaStore used are now deprecated. The use of getExternalStorageState() was recommended through the warnings. I will typically clean up the warnings and use recommendations and this is the first to cause an issue.

The emulator location:

enter image description here


Solution

  • When I use the recommended getExternalStorageState() to replace the deprecated getExternalStorageDirectory(),

    That makes no sense as you cannot compare them with each other.

    The one delivers a file path. The other a state.

    No need to use getExternalStorageState() as it always returns state mounted.

    Since years there is always external storage available.

    Method getExternalStorageDirectory() works and is undeprecated a week ago.