How can I get the external SD card path for Android 4.0+?

前端 未结 26 3336
清歌不尽
清歌不尽 2020-11-22 04:48

Samsung Galaxy S3 has an external SD card slot, which is mounted to /mnt/extSdCard.

How can I get this path by something like Environment.getExter

26条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:42

    In order to retrieve all the External Storages (whether they are SD cards or internal non-removable storages), you can use the following code:

    final String state = Environment.getExternalStorageState();
    
    if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) {  // we can read the External Storage...           
        //Retrieve the primary External Storage:
        final File primaryExternalStorage = Environment.getExternalStorageDirectory();
    
        //Retrieve the External Storages root directory:
        final String externalStorageRootDir;
        if ( (externalStorageRootDir = primaryExternalStorage.getParent()) == null ) {  // no parent...
            Log.d(TAG, "External Storage: " + primaryExternalStorage + "\n");
        }
        else {
            final File externalStorageRoot = new File( externalStorageRootDir );
            final File[] files = externalStorageRoot.listFiles();
    
            for ( final File file : files ) {
                if ( file.isDirectory() && file.canRead() && (file.listFiles().length > 0) ) {  // it is a real directory (not a USB drive)...
                    Log.d(TAG, "External Storage: " + file.getAbsolutePath() + "\n");
                }
            }
        }
    }
    

    Alternatively, you might use System.getenv("EXTERNAL_STORAGE") to retrieve the primary External Storage directory (e.g. "/storage/sdcard0") and System.getenv("SECONDARY_STORAGE") to retieve the list of all the secondary directories (e.g. "/storage/extSdCard:/storage/UsbDriveA:/storage/UsbDriveB"). Remember that, also in this case, you might want to filter the list of secondary directories in order to exclude the USB drives.

    In any case, please note that using hard-coded paths is always a bad approach (expecially when every manufacturer may change it as pleased).

提交回复
热议问题