Android get free size of internal/external memory

how to manage memory in android programmatically
get storage info android
android internal storage path
internal storage android data
android external storage path
storage service android
android low memory
android low memory warning

I want to get the size of free memory on internal/external storage of my device programmatically. I'm using this piece of code :

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;
Log.e("","Available MB : "+megAvailable);

File path = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize = stat2.getBlockSize();
long availableBlocks = stat2.getAvailableBlocks();
String format =  Formatter.formatFileSize(this, availableBlocks * blockSize);
Log.e("","Format : "+format);

and the result which I'm getting is :

11-15 10:27:18.844: E/(25822): Available MB : 7572
11-15 10:27:18.844: E/(25822): Format : 869MB

The problem is that I want to get the free memory of SdCard which is 1,96GB right now. How can I fix this code so I can get the free size ?

Below is the code for your purpose :

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

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

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

        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffix != null) resultBuffer.append(suffix);
        return resultBuffer.toString();
    }

Get RAM Size

ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;

How to get free size of internal/external memory in Android App?, This example demonstrates how do I get the free size of internal/external memory in android app.Step 1 − Create a new project in Android  This example demonstrates how do I get the free size of internal/external memory in android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.

This is the way I did it :

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable;
if (android.os.Build.VERSION.SDK_INT >= 
    android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
    bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
}
else {
    bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
}
long megAvailable = bytesAvailable / (1024 * 1024);
Log.e("","Available MB : "+megAvailable);

Android get free size of internal/external memory, I want to get the size of free memory on internalexternal storage of my device programmatically Im using this piece of code StatFs stat We can also determine the free space in our external storage if you are planning to install or save huge file in our external storage. In this tutorial, we will make use of ListView and each item of the ListView will hold information about a particular memory. We will focus on the RAM, Internal and External storage.

Since API 9 you can do:

long freeBytesInternal = new File(ctx.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
long freeBytesExternal = new File(getExternalFilesDir(null).toString()).getFreeSpace();

[Solved] Get operating system size android programmatically , I'd suggest to read this: java - How to Check available space on android device ? on SD card? - Stack Overflow[^] Android get free size of  When I run this code it only shows me the free storage of internal memory. Why does it not shows the external SD-Card size? On Device Storage I have 11GB free and on external SD-Card there are 40GB free.

To get all available storage folders (including SD cards), you first get the storage files:

File internalStorageFile=getFilesDir();
File[] externalStorageFiles=ContextCompat.getExternalFilesDirs(this,null);

Then you can get the available size of each of those.

There are 3 ways to do it:

API 8 and below:

StatFs stat=new StatFs(file.getPath());
long availableSizeInBytes=stat.getBlockSize()*stat.getAvailableBlocks();

API 9 and above:

long availableSizeInBytes=file.getFreeSpace();

API 18 and above (not needed if previous one is ok) :

long availableSizeInBytes=new StatFs(file.getPath()).getAvailableBytes(); 

To get a nice formatted string of what you got now, you can use:

String formattedResult=android.text.format.Formatter.formatShortFileSize(this,availableSizeInBytes);

or you can use this in case you wish to see exact bytes number but nicely:

NumberFormat.getInstance().format(availableSizeInBytes);

Do note that I think the internal storage could be the same as the first external storage, since the first one is the emulated one.


EDIT: Using StorageVolume on Android Q and above, I think it's possible to get the free space of each, using something like:

    val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
    val storageVolumes = storageManager.storageVolumes
    AsyncTask.execute {
        for (storageVolume in storageVolumes) {
            val uuid: UUID = storageVolume.uuid?.let { UUID.fromString(it) } ?: StorageManager.UUID_DEFAULT
            val allocatableBytes = storageManager.getAllocatableBytes(uuid)
            Log.d("AppLog", "allocatableBytes:${android.text.format.Formatter.formatShortFileSize(this,allocatableBytes)}")
        }
    }

I'm not sure if this is correct, and I can't find a way to get the total size of each, so I wrote about it here, and asked about it here.

Android beginner point: How to get Internal and External Memory , Explain:-How to get Internal and External Memory Size Programmatically in Android Device ? explain step by step. 1. you can check internal  Here is how you get external storage sizes (SD card size): StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); long blockSize = statFs.getBlockSize(); long totalSize = statFs.getBlockCount()*blockSize; long availableSize = statFs.getAvailableBlocks()*blockSize; long freeSize = statFs.getFreeBlocks()*blockSize;

@Android-Droid - you are wrong Environment.getExternalStorageDirectory() points to external storage which does not have to be SD card, it can also be mount of internal memory. See:

Find an external SD card location

How to get Android RAM, Internal and External Memory Information, How to get Android RAM, Internal and External Memory Information In this tutorial​, we might want to check the amount of free or available memory in our device. @Override public int getCount() { return listStorage.size(); } @Override public  For most devices, I believe there are no fixed limits built into Android for external file storage. (Internal storage is a different matter. Device manufacturers can impose quite restrictive limits, perhaps as low as 100MB shared among all applications.)

Access app-specific files, Other apps cannot access files stored within internal storage. This makes To add an app-specific file to the cache within external storage, get a reference to the  I'm attempting to get the total memory (RAM) and internal storage size, but every method I have used is reporting it too low. I'm aware the kernel may take up some of it but I need to know how much there is installed in total. For the memory I first just read from /proc/meminfo/ then used the getMemoryInfo. Each of these reported less than the

Data and file storage overview, Categories of storage locations; Permissions and access to external storage Use the directories within internal storage to save sensitive information If your APK size is very large, however, you can indicate a preference within Privacy · License · Brand guidelines; Get news and tips by email Subscribe. Follow the steps mentioned below: Follow the method mentioned above until Step 4. Tap your SD card. Tap the three dots on the top right corner of the screen. Tap Format as portable. Tap Format. The process will take around a few minutes to complete.

Storage Analyzer & Disk Usage, Storage Analyzer & Disk Usage displays information on sdcard, usb devices, sd-​cards, external and internal storage, cloud storages (Google Drive, Dropbox,  Generally, Android memory can be divided into two parts: internal and external. External memory can be easily increased, fortunately nowadays sd cards aren't inexpensive at all (for $25 you can buy a memory card with the capacity of 256 GB).

Comments
  • As of API level 18 they have renamed the method to end with Long. Probably you would need to add a check of API level prior to it
  • All Solution i tried not working anyone, when i do format as internal storage ... can you please me , how to do achieve this ?
  • getBlockSize() and getBlockCount are deprecated.
  • @DineshPrajapati Thanks for the answer, I have query , If I use Environment.getRootDirectory() instead-of Environment.getDataDirectory for calculating Internal Storage, I am getting some output ..this refers to Internal Memory other memory..
  • @DineshPrajapati .. Tested on MOTO G2 Getting wrong data for External Storage
  • Use Long in the end for newer API levels(>18)
  • Thank you so much for sharing knowledge
  • but this is depracated :(
  • @ArMo372 , Did u guys find out the replacement code for this?
  • Just replace getBlockSize and getAvailableBlocks with getBlockSizeLong and getAvailableBlocksLong.
  • this is not getting right available space. This is getting 1141 instead of 1678 @smg
  • Need different implementation for android Q onward as Q have some restriction to accessing file system. More more info check Scoped storage
  • File.getUsableSpace() is probably better because you are probably not running as root.
  • The File.getUsableSpace() looks like an easier method to use rather than using StatFs. Why would I use StatFs @MarkCarter?