ITeye博客

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

zhangle2612 · 2010-10-26 11:29 · Android · 移动开发 · Markdown

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)*mProgressBar.getMax()/Integer.parseInt(total);
		mProgressBar.setProgress(ps);
		
		String text = "总共:"+total+" "+ total+"\n"
			+"可用:"+available+""+available;
			
	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;
	ss = df.format(size);
	ss = str;
	
	return ss;
	
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。