* 存储设备会被分为若干个区块
* 每个区块的大小 * 区块总数 = 存储设备的总大小
* 每个区块的大小 * 可用区块的数量 = 存储设备可用大小
相关代码如下:
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
protected 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;
//判断当前版本是否是4.3或以上
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
blockSize = stat.getBlockSizeLong();
totalBlocks = stat.getBlockCountLong();
availableBlocks = stat.getAvailableBlocksLong();
}
else{
blockSize = stat.getBlockSize();
totalBlocks = stat.getBlockCount();
availableBlocks = stat.getAvailableBlocks();
}
String text = formatSize(availableBlocks * blockSize);
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(text);
}
private String formatSize(long size) {
return Formatter.formatFileSize(this, size);
}
}