The Android program determines whether the SD card exists and USES the capacity query implementation method

  • 2020-09-16 07:47:00
  • OfStack

This paper describes the Android programming to determine the existence of SD card and the use of capacity query implementation methods. To share for your reference, the details are as follows:

1. Determine whether an SD card exists. Return true to indicate the existence


/*  judge SD Whether the card exists   return true Said there is  */
public boolean avaiableMedia() {
  String status = Environment.getExternalStorageState();
  if (status.equals(Environment.MEDIA_MOUNTED)) {
   return true;
  } else {
   return false;
  }
}

2. Get the free space for the SD card


/*  To obtain SD Card free space  */
public long getSDFreeSize() {
  //  achieve SD Carven path 
  File path = Environment.getExternalStorageDirectory();
  StatFs sf = new StatFs(path.getPath());
  //  Gets the size of a single block of data (Byte)
  long blockSize = sf.getBlockSizeLong();
  //  The number of free data blocks 
  long freeBlocks = sf.getAvailableBlocksLong();
  //  return SD Card free size 
  // return freeBlocks * blockSize; // unit Byte
  // return (freeBlocks * blockSize)/1024; // unit KB
  return (freeBlocks * blockSize) / 1024 / 1024; //  unit MB
}

3. Get all space on the SD card


/*  To obtain SD Card all space  */
public long getSDAllSize() {
  //  achieve SD Carven path 
  File path = Environment.getExternalStorageDirectory();
  StatFs sf = new StatFs(path.getPath());
  //  Gets the size of a single block of data (Byte)
  long blockSize = sf.getBlockSizeLong();
  //  Gets the total number of data blocks 
  long allBlocks = sf.getBlockCountLong();
  //  return SD The card size 
  // return allBlocks * blockSize; // unit Byte
  // return (allBlocks * blockSize)/1024; // unit KB
  return (allBlocks * blockSize) / 1024 / 1024; //  unit MB
}

I hope this article has been helpful in Android programming.


Related articles: