How to get an External storage sd card size (With Mounted SD card)?

Achiever picture Achiever · May 30, 2013 · Viewed 8.3k times · Source

Link :I worked on based on this Link

I added this line to find the size (both Internal and External) size,

return availableExternalMemorySize/(1024*1024);

I tested in my Tablet. I am getting both Internal and External SD card size as,

In Internal Storage:

  1. Total Memory --1007
  2. Available Memory --683

In External Storage:

  1. Total Memory -- 1763
  2. Available Memory -- 1554

But in Tablet, I saw settings. An External Storage size has 8GB. But it is showing me 1.7 GB around when I tested via programmatically.

What is the procedure to find an External storage size?

Answer

MDMalik picture MDMalik · May 30, 2013

To get the external SD card's available "free" space to show a number which agrees with the Menu->Settings->SD card and phone storage's number, use the following code:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
double sdAvailSize = (double)stat.getAvailableBlocks()
                   * (double)stat.getBlockSize();
//One binary gigabyte equals 1,073,741,824 bytes.
double gigaAvailable = sdAvailSize / 1073741824;

Here is how you get internal storage sizes:

 StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());        
 long blockSize = statFs.getBlockSize();
 long totalSize = statFs.getBlockCount()*blockSize;
 long availableSize = statFs.getAvailableBlocks()*blockSize;
 long freeSize = statFs.getFreeBlocks()*blockSize;

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;

Short note

Free blocks:

The total number of blocks that are free on the file system, including reserved blocks (that are not available to normal applications).

Available blocks:

The number of blocks that are free on the file system and available to applications.


Here is how to detect whether SD card is mounted:

 String state = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED.equals(state)) 
 {
   // We can read and write the media    
 } 
 else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) 
 {
    // We can only read the media     
 } 
 else 
 {
    // No external media
 }

Relevant documentation: http://developer.android.com/reference/android/os/StatFs.html