web-dev-qa-db-fra.com

Android obtenir la taille libre de la mémoire interne / externe

Je souhaite obtenir par programme la taille de la mémoire libre sur le stockage interne/externe de mon périphérique. J'utilise ce morceau de code:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;
Log.e("","Available MB : "+megAvailable);

File path = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize = stat2.getBlockSize();
long availableBlocks = stat2.getAvailableBlocks();
String format =  Formatter.formatFileSize(this, availableBlocks * blockSize);
Log.e("","Format : "+format);

et le résultat que j'obtiens est:

11-15 10:27:18.844: E/(25822): Available MB : 7572
11-15 10:27:18.844: E/(25822): Format : 869MB

Le problème est que je veux obtenir la mémoire libre de SdCard qui est 1,96GB maintenant. Comment puis-je corriger ce code afin que je puisse obtenir la taille libre?

84
Android-Droid

Voici comment je l'ai fait:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable;
if (Android.os.Build.VERSION.SDK_INT >= 
    Android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
    bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
}
else {
    bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
}
long megAvailable = bytesAvailable / (1024 * 1024);
Log.e("","Available MB : "+megAvailable);
36
Android-Droid

Ci-dessous le code pour votre but:

public static boolean externalMemoryAvailable() {
        return Android.os.Environment.getExternalStorageState().equals(
                Android.os.Environment.MEDIA_MOUNTED);
    }

    public static String getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        return formatSize(availableBlocks * blockSize);
    }

    public static String getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        long totalBlocks = stat.getBlockCountLong();
        return formatSize(totalBlocks * blockSize);
    }

    public static String getAvailableExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSizeLong();
            long availableBlocks = stat.getAvailableBlocksLong();
            return formatSize(availableBlocks * blockSize);
        } else {
            return ERROR;
        }
    }

    public static String getTotalExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSizeLong();
            long totalBlocks = stat.getBlockCountLong();
            return formatSize(totalBlocks * blockSize);
        } else {
            return ERROR;
        }
    }

    public static String formatSize(long size) {
        String suffix = null;

        if (size >= 1024) {
            suffix = "KB";
            size /= 1024;
            if (size >= 1024) {
                suffix = "MB";
                size /= 1024;
            }
        }

        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffix != null) resultBuffer.append(suffix);
        return resultBuffer.toString();
    }

Obtenir RAM Taille

ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;
170
Dinesh Prajapati

Depuis API 9, vous pouvez faire:

long freeBytesInternal = new File(ctx.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
long freeBytesExternal = new File(getExternalFilesDir(null).toString()).getFreeSpace();
24
Tzoiker

Pour obtenir tous les dossiers de stockage disponibles (y compris les cartes SD), vous devez d’abord obtenir les fichiers de stockage:

File internalStorageFile=getFilesDir();
File[] externalStorageFiles=ContextCompat.getExternalFilesDirs(this,null);

Ensuite, vous pouvez obtenir la taille disponible de chacun de ceux-ci.

Il y a 3 façons de le faire:

API 8 et ci-dessous:

StatFs stat=new StatFs(file.getPath());
long availableSizeInBytes=stat.getBlockSize()*stat.getAvailableBlocks();

API 9 et supérieure:

long availableSizeInBytes=file.getFreeSpace();

API 18 et supérieure (non nécessaire si la précédente est correcte):

long availableSizeInBytes=new StatFs(file.getPath()).getAvailableBytes(); 

Pour obtenir une belle chaîne formatée de ce que vous avez maintenant, vous pouvez utiliser:

String formattedResult=Android.text.format.Formatter.formatShortFileSize(this,availableSizeInBytes);

ou vous pouvez l'utiliser si vous voulez voir exactement le nombre d'octets, mais:

NumberFormat.getInstance().format(availableSizeInBytes);

Notez que je pense que la mémoire interne pourrait être la même que la première mémoire externe, puisque la première est celle émulée.


EDIT: Utiliser StorageVolume sur Android Q et supérieur, je pense qu’il est possible d’obtenir l’espace libre de chacun, en utilisant quelque chose comme:

    val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
    val storageVolumes = storageManager.storageVolumes
    AsyncTask.execute {
        for (storageVolume in storageVolumes) {
            val uuid: UUID = storageVolume.uuid?.let { UUID.fromString(it) } ?: StorageManager.UUID_DEFAULT
            val allocatableBytes = storageManager.getAllocatableBytes(uuid)
            Log.d("AppLog", "allocatableBytes:${Android.text.format.Formatter.formatShortFileSize(this,allocatableBytes)}")
        }
    }

Je ne suis pas sûr que ce soit correct et je ne trouve pas le moyen de connaître la taille totale de chacun. J'ai donc écrit à ce sujet ici , et interrogé à ce sujet ici .

21

@ Android-Droid - vous vous trompez Environment.getExternalStorageDirectory() pointe vers un stockage externe qui ne doit pas nécessairement être une carte SD, il peut également s'agir d'un montage de mémoire interne. Voir:

Trouver un emplacement de carte SD externe

9
Sharp80

Essayez ce simple extrait

    public static String readableFileSize() {
    long availableSpace = -1L;
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    if (Android.os.Build.VERSION.SDK_INT >= Android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        availableSpace = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
    else
        availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();

    if(availableSpace <= 0) return "0";
    final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(availableSpace)/Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(availableSpace/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
7
Ness Tyagi

Il est très facile de connaître le stockage disponible si vous avez un chemin de stockage interne et externe. Aussi le chemin de stockage externe du téléphone vraiment très facile à trouver en utilisant

Environment.getExternalStorageDirectory (). GetPath ();

Donc, je me concentre simplement sur la façon de trouver les chemins de stockage externe amovible comme une carte SD amovible, USB OTG (USB OTG non testé car je n’ai pas USB OTG).

La méthode ci-dessous donnera une liste de tous les chemins de stockage amovibles externes possibles.

 /**
     * This method returns the list of removable storage and sdcard paths.
     * I have no USB OTG so can not test it. Is anybody can test it, please let me know
     * if working or not. Assume 0th index will be removable sdcard path if size is
     * greater than 0.
     * @return the list of removable storage paths.
     */
    public static HashSet<String> getExternalPaths()
    {
    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.replace("/media_rw","").replace("mnt", "storage"));
                        }
                    }
                }
            }
        }
    }
    //Phone's external storage path (Not removal SDCard path)
    String phoneExternalPath = Environment.getExternalStorageDirectory().getPath();

    //Remove it if already exist to filter all the paths of external removable storage devices
    //like removable sdcard, USB OTG etc..
    //When I tested it in ICE Tab(4.4.2), Swipe Tab(4.0.1) with removable sdcard, this method includes
    //phone's external storage path, but when i test it in Moto X Play (6.0) with removable sdcard,
    //this method does not include phone's external storage path. So I am going to remvoe the phone's
    //external storage path to make behavior consistent in all the phone. Ans we already know and it easy
    // to find out the phone's external storage path.
    out.remove(phoneExternalPath);

    return out;
}
6
Smeet

