【问题标题】:Get correct path to External SDCard in android在android中获取外部SDCard的正确路径
【发布时间】:2014-09-30 09:37:53
【问题描述】:

我正在尝试通过我的应用程序获取到我的 samsung s4 android 设备内的 sd 卡的正确路径,但是当我尝试上述路径时:

  String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
        String pathTwo = Environment.getExternalStorageDirectory().getAbsolutePath();
        String path3 = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();

获取私有的不可写路径 /storage/emulated/0 而不是正确的 storage/sdcard1 路径

我使用 Android 设备监视器通过文件资源管理器找到了正确的路径,但我不想硬编码路径,因为路径可能因设备而异。

亲切的问候

【问题讨论】:

    标签: java android storage android-sdcard


    【解决方案1】:

    适用于所有设备

    String sSDpath = null;
                File   fileCur = null;
                for( String sPathCur : Arrays.asList( "MicroSD","external_SD","sdcard1","ext_card", "external_sd", "ext_sd", "external", "extSdCard",  "externalSdCard")) // external sdcard
                 {
    
                   fileCur = new File( "/mnt/", sPathCur);
                   if( fileCur.isDirectory() && fileCur.canWrite())
                     {
                       sSDpath = fileCur.getAbsolutePath();
                       break;
                     }
                   if( sSDpath == null)  {
                   fileCur = new File( "/storage/", sPathCur);
                   if( fileCur.isDirectory() && fileCur.canWrite())
                     {
                       sSDpath = fileCur.getAbsolutePath();
                       break;
                     }
                   }
                   if( sSDpath == null)  {
                   fileCur = new File( "/storage/emulated", sPathCur);
                   if( fileCur.isDirectory() && fileCur.canWrite())
                     {
                       sSDpath = fileCur.getAbsolutePath();
    Log.e("path",sSpath);
                       break;
                     }
                   }
                 }
    

    100% 工作,在多个设备上测试。

    【讨论】:

      【解决方案2】:

      根据之前的回答,外置SD卡的路径实际上因不同的设备制造商而异。

      "Environment.getExternalStorageDirectory() 指的是设备制造商认为的“外部存储”。在某些设备上,这是可移动媒体,例如 SD 卡。在某些设备上,这是设备上的一部分在这里,“外部存储”是指“安装在主机上时可通过 USB 大容量存储模式访问的东西”,至少对于 Android 1.x 和 2.x 而言。 但问题是关于外部SD。如何获得像“/mnt/sdcard/external_sd”这样的路径(它可能因设备而异)? 如上所述,除了外部存储,Android 没有“外部 SD”的概念。 如果设备制造商已选择将外部存储设备作为板载闪存并且还具有 SD 卡,则您需要联系该制造商以确定您是否可以使用 SD 卡(不保证)以及规则的用途使用它,例如使用什么路径。”

      基于this 的回答。

      因此,没有绝对的方法可以通过代码获取此路径。

      【讨论】:

        【解决方案3】:

        正如 gilonm 所提到的,外部(可移动)Sd 路径因设备而异,但我编写了一个方法,该方法遍历不同制造商使用的所有不同 ext 路径,然后找到精确匹配。

        如果找不到路径,则返回空字符串。如果找到了路径,还需要验证卡是否插入。 (通过检查该路径上是否存在子文件夹)

        注意:我在方法中使用了StreamSupport库,所以你需要下载jar文件并将其添加到项目的libs文件夹中,这样就可以了!

           public static String getExternalSdPath(Context context) {
            List<String> listOfFoldersToSearch = Arrays.asList("/storage/", "/mnt/", "/removable/", "/data/");
            final List<String> listOf2DepthFolders = Arrays.asList("sdcard0", "media_rw", "removable");
            final List<String> listOfExtFolders = Arrays.asList("sdcard1", "extsdcard", "external_sd", "microsd", "emmc", "ext_sd", "sdext",
                    "sdext1", "sdext2", "sdext3", "sdext4");
            final String[] thePath = {""};
            Optional<File> optional = StreamSupport.stream(listOfFoldersToSearch)
                    .filter(new Predicate<String>() {
                        @Override
                        public boolean test(final String s) {
                            File folder = new File(s);
                            return folder.exists() && folder.isDirectory();
                        }
                    }) //I got the ones that exist and are directories
                    .flatMap(new Function<String, Stream<File>>() {
                        @Override
                        public Stream<File> apply(final String s) {
                            try {
                                List<File> files = Arrays.asList(new File(s).listFiles());
                                return StreamSupport.stream(files);
                            } catch (NullPointerException e) {
                                return StreamSupport.stream(new ArrayList<File>());
                            }
                        }
                    }) //I got all sub-dirs of the main folders
                    .flatMap(new Function<File, Stream<File>>() {
                        @Override
                        public Stream<File> apply(final File file1) {
                            if (listOf2DepthFolders.contains(file1.getName()
                                    .toLowerCase())) {
                                try {
                                    List<File> files = Arrays.asList(file1.listFiles());
                                    return StreamSupport.stream(files);
                                } catch (NullPointerException e) {
                                    return StreamSupport.stream(Collections.singletonList(file1));
                                }
                            } else
                                return StreamSupport.stream(Collections.singletonList(file1));
                        }
                    }) //Here I got all the 2 depth and 3 depth folders
                    .filter(new Predicate<File>() {
                        @Override
                        public boolean test(final File o) {
                            return listOfExtFolders.contains(o.getName()
                                    .toLowerCase());
                        }
                    })
                    .findFirst();
        
            optional.ifPresent(new Consumer<File>() {
                @Override
                public void accept(final File file) {
                    thePath[0] = file.getAbsolutePath();
                }
            });
        
            Log.e("Path", thePath[0]);
        
            try {
                ContextCompat.getExternalFilesDirs(context, null);
            } catch (Exception e) {
                Log.e("PathException", thePath[0]);
            }
            return thePath[0];
        }
        

        附:我在一些 HTC 和三星设备上对其进行了测试和验证。

        【讨论】:

          【解决方案4】:

          此函数将返回 SD 卡路径的路径。

          private String getExternalSdCard(){
             String finalPath = null;
             File sdCardFile = ContextCompat.getExternalFilesDirs(this, null)[1];
             String base = String.format("/Android/data/%s/files", getPackageName());
          
             String path = sdCardFile.getAbsolutePath();
             if(path.contains(base)){
                 finalPath = path.replace(base, "");
             }
             return finalPath;
          

          }

          获取所有存储列表。使用循环

          private String[] storages() {
              List<String> storages = new ArrayList<>();
          
              try {
                  File[] externalStorageFiles = ContextCompat.getExternalFilesDirs(this, null);
          
                  String base = String.format("/Android/data/%s/files", getPackageName());
          
                  for (File file : externalStorageFiles) {
                      try {
                          if (file != null) {
                              String path = file.getAbsolutePath();
          
                              if (path.contains(base)) {
                                  String finalPath = path.replace(base, "");
          
                                  if (validPath(finalPath)) {
                                      storages.add(finalPath);
                                  }
                              }
                          }
                      } catch (Exception e) {
                          CrashUtils.report(e);
                      }
                  }
              } catch (Exception e) {
                  CrashUtils.report(e);
              }
          
              String[] result = new String[storages.size()];
              storages.toArray(result);
          
              return result;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-11-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-01
            • 2015-01-01
            • 2023-03-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多