Comment vérifier l’espace disponible sur l’appareil Android? sur la carte SD?

Comment puis-je vérifier la quantité de Mo ou de Go restant sur le périphérique Android? J’utilise JAVA et Android SDK 2.0.1.

Y a-t-il un service système qui exposerait quelque chose comme ça?

Essayez ce code :

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount(); long megAvailable = bytesAvailable / 1048576; System.out.println("Megs :"+megAvailable); 

Mettre à jour:

getBlockCount() – retourne la taille de la carte SD;

getAvailableBlocks() – Retourne le nombre de blocs encore accessibles aux programmes normaux (merci Joe)

La réponse de Yaroslav donnera la taille de la carte SD, pas l’espace disponible. GetAvailableBlocks getAvailableBlocks() de getAvailableBlocks() renverra le nombre de blocs encore accessibles aux programmes normaux. Voici la fonction que j’utilise:

 public static float megabytesAvailable(File f) { StatFs stat = new StatFs(f.getPath()); long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks(); return bytesAvailable / (1024.f * 1024.f); } 

Le code ci-dessus fait référence à certaines fonctions obsolètes au 13 août 2014. Je reproduis ci-dessous une version mise à jour:

 public static float megabytesAvailable(File f) { StatFs stat = new StatFs(f.getPath()); long bytesAvailable = 0; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) bytesAvailable = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong(); else bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks(); return bytesAvailable / (1024.f * 1024.f); } 

J’ai conçu des fonctions prêtes à l’emploi pour obtenir de l’espace disponible dans différentes unités. Vous pouvez utiliser ces méthodes en copiant simplement l’une d’entre elles dans votre projet.

 /** * @return Number of bytes available on External storage */ public static long getAvailableSpaceInBytes() { long availableSpace = -1L; StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availableSpace; } /** * @return Number of kilo bytes available on External storage */ public static long getAvailableSpaceInKB(){ final long SIZE_KB = 1024L; long availableSpace = -1L; StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availableSpace/SIZE_KB; } /** * @return Number of Mega bytes available on External storage */ public static long getAvailableSpaceInMB(){ final long SIZE_KB = 1024L; final long SIZE_MB = SIZE_KB * SIZE_KB; long availableSpace = -1L; StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availableSpace/SIZE_MB; } /** * @return Number of gega bytes available on External storage */ public static long getAvailableSpaceInGB(){ final long SIZE_KB = 1024L; final long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB; long availableSpace = -1L; StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availableSpace/SIZE_GB; } 

De nouvelles méthodes ont été introduites depuis la version API 18.

J’ai utilisé quelque chose comme ça pour l’estimation de la taille du cache disque (pour Picasso OkHttp downloader cache). Méthode auxiliaire était comme ça:

 private static final Ssortingng BIG_CACHE_PATH = "my-cache-dir"; private static final float MAX_AVAILABLE_SPACE_USE_FRACTION = 0.9f; private static final float MAX_TOTAL_SPACE_USE_FRACTION = 0.25f; static File createDefaultCacheDirExample(Context context) { File cache = new File(context.getApplicationContext().getCacheDir(), BIG_CACHE_PATH); if (!cache.exists()) { cache.mkdirs(); } return cache; } /** * Calculates minimum of available or total fraction of disk space * * @param dir * @return space in bytes */ @SuppressLint("NewApi") static long calculateAvailableCacheSize(File dir) { long size = 0; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); int sdkInt = Build.VERSION.SDK_INT; long totalBytes; long availableBytes; if (sdkInt < Build.VERSION_CODES.JELLY_BEAN_MR2) { int blockSize = statFs.getBlockSize(); availableBytes = ((long) statFs.getAvailableBlocks()) * blockSize; totalBytes = ((long) statFs.getBlockCount()) * blockSize; } else { availableBytes = statFs.getAvailableBytes(); totalBytes = statFs.getTotalBytes(); } // Target at least 90% of available or 25% of total space size = (long) Math.min(availableBytes * MAX_AVAILABLE_SPACE_USE_FRACTION, totalBytes * MAX_TOTAL_SPACE_USE_FRACTION); } catch (IllegalArgumentException ignored) { // ignored } return size; } 

