As an extended storage device for mobile phones, SD cards act as hard disks on mobile phones, allowing our mobile phones to store more data, multimedia files, and other large files. Therefore, checking the memory of the SD card is the same as checking the remaining space on the hard disk. It is a common task. How can we obtain the memory capacity of the SD card during Android development?
First, you must have the permission to access the SD card before obtaining the information on the SD card. Therefore, you must add the permission to access the extended device.
<Uses-permission
Android: name = "android. permission. WRITE_EXTERNAL_STORAGE">
</Uses-permission>
Second, you need to determine whether the SD card is inserted on your phone. If an SD card exists, we can access and obtain the relevant information, of course, the following statements need to be judged using if.
Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED)
Get sdcard file path
File path = Environment. getExternalStorageDirectory ();
StatFs statfs = new StatFs (path. getPath ());
Obtain the block SIZE.
Long blocSize = statfs. getBlockSize ();
Obtain the number of blocks
Long totalBlocks = statfs. getBlockCount ();
Number of idle Blocks
Long availablock = statfs. getavailableblocks ();
Calculate the total space and free space
The size of the bucket and the size of the idle bucket are calculated.
Public long getavailalesize (){
File Path = environment. getexternalstoragedirectory (); // get the path of the sdcard File
Statfs stat = new statfs (path. getpath ());
Long blocksize = Stat. getblocksize ();
Long availableblocks = Stat. getavailableblocks ();
Return availableblocks * blocksize;
// (Availableblocks * blocksize)/1024 kib Unit
// (Availableblocks * blocksize)/1024/1024 MIB
}
Public long getallsize (){
File Path = environment. getexternalstoragedirectory ();
Statfs stat = new statfs (path. getpath ());
Long blocksize = Stat. getblocksize ();
Long availableblocks = Stat. getblockcount ();
Return availableblocks * blocksize;
}