¿Cómo encontrar la cantidad de almacenamiento libre (espacio en disco) que queda en Android?


Estoy tratando de averiguar el espacio en disco disponible en el teléfono Android que ejecuta mi aplicación. ¿Hay alguna manera de hacer esto programáticamente?

Gracias,

Author: Damian Yerrick, 2011-08-19

9 answers

Intenta StatFs.getAvailableBlocks . Necesitará convertir el número de bloques a KB con getBlockSize.

 12
Author: Femi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-18 22:50:13

Ejemplo: Obtener un tamaño legible como 1 Gb

String memory = bytesToHuman (totalMemory())

/*************************************************************************************************
Returns size in bytes.

If you need calculate external memory, change this: 
    StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
to this: 
    StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());        
**************************************************************************************************/
    public long totalMemory()
    {
        StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());   
        long   total  = (statFs.getBlockCount() * statFs.getBlockSize());
        return total;
    }

    public long freeMemory()
    {
        StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
        long   free   = (statFs.getAvailableBlocks() * statFs.getBlockSize());
        return free;
    }

    public long busyMemory()
    {
        StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());   
        long   total  = (statFs.getBlockCount() * statFs.getBlockSize());
        long   free   = (statFs.getAvailableBlocks() * statFs.getBlockSize());
        long   busy   = total - free;
        return busy;
    }

Convertir bytes a formato legible por humanos (como 1 Mb, 1 Gb)

    public static String floatForm (double d)
    {
       return new DecimalFormat("#.##").format(d);
    }


    public static String bytesToHuman (long size)
    {
        long Kb = 1  * 1024;
        long Mb = Kb * 1024;
        long Gb = Mb * 1024;
        long Tb = Gb * 1024;
        long Pb = Tb * 1024;
        long Eb = Pb * 1024;

        if (size <  Kb)                 return floatForm(        size     ) + " byte";
        if (size >= Kb && size < Mb)    return floatForm((double)size / Kb) + " Kb";
        if (size >= Mb && size < Gb)    return floatForm((double)size / Mb) + " Mb";
        if (size >= Gb && size < Tb)    return floatForm((double)size / Gb) + " Gb";
        if (size >= Tb && size < Pb)    return floatForm((double)size / Tb) + " Tb";
        if (size >= Pb && size < Eb)    return floatForm((double)size / Pb) + " Pb";
        if (size >= Eb)                 return floatForm((double)size / Eb) + " Eb";

        return "???";
    }
 45
Author: XXX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-19 11:34:21

Basado en la respuesta de @XXX, he creado un fragmento de código gist que envuelve StatFs para un uso fácil y simple. Puedes encontrarlo aquí como GitHub gist.

 6
Author: Tom Susel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-15 06:27:47

Hay algunas sutilezas con respecto a las rutas que ninguna de las respuestas actuales aborda. Debes usar el camino correcto basado en qué tipo de estadísticas te interesan. Basado en una profunda inmersión en DeviceStorageMonitorService.java que genera las advertencias de espacio en disco bajo en el área de notificación y las emisiones adhesivas para ACTION_DEVICE_STORAGE_LOW, estas son algunas de las rutas que puede usar:

  1. Para comprobar el espacio libre del disco interno utilice el directorio de los datos obtenido vía Ambiente.getDataDirectory(). Esto le dará el espacio libre en la partición de datos. La partición de datos aloja todo el almacenamiento interno para todas las aplicaciones en el dispositivo.

  2. Para comprobar el espacio libre en disco externo (SDCARD) utilice el directorio de almacenamiento externo obtenido a través de Environment.getExternalStorageDirectory(). Esto le dará el espacio libre en la tarjeta SD.

  3. Para comprobar si hay memoria disponible en la partición del sistema que contiene archivos del sistema operativo, utilice Ambiente.getRootDirectory(). Dado que su aplicación no tiene acceso a la partición del sistema, esta estadística probablemente no sea muy útil. DeviceStorageMonitorService lo utiliza con fines informativos y lo introduce en un registro.

  4. Para comprobar si hay archivos temporales / memoria caché, utilice Entorno.getDownloadCacheDirectory(). DeviceStorageMonitorService intenta limpiar algunos de los archivos temporales cuando la memoria se agota.

Algún código de ejemplo para obtener el interno (/data), externo (/sdcard) y OS (/system) memoria libre:

// Get internal (data partition) free space
// This will match what's shown in System Settings > Storage for 
// Internal Space, when you subtract Total - Used
public long getFreeInternalMemory()
{
    return getFreeMemory(Environment.getDataDirectory());
}

// Get external (SDCARD) free space
public long getFreeExternalMemory()
{
    return getFreeMemory(Environment.getExternalStorageDirectory());
}

// Get Android OS (system partition) free space
public long getFreeSystemMemory()
{
    return getFreeMemory(Environment.getRootDirectory());
}

// Get free space for provided path
// Note that this will throw IllegalArgumentException for invalid paths
public long getFreeMemory(File path)
{
    StatFs stats = new StatFs(path.getAbsolutePath());
    return stats.getAvailableBlocksLong() * stats.getBlockSizeLong();
}
 6
Author: Theo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-17 23:52:25

Encasillar sus valores enteros mucho antes de hacer la multiplicación. La multiplicación entre dos enteros grandes podría desbordarse y dar un resultado negativo.

public long sd_card_free(){
    File path = Environment.getExternalStorageDirectory();
    StatFs stat = new StatFs(path.getPath());
    int availBlocks = stat.getAvailableBlocks();
    int blockSize = stat.getBlockSize();
    long free_memory = (long)availBlocks * (long)blockSize;

    return free_memory;
}
 4
Author: user802467,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-26 02:37:28

Con un poco de Google que podría haber encontrado la StatFs-clase que es:

[...] un Wrapper para Unix statfs ().

Se proporcionan ejemplos

 3
Author: Lukas Knuth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:24
    File pathOS = Environment.getRootDirectory();//Os Storage
    StatFs statOS = new StatFs(pathOS.getPath());

    File pathInternal = Environment.getDataDirectory();// Internal Storage
  StatFs statInternal = new StatFs(pathInternal.getPath());

    File pathSdcard = Environment.getExternalStorageDirectory();//External(SD CARD) Storage
    StatFs statSdcard = new StatFs(pathSdcard.getPath());

    if((android.os.Build.VERSION.SDK_INT < 18)) {
        // Get Android OS (system partition) free space API 18 & Below
        int totalBlocksOS = statOS.getBlockCount();
        int blockSizeOS = statOS.getBlockSize();
        int availBlocksOS = statOS.getAvailableBlocks();
        long total_OS_memory = (long) totalBlocksOS * (long) blockSizeOS;
        long free_OS_memory = (long) availBlocksOS * (long) blockSizeOS;
        long Used_OS_memory = total_OS_memory - free_OS_memory;
        TotalOsMemory       =   total_OS_memory ;
        FreeOsMemory        =   free_OS_memory;
        UsedOsMemory        =   Used_OS_memory;

        // Get internal (data partition) free space API 18 & Below
        int totalBlocksInternal = statInternal.getBlockCount();
        int blockSizeInternal = statOS.getBlockSize();
        int availBlocksInternal = statInternal.getAvailableBlocks();
        long total_Internal_memory = (long) totalBlocksInternal * (long) blockSizeInternal;
        long free_Internal_memory = (long) availBlocksInternal * (long) blockSizeInternal;
        long Used_Intenal_memory = total_Internal_memory - free_Internal_memory;
        TotalInternalMemory =   total_Internal_memory;
        FreeInternalMemory  =   free_Internal_memory ;
        UsedInternalMemory  =   Used_Intenal_memory ;

        // Get external (SDCARD) free space for API 18 & Below
        int totalBlocksSdcard = statSdcard.getBlockCount();
        int blockSizeSdcard = statOS.getBlockSize();
        int availBlocksSdcard = statSdcard.getAvailableBlocks();
        long total_Sdcard_memory = (long) totalBlocksSdcard * (long) blockSizeSdcard;
        long free_Sdcard_memory = (long) availBlocksSdcard * (long) blockSizeSdcard;
        long Used_Sdcard_memory = total_Sdcard_memory - free_Sdcard_memory;
        TotalSdcardMemory   =   total_Sdcard_memory;
        FreeSdcardMemory    =   free_Sdcard_memory;
        UsedSdcardMemory    =   Used_Sdcard_memory;
    }
    else {
        // Get Android OS (system partition) free space for API 18 & Above
        long   total_OS_memory          = (statOS.       getBlockCountLong()      * statOS.getBlockSizeLong());
        long   free_OS_memory           = (statOS.       getAvailableBlocksLong() * statOS.getBlockSizeLong());
        long Used_OS_memory = total_OS_memory - free_OS_memory;
        TotalOsMemory       =   total_OS_memory ;
        FreeOsMemory        =   free_OS_memory;
        UsedOsMemory        =   Used_OS_memory;

        // Get internal (data partition) free space for API 18 & Above
        long   total_Internal_memory    = (statInternal. getBlockCountLong()      * statInternal.getBlockSizeLong());
        long   free_Internal_memory     = (statInternal. getAvailableBlocksLong() * statInternal.getBlockSizeLong());
        long Used_Intenal_memory = total_Internal_memory - free_Internal_memory;
        TotalInternalMemory =   total_Internal_memory;
        FreeInternalMemory  =   free_Internal_memory ;
        UsedInternalMemory  =   Used_Intenal_memory ;

        // Get external (SDCARD) free space for API 18 & Above
        long   total_Sdcard_memory      = (statSdcard.   getBlockCountLong()      * statSdcard.getBlockSizeLong());
        long   free_Sdcard_memory       = (statSdcard.   getAvailableBlocksLong() * statSdcard.getBlockSizeLong());
        long Used_Sdcard_memory = tota*emphasized text*l_Sdcard_memory - free_Sdcard_memory;
        TotalSdcardMemory   =   total_Sdcard_memory;
        FreeSdcardMemory    =   free_Sdcard_memory;
        UsedSdcardMemory    =   Used_Sdcard_memory;
    }
}
 2
