获取手机存储设备的空间使用情况
Environment: 获取系统中的存储设备信息
getExternalStorageDirectory(): 获取外部存储设备及SD卡文件对象。
getRootDirectory(): 获取系统空间文件对象。
getBlockCount(): 获取存储块数量。
getAvailableBlocks(): 获取存储块数量。
getBlockSize(): 获取存储块大小。
因为Android是基于Linux系统的,所以其没有盘符的概念,而且是以存储块来存储数据。所以获得容量的正确方式为:
1. 通过Environment获取需要检测容量的文件对象。
2. 构建StatFs对象。
3. 获取存储块数量。
4. 获取存储块大小。
5. 计算得出容量大小。
通过getBlockSize()方法获取出来的值,是以字节做单位。
下面是代码:
package Getystem_file_info.demo;
import java.io.File;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv1,tv2,tv3,tv4;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findVeiw();
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File externalStoragePath = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(externalStoragePath.getPath());
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getBlockCount();
int availableBlocks = statFs.getAvailableBlocks();
int freeBlocks = statFs.getFreeBlocks();
String[] blockSizes = sizeFormat(blockCount*blockSize);
String[] availableSize = sizeFormat(availableBlocks*blockSize);
String[] freebleSize = sizeFormat(freeBlocks*blockSize);
tv1.setText("外储设备总大小:"+ blockSizes[0] + blockSizes[1] );
tv2.setText("外储设备可用大小:"+ availableSize[0] + availableSize[1] );
tv3.setText("外储设备freeBlocks大小:"+ freebleSize[0] + freebleSize[1] );
}
}
private void findVeiw() {
tv1 = (TextView) this.findViewById(R.id.textview1);
tv2 = (TextView) this.findViewById(R.id.textview2);
tv3 = (TextView) this.findViewById(R.id.textview3);
}
String[] sizeFormat(long size) {
String str = "B";
if(size >= 1024) {
str = "KB";
size /= 1024;
if(size >= 1024) {
str = "MB";
size /= 1024;
}
}
DecimalFormat format = new DecimalFormat();
format.setGroupingSize(3);
String[] result = new String[2];
result[0] = format.format(size);
result[1] = str;
return result;
}
}