Skip to content

Instantly share code, notes, and snippets.

@li-jkwok
Created August 1, 2016 18:39
Show Gist options
  • Save li-jkwok/e460a042326e8509ada9ec23ae677bdf to your computer and use it in GitHub Desktop.
Save li-jkwok/e460a042326e8509ada9ec23ae677bdf to your computer and use it in GitHub Desktop.
Getting Total Disk Space Available for Android Device
/**
* Get the total disk space available on this Android Device
*
* @return total size (in bytes) that is the total disk space avaialble on the device.
*/
public static long getTotalDiskSpace() {
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
long totalDiskSpace = statFs.getBlockCount() * statFs.getBlockSize();
return totalDiskSpace;
}
@mohammednawas8
Copy link

mohammednawas8 commented Jan 22, 2024

This code worked for me, but im still looking for an implementation that works on old versions

fun getTotalStorageSize(context: Context): Double {
    val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
       return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           try {
               val storageStatsManager = context.getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager
               val uuid = storageManager.getUuidForPath(Environment.getDataDirectory())
               val totalBytes = storageStatsManager.getTotalBytes(uuid)
               val sizeRepresentation = StorageUtil.getStorageSizeRepresentation(totalBytes)
               val base = sizeRepresentation.base.toDouble()
               val totalGB = totalBytes / (base * base * base)
               totalGB
           } catch (e: IOException){
               0.0
           }

        } else {
            TODO("Implementation for devices that work on lower versions")
        }
}

object StorageUtil {
    /**
     * Determines if the data size is in Binary or in Decimal.
     */
    fun getStorageSizeRepresentation(storageSizeInBytes: Long): SizeRepresentation {
        /**
         * In Binary representation the base is 2 and the storage size could be 2, 4, 8, 16, 32, 64, 128, ...
         * In Decimal representation we multiply by 10
         * To determine what type of representation the device uses we can convert the total storage size in bytes to Binary by dividing it on 1024 three times
         * Then we take Log(binary_size) of base 2, if the reminder = 0 then we know we have Binary representation.
         */
        return if (log(storageSizeInBytes / (1024.0.pow(3)), 2.0) % 1.0 == 0.0) {
            SizeRepresentation.Binary
        } else {
            SizeRepresentation.Decimal
        }
    }
}

enum class SizeRepresentation(val base: Int) {
    Binary(1024), Decimal(1000)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment