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(En
None of the solutions mentioned here can be used for External Memory. Here is my code(for RAM, ROM, System Storage and External Storage). You can calculate free storage by using (total storage - used storage). And also, one must not use Environment.getExternalStorageDirectory()
for external storage. It does not necessarily points to External SD Card. Also, this solution will work with all the Android versions (tested for API 16-30 on real devices and emulators).
// Divide by (1024*1024*1024) to get in GB, by (1024*1024) to get in MB, by 1024 to get in KB..
// RAM
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
manager.getMemoryInfo(memoryInfo);
long totalRAM=memoryInfo.totalMem;
long availRAM=memoryInfo.availMem; // remember to convert in GB,MB or KB.
long usedRAM=totalRAM-availRAM;
// ROM
getTotalStorageInfo(Environment.getDataDirectory().getPath());
getUsedStorageInfo(Environment.getDataDirectory().getPath());
// System Storage
getTotalStorageInfo(Environment.getRootDirectory().getPath());
getUsedStorageInfo(Environment.getRootDirectory().getPath());
// External Storage (SD Card)
File[] files = ContextCompat.getExternalFilesDirs(context, null);
if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.JELLY_BEAN_MR2){
if (files.length == 1) {
Log.d("External Storage Memory","is present");
getTotalStorageInfo(files[0].getPath());
getUsedStorageInfo(files[0].getPath());
}
} else {
if (files.length > 1 && files[0] != null && files[1] != null) {
Log.d("External Storage Memory","is present");
long t=getTotalStorageInfo(files[1].getPath());
long u=getUsedStorageInfo(files[1].getPath());
System.out.println("Total External Mem: "+t+" Used External Mem: "+u+" Storage path: "+files[1].getPath());
}
}
}
public long getTotalStorageInfo(String path) {
StatFs statFs = new StatFs(path);
long t;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
t = statFs.getTotalBytes();
} else {
t = statFs.getBlockCount() * statFs.getBlockCount();
}
return t; // remember to convert in GB,MB or KB.
}
public long getUsedStorageInfo(String path) {
StatFs statFs = new StatFs(path);
long u;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
u = statFs.getTotalBytes() - statFs.getAvailableBytes();
} else {
u = statFs.getBlockCount() * statFs.getBlockSize() - statFs.getAvailableBlocks() * statFs.getBlockSize();
}
return u; // remember to convert in GB,MB or KB.
}
Now here for ROM I have used path as "/data" and for System Storage path is "/system". And for External Storage I have used ContextCompat.getExternalFilesDirs(context, null);
therefore it will work on Android Q and Android R also. I hope, this will help you.