查看SDCard的容量情况

 

 

private Button myButton;
	private TextView myTextView;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sd_size);
		
		myButton = (Button) findViewById(R.id.button1);
		myTextView = (TextView) findViewById(R.id.textView1);
		myButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View arg0) {
				showSize();
			}
		});
	}

	private void showSize() {
		/* 将TextView及ProgressBar设定为空值及0 */
		myTextView.setText("");
		/* 判断记忆卡是否插入 */
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			/* 取得SD CARD档案路径一般是/sdcard */
			File path = Environment.getExternalStorageDirectory();
			/* StatFs看文件系统空间使用状况 */
			StatFs statFs = new StatFs(path.getPath());
			/* Block的size */
			long blockSize = statFs.getBlockSize();
			/* 总Block数量 */
			long totalBlocks = statFs.getBlockCount();
			/* 已使用的Block数量 */
			long availableBlocks = statFs.getAvailableBlocks();
			String[] total = fileSize(totalBlocks * blockSize);
			String[] available = fileSize(availableBlocks * blockSize);
			/* getMax取得在main.xml里ProgressBar设定的最大值 */
			String text = "总共" + total[0] + total[1] + "\n";
			text += "可用" + available[0] + available[1];
			myTextView.setText(text);
		} else if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_REMOVED)) {
			String text = "SD CARD已移除";
			myTextView.setText(text);
		}
	}

	/* 回传为字符串数组[0]为大小[1]为单位KB或MB */
	private String[] fileSize(long size) {
		String str = "";
		if (size >= 1024) {
			str = "KB";
			size /= 1024;
			if (size >= 1024) {
				str = "MB";
				size /= 1024;
			}
		}
		DecimalFormat formatter = new DecimalFormat();
		/* 每3个数字用,分隔如:1,000 */
		formatter.setGroupingSize(3);
		String result[] = new String[2];
		result[0] = formatter.format(size);
		result[1] = str;
		return result;
	}
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值