Android_02 _ Get the available capacity of the SD card
The sample code is as follows:
Package com. itheima. getsdavail; import java. io. file; import android. OS. build; import android. OS. bundle; import android. OS. environment; import android. OS. statFs; import android. app. activity; import android. text. format. formatter; import android. view. menu; import android. widget. textView; public class MainActivity extends Activity {@ SuppressWarnings (deprecation) @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); File path = Environment. getExternalStorageDirectory (); StatFs stat = new StatFs (path. getPath (); long blockSize; long totalBlocks; long availableBlocks; // obtain the level of the current system version if (Build. VERSION. SDK_INT> = Build. VERSION_CODES.JELLY_BEAN_MR2 ){
// Later versions of Android support the following operations: blockSize = stat. getBlockSizeLong (); totalBlocks = stat. getBlockCountLong (); availableBlocks = stat. getAvailableBlocksLong ();}
// Earlier Android versions support the following else {blockSize = stat. getBlockSize (); totalBlocks = stat. getBlockCount (); availableBlocks = stat. getAvailableBlocks ();} TextView TV = (TextView) findViewById (R. id. TV); TV. setText (formatSize (availableBlocks * blockSize);} private String formatSize (long size) {return Formatter. formatFileSize (this, size );}}
Note: You can use the Setting application of the source code to view how the app gets the remaining space of the SD card, so that we can get the remaining capacity of the SD card through reference.