Jak Mogę uzyskać zewnętrzną ścieżkę karty SD dla Androida 4.0+?

Samsung Galaxy S3 posiada zewnętrzne Gniazdo Kart SD, które jest montowane do /mnt/extSdCard.

Jak mogę uzyskać tę ścieżkę przez coś takiego jak Environment.getExternalStorageDirectory()?

To zwróci mnt/sdcard, i nie mogę znaleźć API dla zewnętrznej karty SD. (Lub wymienna pamięć USB na niektórych tabletach.)

Author: Peter Mortensen, 2012-07-01

26 answers

Mam wariację na temat rozwiązania, które znalazłem tutaj

public static HashSet<String> getExternalMounts() {
    final HashSet<String> out = new HashSet<String>();
    String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
    String s = "";
    try {
        final Process process = new ProcessBuilder().command("mount")
                .redirectErrorStream(true).start();
        process.waitFor();
        final InputStream is = process.getInputStream();
        final byte[] buffer = new byte[1024];
        while (is.read(buffer) != -1) {
            s = s + new String(buffer);
        }
        is.close();
    } catch (final Exception e) {
        e.printStackTrace();
    }

    // parse output
    final String[] lines = s.split("\n");
    for (String line : lines) {
        if (!line.toLowerCase(Locale.US).contains("asec")) {
            if (line.matches(reg)) {
                String[] parts = line.split(" ");
                for (String part : parts) {
                    if (part.startsWith("/"))
                        if (!part.toLowerCase(Locale.US).contains("vold"))
                            out.add(part);
                }
            }
        }
    }
    return out;
}

Oryginalna metoda została przetestowana i zadziałała

  • Huawei X3 (stock)
  • Galaxy S2 (stock)
  • Galaxy S3 (stock)

Nie jestem pewien, na której wersji Androida były one, gdy były testowane.

Przetestowałem moją zmodyfikowaną wersję z

  • Moto Xoom 4.1.2 (stock)
  • [[8]}Galaxy Nexus (cyanogenmod 10) za pomocą kabla otg
  • HTC Incredible (cyanogenmod 7.2) zwróciło to zarówno wewnętrzne, jak i zewnętrzne. To urządzenie jest trochę dziwny w tym, że jego wewnętrzne w dużej mierze idzie nieużywane jak getExternalStorage () zwraca ścieżkę do sdcard zamiast.
[1]} i niektóre pojedyncze urządzenia pamięci masowej, które używają karty SD jako głównej pamięci
  • HTC G1 (cyanogenmod 6.1)
  • HTC G1 (stock)
  • HTC Vision / G2 (stock)
/ Align = "center" bgcolor = "# e0ffe0 " / cesarz chin / / align = center / Są chyba jakieś dodatkowe kontrole powinienem robić, ale jest to przynajmniej trochę lepsze niż jakiekolwiek rozwiązanie, które znalazłem do tej pory.
 58
Author: Gnathonic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-05 13:03:41

Znalazłem bardziej niezawodny sposób, aby uzyskać ścieżki do wszystkich kart SD w systemie. Działa to na wszystkich wersjach Androida i zwraca ścieżki do wszystkich magazynów(zawierają emulowane).

Działa poprawnie na wszystkich moich urządzeniach.

P. S.: na podstawie kodu źródłowego klasy środowiska.

private static final Pattern DIR_SEPORATOR = Pattern.compile("/");

/**
 * Raturns all available SD-Cards in the system (include emulated)
 *
 * Warning: Hack! Based on Android source code of version 4.3 (API 18)
 * Because there is no standart way to get it.
 * TODO: Test on future Android versions 4.4+
 *
 * @return paths to all available SD-Cards in the system (include emulated)
 */