Ajout rapide au sujet de la mémoire externe

Ne soyez pas dérouté par le nom de la méthode externalMemoryAvailable() dans la réponse de Dinesh Prajapati.

Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) vous donne l'état actuel de la mémoire, si le support est présent et monté à son point de montage avec un accès en lecture/écriture. Vous obtiendrez true même sur des appareils sans carte SD, comme Nexus 5. Mais c'est quand même une méthode "indispensable" avant toute opération de stockage.

Pour vérifier s’il existe une carte SD sur votre appareil, vous pouvez utiliser la méthode ContextCompat.getExternalFilesDirs()

Il ne montre pas les périphériques transitoires, tels que les clés USB.

Sachez également que ContextCompat.getExternalFilesDirs() sur Android 4.3 et versions ultérieures renvoie toujours uniquement une entrée (carte SD si elle est disponible, sinon interne). Vous pouvez en lire plus à ce sujet ici .

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

dans mon cas c'était suffisant, mais n'oubliez pas que certains des appareils Android pourraient avoir 2 cartes SD, donc si vous en avez besoin, réglez le code ci-dessus.

4
Kirill Karmazin
@RequiresApi(api = Build.VERSION_CODES.O)
private void showStorageVolumes() {
    StorageStatsManager storageStatsManager = (StorageStatsManager) getSystemService(Context.STORAGE_STATS_SERVICE);
    StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
    if (storageManager == null || storageStatsManager == null) {
        return;
    }
    List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
    for (StorageVolume storageVolume : storageVolumes) {
        final String uuidStr = storageVolume.getUuid();
        final UUID uuid = uuidStr == null ? StorageManager.UUID_DEFAULT : UUID.fromString(uuidStr);
        try {
            Log.d("AppLog", "storage:" + uuid + " : " + storageVolume.getDescription(this) + " : " + storageVolume.getState());
            Log.d("AppLog", "getFreeBytes:" + Formatter.formatShortFileSize(this, storageStatsManager.getFreeBytes(uuid)));
            Log.d("AppLog", "getTotalBytes:" + Formatter.formatShortFileSize(this, storageStatsManager.getTotalBytes(uuid)));
        } catch (Exception e) {
            // IGNORED
        }
    }
}

Classe StorageStatsManager introduite Android O et supérieur, qui peut vous donner un octet gratuit et total en stockage externe/interne. Pour plus de détails avec le code source, vous pouvez lire mon article suivant. Vous pouvez utiliser la réflexion pour des valeurs inférieures à Android O

https://medium.com/cashify-engineering/how-to-get-storage-stats-in-Android-o-api-26-4b92eca6805b

1
Brijesh Gupta

À propos de la ménésie externe, il existe un autre moyen:
File external = Environment.getExternalStorageDirectory(); free:external.getFreeSpace(); total:external.getTotalSpace();

0
Edward Anderson

C'est comme ça que je l'ai fait ..

mémoire interne totale

double totalSize = new File(getApplicationContext().getFilesDir().getAbsoluteFile().toString()).getTotalSpace();
double totMb = totalSize / (1024 * 1024);

Taille libre interne

 double availableSize = new File(getApplicationContext().getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
    double freeMb = availableSize/ (1024 * 1024);

Mémoire externe libre et totale

 long freeBytesExternal =  new File(getExternalFilesDir(null).toString()).getFreeSpace();
       int free = (int) (freeBytesExternal/ (1024 * 1024));
        long totalSize =  new File(getExternalFilesDir(null).toString()).getTotalSpace();
        int total= (int) (totalSize/ (1024 * 1024));
       String availableMb = free+"Mb out of "+total+"MB";
0
makvine