Find location of a removable SD card

前端 未结 22 2977
南方客
南方客 2020-11-21 11:32

Is there an universal way to find the location of an external SD card?

Please, do not be confused with External Storage.

Environment.getExternalStorage

22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 11:50

    This solution handles the fact 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;
      }
      

提交回复
热议问题