public static String[] getStorageDirectories()
{
    // Final set of paths
    final Set<String> rv = new HashSet<String>();
    // Primary physical SD-CARD (not emulated)
    final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
    // All Secondary SD-CARDs (all exclude primary) separated by ":"
    final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
    // Primary emulated SD-CARD
    final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
    if(TextUtils.isEmpty(rawEmulatedStorageTarget))
    {
        // Device has physical external storage; use plain paths.
        if(TextUtils.isEmpty(rawExternalStorage))
        {
            // EXTERNAL_STORAGE undefined; falling back to default.
            rv.add("/storage/sdcard0");
        }
        else
        {
            rv.add(rawExternalStorage);
        }
    }
    else
    {
        // Device has emulated storage; external storage paths should have
        // userId burned into them.
        final String rawUserId;
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        {
            rawUserId = "";
        }
        else
        {
            final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            final String[] folders = DIR_SEPORATOR.split(path);
            final String lastFolder = folders[folders.length - 1];
            boolean isDigit = false;
            try
            {
                Integer.valueOf(lastFolder);
                isDigit = true;
            }
            catch(NumberFormatException ignored)
            {
            }
            rawUserId = isDigit ? lastFolder : "";
        }
        // /storage/emulated/0[1,2,...]
        if(TextUtils.isEmpty(rawUserId))
        {
            rv.add(rawEmulatedStorageTarget);
        }
        else
        {
            rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
        }
    }
    // Add all secondary storages
    if(!TextUtils.isEmpty(rawSecondaryStoragesStr))
    {
        // All Secondary SD-CARDs splited into array
        final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
        Collections.addAll(rv, rawSecondaryStorages);
    }
    return rv.toArray(new String[rv.size()]);
}
 54
Author: Dmitriy Lozenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-18 11:29:22

Myślę, że aby użyć zewnętrznej karty SD, musisz użyć tego:

new File("/mnt/external_sd/")

Lub

new File("/mnt/extSdCard/")
W Twoim przypadku...

W miejsce Environment.getExternalStorageDirectory()

Mi pasuje. Powinieneś najpierw sprawdzić, co znajduje się w katalogu mnt i stamtąd pracować..

Powinieneś użyć pewnego rodzaju metody wyboru, aby wybrać, której karty SD użyć:

File storageDir = new File("/mnt/");
if(storageDir.isDirectory()){
    String[] dirList = storageDir.list();
    //TODO some type of selecton method?
}
 32
Author: FabianCook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-01 10:14:05

W celu pobrania wszystkich zewnętrznych magazynów (czy są karty SD lub wewnętrzne nieusuwalne magazyny), możesz użyć następującego kodu:

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");
            }
        }
    }
}

Alternatywnie możesz użyć systemu.getenv ("EXTERNAL_STORAGE") , aby pobrać główny zewnętrzny katalog pamięci (np. "/storage/sdcard0") i System .getenv ("SECONDARY_STORAGE") to retive the list of all the secondary Directory (e. g. W tym celu należy wykonać następujące czynności: Pamiętaj, że również w tym przypadku możesz filtrować listę wtórnych katalogów, aby wykluczyć napędy USB.

W każdym razie należy pamiętać, że używanie mocno zakodowanych ścieżek jest zawsze złym podejściem (szczególnie, gdy każdy producent może zmienić je według uznania).

 15
Author: Paolo Rovelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-07 14:03:11

Używałem rozwiązania , dopóki nie sprawdziłem na Asus Zenfone2, Marshmallow 6.0.1 i rozwiązanie nie działa. Rozwiązanie nie powiodło się podczas uzyskiwania EMULATED_STORAGE_TARGET, specjalnie dla ścieżki microSD, np.: /storage/F99C-10f4/. Edytowałem kod, aby pobrać emulowane ścieżki główne bezpośrednio z emulowanych ścieżek aplikacji z context.getExternalFilesDirs(null); i dodać bardziej znane phone-model-specific ścieżki fizyczne.

To make our life łatwiej, zrobiłem bibliotekę tutaj . Możesz go używać za pomocą gradle, maven, sbt i Leiningen build system.

Jeśli podoba Ci się staromodny sposób, możesz również skopiować wklejony plik bezpośrednio z tutaj, ale nie będziesz wiedział, czy będzie aktualizacja w przyszłości bez ręcznego sprawdzania.

Jeśli masz jakieś pytania lub sugestie, daj mi znać

 15
Author: HendraWD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-15 08:56:58

Dobre wieści! W KitKat istnieje teraz publiczne API do interakcji z tymi drugorzędnymi współdzielonymi urządzeniami pamięci masowej.

Nowe metody Context.getExternalFilesDirs() i Context.getExternalCacheDirs() mogą zwracać wiele ścieżek, w tym zarówno urządzenia pierwotne, jak i wtórne. Następnie możesz je iterować i sprawdzić Environment.getStorageState() i File.getFreeSpace(), Aby określić najlepsze miejsce do przechowywania plików. Metody te są również dostępne na ContextCompat w bibliotece support-v4.

Zauważ również, że jeśli jesteś zainteresowany tylko wykorzystaniem katalogów zwracanych przez Context, nie potrzebujesz już uprawnień READ_ lub WRITE_EXTERNAL_STORAGE. W przyszłości zawsze będziesz mieć dostęp do odczytu/zapisu tych katalogów bez dodatkowych uprawnień.

[9]} aplikacje mogą również kontynuować pracę na starszych urządzeniach, wycofując żądanie zezwolenia w następujący sposób:]}
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />
 13
