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

前端 未结 26 3395
清歌不尽
清歌不尽 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:33

    This solution (assembled from other answers to this question) handles the fact (as mentioned by @ono) that System.getenv("SECONDARY_STORAGE") is of no use with Marshmallow.

    Tested and working on:

    • Samsung Galaxy Tab 2 (Android 4.1.1 - Stock)
    • Samsung Galaxy Note 8.0 (Android 4.2.2 - Stock)
    • Samsung Galaxy S4 (Android 4.4 - Stock)
    • Samsung Galaxy S4 (Android 5.1.1 - Cyanogenmod)
    • Samsung Galaxy Tab A (Android 6.0.1 - Stock)

      /**
       * Returns all available external SD-Card roots in the system.
       *
       * @return paths to all available external SD-Card roots in the system.
       */
      public static String[] getStorageDirectories() {
          String [] storageDirectories;
          String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
      
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
              List results = new ArrayList();
              File[] externalDirs = applicationContext.getExternalFilesDirs(null);
              for (File file : externalDirs) {
                  String path = file.getPath().split("/Android")[0];
                  if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
                          || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)){
                      results.add(path);
                  }
              }
              storageDirectories = results.toArray(new String[0]);
          }else{
              final Set rv = new HashSet();
      
              if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                  final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                  Collections.addAll(rv, rawSecondaryStorages);
              }
              storageDirectories = rv.toArray(new String[rv.size()]);
          }
          return storageDirectories;
      }
      

提交回复
热议问题