Khurram Ansar Khurram Ansar - 1 month ago 8
Android Question

Get Internal and External Memory size in MarshMallow

I am trying to show the size of Internal and External(SD card) memory in my application.My code is working fine for kitkat and below api versions but My app is crashing in Marshmallow or lollipop .Here is my code ...

public static long getAvailableInternalMemorySize()

{
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}

public static long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}

public static long getAvailableExternalMemorySize() {


String secStore = System.getenv("SECONDARY_STORAGE");
File path = new File(secStore);
StatFs stat = new StatFs(path.getPath());

long blockSize = stat.getBlockSize();

long availableBlocks = stat.getAvailableBlocks();

long total = availableBlocks * blockSize;

return total;
}


public static long getTotalExternalMemorySize() {

String secStore = System.getenv("SECONDARY_STORAGE");
File path = new File(secStore);
StatFs stat = new StatFs(path.getPath());

long blockSize = stat.getBlockSize();

long availableBlocks = stat.getBlockCount();

long total = availableBlocks * blockSize;


return total;

}


Can you tell me the solution to get the memory sizes in above api versions...?

EKN EKN
Answer

In lolipop or marshmallo you must use
Environment.getExternalStorageDirectory().getAbsolutePath();

to get external storage path instead of System.getenv("SECONDARY_STORAGE");

Refer beolw code for get external and internal storage in >android 5.0

public static String getTotalInternalMemorySize() {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return formatSize(totalBlocks * blockSize);
        }

        public static String getAvailableExternalMemorySize() {
                File path = Environment.getExternalStorageDirectory();
                StatFs stat = new StatFs(path.getPath());
                long blockSize = stat.getBlockSize();
                long availableBlocks = stat.getAvailableBlocks();
                return formatSize(availableBlocks * blockSize);
            }