Author: Jeff Sharkey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-20 23:13:09

Wykonałem następujące czynności, aby uzyskać dostęp do wszystkich zewnętrznych kart sd.

Z:

File primaryExtSd=Environment.getExternalStorageDirectory();

Dostajesz ścieżkę do głównego zewnętrznego SD Następnie z:

File parentDir=new File(primaryExtSd.getParent());

Otrzymujesz Katalog nadrzędny podstawowej pamięci zewnętrznej i jest on również rodzicem wszystkich zewnętrznych pamięci sd. Teraz możesz wyświetlić listę wszystkich magazynów i wybrać ten, który chcesz.

Mam nadzieję, że się przyda.

 11
Author: valenta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-19 04:45:51

Oto jak otrzymuję listę ścieżek kart SD (z wyłączeniem podstawowej pamięci zewnętrznej):

  /**
   * returns a list of all available sd cards paths, or null if not found.
   * 
   * @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
   */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static List<String> getSdCardPaths(final Context context,final boolean includePrimaryExternalStorage)
    {
    final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
    if(externalCacheDirs==null||externalCacheDirs.length==0)
      return null;
    if(externalCacheDirs.length==1)
      {
      if(externalCacheDirs[0]==null)
        return null;
      final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
      if(!Environment.MEDIA_MOUNTED.equals(storageState))
        return null;
      if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
        return null;
      }
    final List<String> result=new ArrayList<>();
    if(includePrimaryExternalStorage||externalCacheDirs.length==1)
      result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
    for(int i=1;i<externalCacheDirs.length;++i)
      {
      final File file=externalCacheDirs[i];
      if(file==null)
        continue;
      final String storageState=EnvironmentCompat.getStorageState(file);
      if(Environment.MEDIA_MOUNTED.equals(storageState))
        result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
      }
    if(result.isEmpty())
      return null;
    return result;
    }

  /** Given any file/folder inside an sd card, this will return the path of the sd card */
  private static String getRootOfInnerSdCardFolder(File file)
    {
    if(file==null)
      return null;
    final long totalSpace=file.getTotalSpace();
    while(true)
      {
      final File parentFile=file.getParentFile();
      if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
        return file.getAbsolutePath();
      file=parentFile;
      }
    }
 9
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-26 20:54:34

Dzięki za wskazówki dostarczone przez was, szczególnie @ SmartLemon, mam rozwiązanie. W przypadku, gdy ktoś inny go potrzebuje, umieszczam moje ostateczne rozwiązanie tutaj (aby znaleźć pierwszą wymienioną zewnętrzną kartę SD):

public File getExternalSDCardDirectory()
{
    File innerDir = Environment.getExternalStorageDirectory();
    File rootDir = innerDir.getParentFile();
    File firstExtSdCard = innerDir ;
    File[] files = rootDir.listFiles();
    for (File file : files) {
        if (file.compareTo(innerDir) != 0) {
            firstExtSdCard = file;
            break;
        }
    }
    //Log.i("2", firstExtSdCard.getAbsolutePath().toString());
    return firstExtSdCard;
}

Jeśli nie ma zewnętrznej karty SD, to zwraca pamięć pokładową. Użyję go, jeśli sdcard nie istnieje, być może trzeba go zmienić.

 5
Author: rml,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-07 13:02:31

Odwołaj się do mojego kodu, mam nadzieję, że pomocny dla ciebie:

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("mount");
    InputStream is = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    String line;
    String mount = new String();
    BufferedReader br = new BufferedReader(isr);
    while ((line = br.readLine()) != null) {
        if (line.contains("secure")) continue;
        if (line.contains("asec")) continue;

        if (line.contains("fat")) {//TF card
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat("*" + columns[1] + "\n");
            }
        } else if (line.contains("fuse")) {//internal storage
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat(columns[1] + "\n");
            }
        }
    }
    txtView.setText(mount);
 3
Author: cst05001,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-17 03:03:15

W rzeczywistości w niektórych urządzeniach domyślna nazwa zewnętrznej karty SD jest wyświetlana jako extSdCard, A dla innych jest to sdcard1.

Ten fragment kodu pomaga znaleźć dokładną ścieżkę i pomaga odzyskać ścieżkę urządzenia zewnętrznego.

String sdpath,sd1path,usbdiskpath,sd0path;    
        if(new File("/storage/extSdCard/").exists())
            {
               sdpath="/storage/extSdCard/";
               Log.i("Sd Cardext Path",sdpath);
            }
        if(new File("/storage/sdcard1/").exists())
         {
              sd1path="/storage/sdcard1/";
              Log.i("Sd Card1 Path",sd1path);
         }
        if(new File("/storage/usbcard1/").exists())
         {
              usbdiskpath="/storage/usbcard1/";
              Log.i("USB Path",usbdiskpath);
         }
        if(new File("/storage/sdcard0/").exists())
         {
              sd0path="/storage/sdcard0/";
              Log.i("Sd Card0 Path",sd0path);
         }
 2
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-20 02:55:35

Tak. Inny producent używa innej nazwy SDcard jak w Samsung Tab 3 jego extsd, a inne urządzenia samsung używają sdcard jak ten inny producent używa różnych nazw.

Miałem takie same wymagania jak ty. więc stworzyłem przykładowy przykład dla Ciebie z mojego projektu goto ten link Android Directory chooser przykład, który wykorzystuje bibliotekę androi-dirchooser. Ten przykład wykrywa kartę SD i wyświetla wszystkie podfoldery, a także wykrywa, czy urządzenie ma więcej Jedna karta SD.

Część kodu wygląda tak dla pełnego przykładu goto link Android Directory Chooser

/**
* Returns the path to internal storage ex:- /storage/emulated/0
 *
* @return
 */
private String getInternalDirectoryPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
 }

/**
 * Returns the SDcard storage path for samsung ex:- /storage/extSdCard
 *
 * @return
 */
    private String getSDcardDirectoryPath() {
    return System.getenv("SECONDARY_STORAGE");
}


 mSdcardLayout.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        String sdCardPath;
        /***
         * Null check because user may click on already selected buton before selecting the folder
         * And mSelectedDir may contain some wrong path like when user confirm dialog and swith back again
         */

        if (mSelectedDir != null && !mSelectedDir.getAbsolutePath().contains(System.getenv("SECONDARY_STORAGE"))) {
            mCurrentInternalPath = mSelectedDir.getAbsolutePath();
        } else {
            mCurrentInternalPath = getInternalDirectoryPath();
        }
        if (mCurrentSDcardPath != null) {
            sdCardPath = mCurrentSDcardPath;
        } else {
            sdCardPath = getSDcardDirectoryPath();
        }
        //When there is only one SDcard
        if (sdCardPath != null) {
            if (!sdCardPath.contains(":")) {
                updateButtonColor(STORAGE_EXTERNAL);
                File dir = new File(sdCardPath);
                changeDirectory(dir);
            } else if (sdCardPath.contains(":")) {
                //Multiple Sdcards show root folder and remove the Internal storage from that.
                updateButtonColor(STORAGE_EXTERNAL);
                File dir = new File("/storage");
                changeDirectory(dir);
            }
        } else {
            //In some unknown scenario at least we can list the root folder
            updateButtonColor(STORAGE_EXTERNAL);
            File dir = new File("/storage");
            changeDirectory(dir);
        }


    }
});
 2
