Environment和StatFs查看存储卡剩余容量

public class MobileMemoryActivity extends Activity {

private Button mButton;
private TextView mTextView;
private ProgressBar mProgressBar;



protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.mobile_memory);

mButton = (Button) findViewById(R.id.mobile_memory_Button);
mTextView = (TextView) findViewById(R.id.mobile_memory_TextView);
mProgressBar = (ProgressBar) findViewById(R.id.mobile_memory_ProgressBar);

mButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
showSize();
}

});

}


private void showSize(){
mTextView.setText("");
mProgressBar.setProgress(0);

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

File path = Environment.getExternalStorageDirectory();

StatFs  statFs = new StatFs(path.getPath());
//取得block的size
long blockSize = statFs.getBlockSize();

                           //取得总容量
long tatalBlock = statFs.getBlockCount();

                           //取得可用容量
long availableBlock = statFs.getAvailableBlocks();

String[] total = fileSize(blockSize*tatalBlock);
String[] available = fileSize(blockSize*availableBlock);

                           //计算可用容量所占比例,在进度条上的显示值
int ps = Integer.parseInt(available[0])*mProgressBar.getMax()/Integer.parseInt(total[0]);
mProgressBar.setProgress(ps);

String text = "总共:"+total[0]+" "+ total[1]+"\n"
+"可用:"+available[0]+""+available[1];

mTextView.setText(text);
}


}

private String[] fileSize(long size){

String str = "";
if(size>=1024){
str="kb";
size/=1024;
if(size>=1024){
str="mb";
size/=1024;
}

}

DecimalFormat df = new DecimalFormat();
df.setGroupingSize(3);

String[] ss = new String[2];
ss[0] = df.format(size);
ss[1] = str;

return ss;

}

}

你可能感兴趣的:(mobile)