Arslan Khan
Arslan Khan

Reputation: 41

Unable to get correct phone memory sizes(Internal Storage Size, Total Storage size, and total External size)

Here is the piece of code I made for getting Internal Total Storage size, Available Internal Storage size, External Storage size and Available External Storage size.

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

for getting availableInternalMemorySize

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

for total Internal Memory Size and so on...

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

Upvotes: 4

Views: 70

Answers (1)

Muhammad Mubeen
Muhammad Mubeen

Reputation: 153

Try this

 fun readableByteCount(bytes: Long, si: Boolean): String {
        val unit = if (si) 1000 else 1024
        if (bytes < unit) return "$bytes B"
        val exp = (Math.log(bytes.toDouble()) / Math.log(unit.toDouble())).toInt()
        val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i"
        return String.format("%.1f %sB", bytes / Math.pow(unit.toDouble(), exp.toDouble()), pre)
    }

Upvotes: 1

Related Questions