2017-07-15 26 views
0

我想掃描存儲以檢索擴展名與一組擴展名匹配的所有文件。對於運行Jellybean +的所有Android手機來說,存儲是否通用?

目前我使用的是Environment.getExternalStorageDirectory().getPath(),但它返回到Samsung Galaxy Core Prime內置存儲器的路徑(我沒有嘗試過在其他設備上),並且遺漏了外部SD卡。

但是,我發現路徑/storage/是上述設備上的內置存儲和SD卡的根。所以我的問題是:在運行SDK 16+的所有Android設備中都一樣嗎?

請確認上述路徑存在,並且它是內置存儲和外部SD卡(如果有)的根。

+0

試試下面的答案 –

回答

0

試試這個代碼

private String[] getExternalStorageDirectoryn() { 
    List<String> results = new ArrayList<>(); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //Method 1 for KitKat & above 
     File[] externalDirs = getExternalFilesDirs(null); 

     for (File file : externalDirs) { 
      String path = file.getPath().split("/Android")[0]; 

      boolean addPath = false; 

      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
       addPath = Environment.isExternalStorageRemovable(file); 
      } 
      else{ 
       addPath = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(file)); 
      } 

      if(addPath){ 
       results.add(path); 
      } 
     } 
    } 

    if(results.isEmpty()) { //Method 2 for all versions 

     String output = ""; 
     try { 
      final Process process = new ProcessBuilder().command("mount | grep /dev/block/vold") 
        .redirectErrorStream(true).start(); 
      process.waitFor(); 
      final InputStream is = process.getInputStream(); 
      final byte[] buffer = new byte[1024]; 
      while (is.read(buffer) != -1) { 
       output = output + new String(buffer); 
      } 
      is.close(); 
     } catch (final Exception e) { 
      e.printStackTrace(); 
     } 
     if(!output.trim().isEmpty()) { 
      String devicePoints[] = output.split("\n"); 
      for(String voldPoint: devicePoints) { 
       results.add(voldPoint.split(" ")[2]); 
      } 
     } 
    } 

    //Below few lines is to remove paths which may not be external memory card, like OTG (feel free to comment them out) 
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     for (int i = 0; i < results.size(); i++) { 
      if (!results.get(i).toLowerCase().matches(".*[0-9a-f]{4}[-][0-9a-f]{4}")) { 
       Log.d("Storage", results.get(i) + " might not be extSDcard"); 
       results.remove(i--); 
      } 
     } 
    } else { 
     for (int i = 0; i < results.size(); i++) { 
      if (!results.get(i).toLowerCase().contains("ext") && !results.get(i).toLowerCase().contains("sdcard")) { 
       Log.d("Storage", results.get(i)+" might not be extSDcard"); 
       results.remove(i--); 
      } 
     } 
    } 

    String[] storageDirectories = new String[results.size()]; 
    for(int i=0; i<results.size(); ++i) storageDirectories[i] = results.get(i); 

    return storageDirectories; 

} 
相關問題