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;
}
@mddanishansari
Copy link

@m-asadullah Thanks for the explanation

@leeyisoft
Copy link

If your app minAPI is 26, then try this

fun getTotalStorage(): Double {
    val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
    val storageStatsManager = getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager
    val storageVolumes = storageManager.storageVolumes
    var totalBytes = 0L
    for (volume in storageVolumes) {
        val uuid = volume.uuid?.let { UUID.fromString(it) } ?: StorageManager.UUID_DEFAULT
        totalBytes += storageStatsManager.getTotalBytes(uuid)
    }
    return totalBytes.toDouble() / 1024.0 / 1024.0 / 1024.0
}
package com.icstoragespace.ic_storage_space

import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import android.os.Environment
import android.os.StatFs

import android.content.Context
import android.os.storage.StorageManager
import android.app.usage.StorageStats
import android.app.usage.StorageStatsManager
import java.io.IOException
import java.util.UUID

/** IcStorageSpacePlugin */
class IcStorageSpacePlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    lateinit var context: Context

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        context = flutterPluginBinding.getApplicationContext()
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ic_storage_space")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
            "getFreeDiskSpaceInBytes" -> result.success(getFreeDiskSpaceInBytes())
            "getTotalDiskSpaceInBytes" -> result.success( getTotalDiskSpaceInBytes())
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
//        context = binding.getApplicationContext();
        channel.setMethodCallHandler(null)
    }


    private fun getFreeDiskSpaceInBytes(): Long {
        val stat = StatFs(Environment.getExternalStorageDirectory().path)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
            return stat.blockSizeLong * stat.availableBlocksLong
        else
            return stat.blockSize.toLong() * stat.availableBlocks.toLong()
    }

    private fun getTotalDiskSpaceInBytes(): Long {
        val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager;
        val storageStatsManager = context.getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager;
        val storageVolumes = storageManager.storageVolumes;
        var totalBytes = 0L;
        for (volume in storageVolumes) {
            val uuid = volume.uuid?.let { UUID.fromString(it) } ?: StorageManager.UUID_DEFAULT;
            totalBytes += storageStatsManager.getTotalBytes(uuid);
        }
        return totalBytes.toLong();
    }
    private fun getTotalDiskSpaceInBytes_(): Long {
        val stat = StatFs(Environment.getRootDirectory().absolutePath)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
            return stat.blockSizeLong * stat.blockCountLong
        else
            return stat.blockSize.toLong() * stat.blockCount.toLong()
    }


}


@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