Sur la base de cette réponse, Ajout du support pour la version Android <18

 public static float megabytesAvailable(File file) { StatFs stat = new StatFs(file.getPath()); long bytesAvailable; if(Build.VERSION.SDK_INT >= 18){ bytesAvailable = getAvailableBytes(stat); } else{ //noinspection deprecation bytesAvailable = stat.getBlockSize() * stat.getAvailableBlocks(); } return bytesAvailable / (1024.f * 1024.f); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private static long getAvailableBytes(StatFs stat) { return stat.getBlockSizeLong() * stat.getAvailableBlocksLong(); } 

De plus, si vous souhaitez vérifier l’espace disponible sur la mémoire interne, utilisez:

 File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); 

Google a des informations à ce sujet sur la page de démarrage – Voir Espace libre de la requête. Ils disent que vous pouvez soit vérifier l’espace disponible par getFreeSpace() mais ils déclarent que c’est inexact et vous devriez vous attendre à un peu moins d’espace libre que celui-ci. Ils disent:

Si le nombre renvoyé est de quelques Mo de plus que la taille des données que vous souhaitez enregistrer, ou si le système de fichiers est rempli à moins de 90%, alors il est probablement prudent de procéder. Sinon, vous ne devriez probablement pas écrire sur le stockage.

En outre, ils donnent le conseil qu’il est souvent plus utile de ne pas vérifier l’espace libre et d’ try catch une erreur:

Vous n’êtes pas obligé de vérifier la quantité d’espace disponible avant d’enregistrer votre fichier. Vous pouvez plutôt essayer d’écrire le fichier immédiatement, puis intercepter une exception IOException si elle se produit. Vous devrez peut-être le faire si vous ne savez pas exactement combien d’espace vous avez besoin. Par exemple, si vous modifiez le codage du fichier avant de l’enregistrer en convertissant une image PNG en JPEG, vous ne connaîtrez pas la taille du fichier au préalable.

Je recommande que pour les très grandes tailles de fichiers, vous devez vérifier le stockage disponible au préalable afin de ne pas perdre de temps à télécharger ou à créer un fichier trop volumineux. Dans les deux cas, vous devez toujours utiliser try catch . Je pense donc que le seul argument pour vérifier au préalable l’espace disponible est l’utilisation inutile des ressources et le temps est trop long.

J’espère que ce code peut aider les autres. Testé fonctionne bien. Merci au membre ci-dessus pour le clarifier.

 /** * Get the free disk available space in boolean to download requested file * * @return boolean value according to size availability */ protected static boolean isMemorySizeAvailableAndroid(long download_bytes, boolean isExternalMemory) { boolean isMemoryAvailable = false; long freeSpace = 0; // if isExternalMemory get true to calculate external SD card available size if(isExternalMemory){ try { StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); freeSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); if(freeSpace > download_bytes){ isMemoryAvailable = true; }else{ isMemoryAvailable = false; } } catch (Exception e) {e.printStackTrace(); isMemoryAvailable = false;} }else{ // find phone available size try { StatFs stat = new StatFs(Environment.getDataDirectory().getPath()); freeSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); if(freeSpace > download_bytes){ isMemoryAvailable = true; }else{ isMemoryAvailable = false; } } catch (Exception e) {e.printStackTrace(); isMemoryAvailable = false;} } return isMemoryAvailable; } 
 public Ssortingng TotalExtMemory() { StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576; Ssortingng strI = Integer.toSsortingng(Total); return strI; } public Ssortingng FreeExtMemory() { StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); int Free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576; Ssortingng strI = Integer.toSsortingng(Free); return strI; } public Ssortingng BusyExtMemory() { StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576; int Free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576; int Busy = Total - Free; Ssortingng strI = Integer.toSsortingng(Busy); return strI; }