0

I have looked over many posts on getting SD card locations, and most that mention using Environment.getExternalStorageState(), Environment.getExternalStorageDirectory() always returns internal storage for my on a Samsung Galaxy Tab A / Android 11 (/storage/emulated/0)

I did see a comment that said to use System.getenv("SECONDARY_STORAGE"), which returns /storage/sdcard:/storage/usb1:/storage/usb2, but trying to open a file (I have put there) just returns a not found error (ie java.io.FileNotFoundException: /sdcard/external_sd/Music/test/testfile.mp3: open failed: ENOENT (No such file or directory).

Also tried Environment.getExternalStoragePublicDirectory(Environment.MEDIA_MOUNTED).getPath() and this returns /storage/emulated/0/mounted and this does not work either

I have the following permissions..

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.PERMISSIONS_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_EXTERNAL_STORAGE" />

and at startup I call

 private fun verifyStoragePermissions(activity: Activity) {
    // Check if we have write permission
    val permission =
        ActivityCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE)

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
            activity,
            arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE),
            
        )
    }
}

Finally, as stated here, I hardwired /sdcard/external_sd and this did not work either (ie I try to open a file I know is there, and also using the following to list contents..

File(testFolder).walk().forEach {
            println(it)
        }

I have other application that writes to it, so there must be some way to do it (I only want to read existing files).

What might I be doing wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
peterc
  • 6,921
  • 9
  • 65
  • 131

1 Answers1

3

You can try this:

File[] dirs = getExternalFilesDirs("");
for (File currD :
        dirs) {
    if (currD.getAbsolutePath().equals(getExternalFilesDir("").getAbsolutePath())) {
        // Here is internal storage path
    } else {
        // Here is SD path
    }
}
Dan Baruch
  • 1,063
  • 10
  • 19