Search code examples
androidandroid-cameraandroid-5.0-lollipop

How get path to secondary external directory for Camera files


I have a device with an SD card. Now I want to check that device has mounted an external SD card and can read files from the public DCIM folder. I know that I can use Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);, but this method returns only files, that is on primary external memory, not on the mounted SD card (Secondary external storage).

I found that Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); returns an element with index 1, for the secondary external storage, but this method gets files only for application sandbox (Android/data/packagename). So my question is how get path to secondary external path for public directory like DCIM?


Solution

  • I found solution, here is code snippet:

    String strSDCardPath = System.getenv("SECONDARY_STORAGE");
    
    if ((strSDCardPath == null) || (strSDCardPath.length() == 0)) {
        strSDCardPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
    }
    
    //If may get a full path that is not the right one, even if we don't have the SD Card there. 
    //We just need the "/mnt/extSdCard/" i.e and check if it's writable
    if(strSDCardPath != null) {
        if (strSDCardPath.contains(":")) {
            strSDCardPath = strSDCardPath.substring(0,strSDCardPath.indexOf(":"));
        }
        File externalFilePath = new File(strSDCardPath);
    
        if (externalFilePath.exists() && externalFilePath.canWrite()) {
            //do what you need here
        } 
    }
    

    For more details, read here: Finding the SDCard Path on Android devices