2011-09-15 17 views

Respuesta

120
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
Boolean isSDSupportedDevice = Environment.isExternalStorageRemovable(); 

if(isSDSupportedDevice && isSDPresent) 
{ 
    // yes SD-card is present 
} 
else 
{ 
// Sorry 
} 
+3

cómo verificar la memoria sdcard libre? – naresh

+1

gracias, está funcionando – naresh

+40

, pero vuelve verdadero si el teléfono tiene almacenamiento incorporado ... no es la respuesta correcta – User10001

12

Uso Environment.getExternalStorageState() como se describe en "Using the External Storage".

Para obtener el espacio disponible en el almacenamiento externo, utilice StatFs:

// do this only *after* you have checked external storage state: 
File extdir = Environment.getExternalStorageDirectory(); 
File stats = new StatFs(extdir.getAbsolutePath()); 
int availableBytes = stats.getAvailableBlocks() * stats.getBlockSize(); 
3
void updateExternalStorageState() { 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     mExternalStorageAvailable = mExternalStorageWriteable = true; 
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
     mExternalStorageAvailable = true; 
     mExternalStorageWriteable = false; 
    } else { 
     mExternalStorageAvailable = mExternalStorageWriteable = false; 
} 
handleExternalStorageState(mExternalStorageAvailable, 
     mExternalStorageWriteable); 
} 
5

escribí un poco de clase para que la comprobación del estado de almacenamiento. Tal vez te sirva de algo.

import android.os.Environment; 

/** 
* Checks the state of the external storage of the device. 
* 
* @author kaolick 
*/ 
public class StorageHelper 
{ 
// Storage states 
private boolean externalStorageAvailable, externalStorageWriteable; 

/** 
* Checks the external storage's state and saves it in member attributes. 
*/ 
private void checkStorage() 
{ 
// Get the external storage's state 
String state = Environment.getExternalStorageState(); 

if (state.equals(Environment.MEDIA_MOUNTED)) 
{ 
    // Storage is available and writeable 
    externalStorageAvailable = externalStorageWriteable = true; 
} 
else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) 
{ 
    // Storage is only readable 
    externalStorageAvailable = true; 
    externalStorageWriteable = false; 
} 
else 
{ 
    // Storage is neither readable nor writeable 
    externalStorageAvailable = externalStorageWriteable = false; 
} 
} 

/** 
* Checks the state of the external storage. 
* 
* @return True if the external storage is available, false otherwise. 
*/ 
public boolean isExternalStorageAvailable() 
{ 
checkStorage(); 

return externalStorageAvailable; 
} 

/** 
* Checks the state of the external storage. 
* 
* @return True if the external storage is writeable, false otherwise. 
*/ 
public boolean isExternalStorageWriteable() 
{ 
checkStorage(); 

return externalStorageWriteable; 
} 

/** 
* Checks the state of the external storage. 
* 
* @return True if the external storage is available and writeable, false 
*   otherwise. 
*/  
public boolean isExternalStorageAvailableAndWriteable() 
{ 
checkStorage(); 

if (!externalStorageAvailable) 
{ 
    return false; 
} 
else if (!externalStorageWriteable) 
{ 
    return false; 
} 
else 
{ 
    return true; 
} 
} 
} 
+0

¿Este calss ayuda a detectar la disponibilidad de la tarjeta sd? –

+0

@PankajNimgade Esta clase le ayuda a verificar si el almacenamiento externo está disponible y/o puede escribirse. El almacenamiento externo puede ser una tarjeta SD o un almacenamiento integrado, como en los dispositivos nexus. – kaolick

+0

¿es posible verificar específicamente para la "tarjeta sd"? Gracias de antemano –

4

Lo modifiqué de tal manera que si existe una tarjeta SD, establece el camino allí. Si no, lo establece en el directorio interno.

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
if(isSDPresent) 
{ 
    path = theAct.getExternalCacheDir().getAbsolutePath() + "/GrammarFolder"; 
} 
else 
{ 
    path = theAct.getFilesDir() + "/GrammarFolder"; 
} 
0

creé una clase para comprobar si la carpeta en la tarjeta SD está disponible o no:

public class GetFolderPath { 

    static String folderPath; 

    public static String getFolderPath(Context context) { 
     if (isSdPresent() == true) { 
      try { 
       File sdPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FolderName"); 
       if(!sdPath.exists()) { 
        sdPath.mkdirs(); 
        folderPath = sdPath.getAbsolutePath(); 
       } else if (sdPath.exists()) { 
        folderPath = sdPath.getAbsolutePath(); 
       } 
      } 
      catch (Exception e) { 

      } 
      folderPath = Environment.getExternalStorageDirectory().getPath()+"/FolderName/"; 
     } 
     else { 
      try { 
       File cacheDir=new File(context.getCacheDir(),"FolderName/"); 
       if(!cacheDir.exists()) { 
        cacheDir.mkdirs(); 
        folderPath = cacheDir.getAbsolutePath(); 
       } else if (cacheDir.exists()) { 
        folderPath = cacheDir.getAbsolutePath(); 
       } 
      } 
      catch (Exception e){ 

      } 
     } 
     return folderPath; 
    } 

    public static boolean isSdPresent() { 
     return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
    } 
} 
0

Este sencillo método se trabajó para mí. Probado en todo tipo de dispositivos.

public boolean externalMemoryAvailable() { 
    if (Environment.isExternalStorageRemovable()) { 
     //device support sd card. We need to check sd card availability. 
     String state = Environment.getExternalStorageState(); 
     return state.equals(Environment.MEDIA_MOUNTED) || state.equals(
      Environment.MEDIA_MOUNTED_READ_ONLY); 
    } else { 
     //device not support sd card. 
     return false; 
    } 
    } 
9

Aceptado respuesta no funciona para mí

Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 

En caso si tiene un dispositivo de almacenamiento incorporado, devuelve true; Mi solución es que para verificar el conteo de directorios de archivos externos, si hay más de uno, el dispositivo tiene sdcard. Funciona y lo probé para varios dispositivos.

public static boolean hasRealRemovableSdCard(Context context) { 
    return ContextCompat.getExternalFilesDirs(context, null).length >= 2; 
} 
2

Puede comprobar si la tarjeta SD externa extraíble está disponible como esto

public static boolean externalMemoryAvailable(Activity context) { 
    File[] storages = ContextCompat.getExternalFilesDirs(context, null); 
    if (storages.length > 1 && storages[0] != null && storages[1] != null) 
     return true; 
    else 
     return false; 

} 

Esto funciona perfectamente ya que he probado.

Cuestiones relacionadas