PS:看了9年的小说,自己开始动手写了一本,请各位猿们动动手指,点击下,有起点账号的可以收藏下!!《武意长存》
在开发中,我们难免会跟手机外部存储或者内部存储打交道,当下载一个文件时,不可避免的就要先判断存储空间是否足够用来下载文件,这时我们就要获取存储空间的情况,代码如下:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvMemoryInfo = (TextView) this.findViewById(R.id.tv_memoryInfo);
tvMemoryInfo.setText("sd卡总空间:"+this.getTotalSDSize()+"\nsd卡可用空间:"+this.getAvailSDSize()+"\n手机rom总空间:"+this.getTotalRomSize()+"\n手机rom可用空间:"+this.getAvailRomSize());
}
/**
* 获取sd卡的总空间
*/
private String getTotalSDSize(){
StatFs stat = getStatFs(0);
long totalBlocks = stat.getBlockCount();
long blockSize = stat.getBlockSize();
long totalSDSize = totalBlocks * blockSize;
return Formatter.formatFileSize(this, totalSDSize);
}
/**
* 获取sd卡的可用空间
*/
private String getAvailSDSize(){
StatFs stat = getStatFs(0);
long availBlocks = stat.getAvailableBlocks();
long blockSize = stat.getBlockSize();
long availSDSize = availBlocks * blockSize;
return Formatter.formatFileSize(this, availSDSize);
}
//mode 0:获取的是sd的状态 1:获取的是手机内部存储rom的状态
private StatFs getStatFs(int mode) {
File path = null;
switch(mode){
case 0 :
path = Environment.getExternalStorageDirectory();
break;
case 1 :
path = Environment.getDataDirectory();
break;
}
StatFs stat = new StatFs(path.getPath());
return stat;
}
/**
* 获取手机内部存储rom的总空间
*/
private String getTotalRomSize(){
StatFs stat = getStatFs(1);
long totalBlocks = stat.getBlockCount();
long blockSize = stat.getBlockSize();
long totalSDSize = totalBlocks * blockSize;
return Formatter.formatFileSize(this, totalSDSize);
}
/**
* 获取手机内部存储rom的可用空间
*/
private String getAvailRomSize(){
StatFs stat = getStatFs(1);
long availBlocks = stat.getAvailableBlocks();
long blockSize = stat.getBlockSize();
long availSDSize = availBlocks * blockSize;
return Formatter.formatFileSize(this, availSDSize);
}