Author: gazi shaikh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-22 21:13:39

Desde blocksize y getAvailableBlocks

Están en desuso

Este código se puede usar

Nota basada en la respuesta anterior de user802467

public long sd_card_free(){
    File path = Environment.getExternalStorageDirectory();
    StatFs stat = new StatFs(path.getPath());
    long availBlocks = stat.getAvailableBlocksLong();
    long blockSize = stat.getBlockSizeLong();
    long free_memory = availBlocks * blockSize;

    return free_memory;
}

Podemos usar getAvailableBlocksLong y getBlockSizeLong

 0
Author: 1234567,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-21 10:29:23

Ubicaciones de memoria:

File[] roots = context.getExternalFilesDirs(null);
String path = roots[0].getAbsolutePath(); // PhoneMemory
String path = roots[1].getAbsolutePath(); // SCCard (if available)
String path = roots[2].getAbsolutePath(); // USB (if available)

Uso

long totalMemory = StatUtils.totalMemory(path);
long freeMemory = StatUtils.freeMemory(path);

final String totalSpace = StatUtils.humanize(totalMemory, true);
final String usableSpace = StatUtils.humanize(freeMemory, true);

Puedes usar esto

public final class StatUtils {

    public static long totalMemory(String path) {
        StatFs statFs = new StatFs(path);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            //noinspection deprecation
            return (statFs.getBlockCount() * statFs.getBlockSize());
        } else {
            return (statFs.getBlockCountLong() * statFs.getBlockSizeLong());
        }
    }

    public static long freeMemory(String path) {
        StatFs statFs = new StatFs(path);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            //noinspection deprecation
            return (statFs.getAvailableBlocks() * statFs.getBlockSize());
        } else {
            return (statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong());
        }
    }

    public static long usedMemory(String path) {
        long total = totalMemory(path);
        long free = freeMemory(path);
        return total - free;
    }

    public static String humanize(long bytes, boolean si) {
        int unit = si ? 1000 : 1024;
        if (bytes < unit) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
        return String.format(Locale.ENGLISH, "%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }
}
 0
Author: Samuel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-06 09:46:11