Author: Shivaraj Patil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-06 07:27:57

To rozwiązanie (złożone z innych odpowiedzi na to pytanie) obsługuje fakt (jak wspomniał @ono), że System.getenv("SECONDARY_STORAGE") jest bezużyteczne Z Marshmallow.

Przetestowane i działające na:

  • 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<String> results = new ArrayList<String>();
            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<String> rv = new HashSet<String>();
    
            if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                Collections.addAll(rv, rawSecondaryStorages);
            }
            storageDirectories = rv.toArray(new String[rv.size()]);
        }
        return storageDirectories;
    }
    
 2
Author: DaveAlden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-07 14:01:39

Na niektórych urządzeniach (na przykład samsung galaxy sII )wewnętrzna karta pamięci Mabe być w vfat. W tym przypadku użyj odnoszą ostatni kod, otrzymujemy ścieżkę wewnętrznej karty pamięci (/mnt / sdcad), ale nie zewnętrznej karty. Kod patrz poniżej Rozwiąż ten problem.

static String getExternalStorage(){
         String exts =  Environment.getExternalStorageDirectory().getPath();
         try {
            FileReader fr = new FileReader(new File("/proc/mounts"));       
            BufferedReader br = new BufferedReader(fr);
            String sdCard=null;
            String line;
            while((line = br.readLine())!=null){
                if(line.contains("secure") || line.contains("asec")) continue;
            if(line.contains("fat")){
                String[] pars = line.split("\\s");
                if(pars.length<2) continue;
                if(pars[1].equals(exts)) continue;
                sdCard =pars[1]; 
                break;
            }
        }
        fr.close();
        br.close();
        return sdCard;  

     } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
 1
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-27 07:32:10
       File[] files = null;
    File file = new File("/storage");// /storage/emulated
if (file.exists()) {
        files = file.listFiles();
            }
            if (null != files)
                for (int j = 0; j < files.length; j++) {
                    Log.e(TAG, "" + files[j]);
                    Log.e(TAG, "//--//--// " +             files[j].exists());

                    if (files[j].toString().replaceAll("_", "")
                            .toLowerCase().contains("extsdcard")) {
                        external_path = files[j].toString();
                        break;
                    } else if (files[j].toString().replaceAll("_", "")
                            .toLowerCase()
                            .contains("sdcard".concat(Integer.toString(j)))) {
                        // external_path = files[j].toString();
                    }
                    Log.e(TAG, "--///--///--  " + external_path);
                }
 1
Author: Amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-13 07:51:46

Jestem pewien, że ten kod z pewnością rozwiąże Twoje problemy...To mi pasuje...\

try {
            File mountFile = new File("/proc/mounts");
            usbFoundCount=0;
            sdcardFoundCount=0;
            if(mountFile.exists())
             {
                Scanner usbscanner = new Scanner(mountFile);
                while (usbscanner.hasNext()) {
                    String line = usbscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/usbcard1")) {
                        usbFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
                    }
            }
         }
            if(mountFile.exists()){
                Scanner sdcardscanner = new Scanner(mountFile);
                while (sdcardscanner.hasNext()) {
                    String line = sdcardscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/sdcard1")) {
                        sdcardFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
                    }
            }
         }
            if(usbFoundCount==1)
            {
                Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
                Log.i("-----USB--------","USB Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"USB not found!!!!", 7000).show();
                Log.i("-----USB--------","USB not found!!!!" );

            }
            if(sdcardFoundCount==1)
            {
                Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
                Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"SDCard not found!!!!", 7000).show();
                Log.i("-----SDCard--------","SDCard not found!!!!" );

            }
        }catch (Exception e) {
            e.printStackTrace();
        } 
 0
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 07:07:33

To nieprawda. / mnt / sdcard / external_sd może istnieć nawet jeśli karta SD nie jest zamontowana. Twoja aplikacja zawiesi się, gdy spróbujesz napisać do /mnt / sdcard / external_sd, gdy nie jest zamontowana.

Musisz sprawdzić, czy karta SD jest zamontowana najpierw za pomocą:

boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
 0
Author: Marcin Skoczylas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-16 12:54:34
 String path = Environment.getExternalStorageDirectory()
                        + File.separator + Environment.DIRECTORY_PICTURES;
                File dir = new File(path);
 0
Author: sarra srairi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-27 22:53:56

Możesz użyć czegoś w rodzaju-Context.getExternalCacheDirs () lub Context.getExternalFilesDirs () lub Context.getObbDirs (). Dają one specyficzne katalogi aplikacji we wszystkich zewnętrznych urządzeniach pamięci masowej, gdzie aplikacja może przechowywać swoje pliki.

Więc coś takiego-kontekst.getExternalCacheDirs () [i].getParentFile ().getParentFile ().getParentFile ().getParent () może uzyskać ścieżkę główną zewnętrznych urządzeń pamięci masowej.

Wiem, że te komendy są do innego celu, ale inne odpowiedzi mi nie odpowiadały.

Ten link dał mi dobre wskazówki- https://possiblemobile.com/2014/03/android-external-storage/

 0
Author: Sharath Holla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-28 06:38:13

System.getenv("SECONDARY_STORAGE") zwraca null dla Marshmallow. Jest to inny sposób na znalezienie wszystkich zewnętrznych dirs. Możesz sprawdzić, czy jest wymienny, co określa, czy wewnętrzny / zewnętrzny

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    File[] externalCacheDirs = context.getExternalCacheDirs();
    for (File file : externalCacheDirs) {
        if (Environment.isExternalStorageRemovable(file)) {
            // It's a removable storage
        }
    }
}
 0
Author: ono,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-05 22:52:54

Próbowałem rozwiązań dostarczonych przez Dmitriy Lozenkoi Gnathonicna moim Samsung Galaxy Tab S2 (Model: T819Y) ale żaden nie pomógł mi pobrać ścieżki do zewnętrznego katalogu kart SD. mount wykonanie polecenia zawierało wymaganą ścieżkę do zewnętrznego katalogu kart SD (tj. /Storage/A5F9-15F4) ale nie pasowało do wyrażenia regularnego, dlatego nie zostało zwrócone. Nie rozumiem mechanizmu nazewnictwa katalogów po Samsungu. Dlaczego odbiegają od standardy (np. extsdcard) i wymyślić coś naprawdę podejrzanego, jak w moim przypadku (np. /Storage/A5F9-15f4). Czy coś mi umyka? W każdym razie, po zmianach w wyrażeniu regularnym rozwiązanie Gnathonic ' S pomogło mi uzyskać poprawny katalog sdcard:

final HashSet<String> out = new HashSet<String>();
        String reg = "(?i).*(vold|media_rw).*(sdcard|vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
        String s = "";
        try {
            final Process process = new ProcessBuilder().command("mount")
                    .redirectErrorStream(true).start();
            process.waitFor();
            final InputStream is = process.getInputStream();
            final byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                s = s + new String(buffer);
            }
            is.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }

        // parse output
        final String[] lines = s.split("\n");
        for (String line : lines) {
            if (!line.toLowerCase(Locale.US).contains("asec")) {
                if (line.matches(reg)) {
                    String[] parts = line.split(" ");
                    for (String part : parts) {
                        if (part.startsWith("/"))
                            if (!part.toLowerCase(Locale.US).contains("vold"))
                                out.add(part);
                    }
                }
            }
        }
        return out;

