Cómo obtener la ruta SD_Card en android6.0 mediante programación
Estoy intentando comprobar si el dispositivo que tiene almacenaje externo o no usando la trayectoria externa del almacenaje como esto dado abajo
if (new File("/ext_card/").exists()) { specialPath = "/ext_card/"; } else if (new File("/mnt/sdcard/external_sd/").exists()) { specialPath = "/mnt/sdcard/external_sd/"; } else if (new File("/storage/extSdCard/").exists()) { specialPath = "/storage/extSdCard/"; } else if (new File("/mnt/extSdCard/").exists()) { specialPath = "/mnt/extSdCard/"; } else if (new File("/mnt/sdcard/external_sd/").exists()) { specialPath = "/mnt/sdcard/external_sd/"; } else if (new File("storage/sdcard1/").exists()) { specialPath = "storage/sdcard1/"; }
Pero en el malvavisco no encuentro este camino y al comprobar usando ES FILEMANAGER, dan como almacenamiento / 3263-3131 en Moto G tercera generación. Mientras compruebe en otros dispositivos de la melcocha que los números que consiguen difieren. Por favor, ayúdame a comprobar que el dispositivo de marshmallow tenga almacenamiento externo o no? Y si el almacenamiento encontrado significa cómo obtener la ruta de ese almacenamiento externo?
- Android 6.0 RuntimeException: No se puede conectar al servicio de cámara
- Control de linterna en Marshmallow
- Cómo leer la aplicación de ubicación simulada en Android M-API 23
- Cómo reparar la superposición de pantalla detectada mediante programación
- Aplicación personalizada no creada en Android M (vista previa final)
Nota: – He dado permiso para el almacenamiento en mi aplicación y también habilité el permiso de almacenamiento en la configuración de mi aplicación.
Gracias de antemano y encontró algún error en mi pregunta por favor crt. gracias de nuevo.
- Opción de fuente de audio en la opción de desarrollador en Android M
- Android M - comprobar el permiso de ejecución - cómo determinar si el usuario marcó "Nunca preguntar de nuevo"?
- No se puede cambiar al modo Doze
- ListFiles () devuelve null en el emulador de Android 6.0
- Desafortunadamente, Package Installer se ha detenido mientras solicitaba permiso en Marshmellow
- ¿Error de Android 6.0? Tengo permiso pero getScanResults () todavía devuelve la lista vacía en Android 6.0
- Cambio de comportamiento de SimpleDateFormat en Android Marshmallow
- WindowBackground en Android 6 (Marshmallow)
Aquí está mi solución, que está garantizada para trabajar hasta Android 7.0 Nougat:
/* returns external storage paths (directory of external memory card) as array of Strings */ public String[] getExternalStorageDirectories() { 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 // better variation of: http://stackoverflow.com/a/40123073/5002496 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(LOG_TAG, 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(LOG_TAG, 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; }
He encontrado la solución para esto aquí https://stackoverflow.com/a/13648873/842607
El código es –
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; }
El otro es el hack que encontré en la misma página –
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()]); }
En esto tengo redmi note prime 2.y no tengo memory card.so cuando encontré la ruta y el archivo [] externalDirs = getExternalFilesDirs (null); Dar nulo segundo valor de posición del archivo []. }
- Casting node to element dando ClassCastException
- Código de estado 12501 autenticando con inicio de sesión de Google