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;
}
@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)
}

@wiraSan1262
Copy link

StatFs ? to root storage . . .

@m-asadullah
Copy link

// Get StatFs for the root storage
StatFs statFs = new StatFs(Environment.getRootDirectory().getPath());

// Get StatFs for the external storage
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());

Root Storage (Environment.getRootDirectory().getPath()):

  • Definition: This refers to the root directory of the Android system. It's where the system files are stored.
  • Usage: As a developer, you generally don't need to interact with this directory, since modifying system files can harm the device's stability and integrity.
  • Path Example: Typically something like /system.

External Storage (Environment.getExternalStorageDirectory().getPath()):

  • Definition: This refers to the primary shared/external storage directory where users can store their media and files. It's accessible by both the user and apps, and is often what people refer to as the "SD card" (though it may be internal to the device).
  • Usage: You use this directory to store user data that needs to be shared across apps or that users might want to access directly (e.g., pictures, videos, downloads).
  • Path Example: Typically something like /storage/emulated/0.
Storage Type Access Method Typical Path Usage
Root Storage Environment.getRootDirectory().getPath() /system System files, not usually modified by apps
External Storage
(Phone: default storage available for user)
Environment.getExternalStorageDirectory().getPath() /storage/emulated/0 User files, media, shared app data
External Storage
(SDCard)
Environment.getExternalStorageDirectory().getPath() /storage/emulated/1 User files, media in MicroSD card

@wiraSan1262
Copy link

i was commenting @mohammednawas8

for below Build.VERSION_CODES.O

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