Nie jestem pewien, czy jest to prawidłowe rozwiązanie i czy da wyniki dla innych tabletów Samsunga, ale to naprawiło mój problem na razie. Poniżej znajduje się inna metoda pobierania ścieżki wymiennej karty SD w Androidzie (v6.0). Przetestowałem metodę z Androidem marshmallow i działa. Podejście zastosowane w nim jest bardzo podstawowe i na pewno zadziała również w innych wersjach, ale testowanie jest obowiązkowe. Niektóre wgląd w to będzie pomocne:

public static String getSDCardDirPathForAndroidMarshmallow() {

    File rootDir = null;

    try {
        // Getting external storage directory file
        File innerDir = Environment.getExternalStorageDirectory();

        // Temporarily saving retrieved external storage directory as root
        // directory
        rootDir = innerDir;

        // Splitting path for external storage directory to get its root
        // directory

        String externalStorageDirPath = innerDir.getAbsolutePath();

        if (externalStorageDirPath != null
                && externalStorageDirPath.length() > 1
                && externalStorageDirPath.startsWith("/")) {

            externalStorageDirPath = externalStorageDirPath.substring(1,
                    externalStorageDirPath.length());
        }

        if (externalStorageDirPath != null
                && externalStorageDirPath.endsWith("/")) {

            externalStorageDirPath = externalStorageDirPath.substring(0,
                    externalStorageDirPath.length() - 1);
        }

        String[] pathElements = externalStorageDirPath.split("/");

        for (int i = 0; i < pathElements.length - 1; i++) {

            rootDir = rootDir.getParentFile();
        }

        File[] files = rootDir.listFiles();

        for (File file : files) {
            if (file.exists() && file.compareTo(innerDir) != 0) {

                // Try-catch is implemented to prevent from any IO exception
                try {

                    if (Environment.isExternalStorageRemovable(file)) {
                        return file.getAbsolutePath();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}
Uprzejmie podziel się, jeśli masz inne podejście do rozwiązania tego problemu. Dzięki
 0
Author: Abdul Rehman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-16 05:22:23
String secStore = System.getenv("SECONDARY_STORAGE");

File externalsdpath = new File(secStore);

To otrzyma ścieżkę zewnętrznej pamięci wtórnej sd.

 0
Author: Kenneth Villamin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-27 13:50:06
//manifest file outside the application tag
//please give permission write this 
//<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        File file = new File("/mnt");
        String[] fileNameList = file.list(); //file names list inside the mnr folder
        String all_names = ""; //for the log information
        String foundedFullNameOfExtCard = ""; // full name of ext card will come here
        boolean isExtCardFounded = false;
        for (String name : fileNameList) {
            if (!isExtCardFounded) {
                isExtCardFounded = name.contains("ext");
                foundedFullNameOfExtCard = name;
            }
            all_names += name + "\n"; // for log
        }
        Log.d("dialog", all_names + foundedFullNameOfExtCard);
 0
Author: Emre Kilinc Arslan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-13 21:17:26

Aby uzyskać dostęp do plików na mojej karcie SD , w moim HTC One X (Android), używam tej ścieżki:

file:///storage/sdcard0/folder/filename.jpg

Uwaga tripple"/"!

 0
Author: HTC user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-12 11:25:55

Na Galaxy S3 Android 4.3 ścieżka, której używam to ./ storage / extSdCard / Card / i robi swoje. Mam nadzieję, że to pomoże,

 -1
Author: CLEMENT DUPUIS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-20 15:46:14

Następujące kroki zadziałały dla mnie. Wystarczy, że napiszesz tę linijkę:

String sdf = new String(Environment.getExternalStorageDirectory().getName());
String sddir = new String(Environment.getExternalStorageDirectory().getPath().replace(sdf,""));

Pierwsza linia poda nazwę katalogu sd i wystarczy użyć jej w metodzie replace dla drugiego łańcucha. Drugi łańcuch będzie zawierał ścieżkę dla wewnętrznego i wymiennego sd(/storage/ w moim przypadku). Po prostu potrzebowałem tej ścieżki dla mojej aplikacji, ale możesz pójść dalej, jeśli potrzebujesz.

 -1
Author: EnVoY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-18 12:08:30