取得SD卡的剩余容量

/*
 * 取得SD卡的剩余容量
 * 存储卡在插拔的时候会对系统进行ACTION broadcast。程序将通过StatFs
 * 文件系统的方法来取得MicroSD卡的剩余容量。首先要通过
 * Environment.getExternalStorageState()方法来判断存储卡是否存在。
 */
import 略;
public class Ex06_08Activity extends Activity {
	private Button myButton;
	private ProgressBar myProgressBar;
	private TextView myTextView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		myButton = (Button) findViewById(R.id.myButton);
		myTextView = (TextView) findViewById(R.id.myTextView);
		myProgressBar = (ProgressBar) findViewById(R.id.myProgressBar);
		myButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showSize();
			}
		});
	}

	private void showSize() {
		// 将TextView和ProgressBar设置为空置及0
		myTextView.setText("");
		myProgressBar.setProgress(0);
		// 判断存储卡是否存在
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// 取得SD卡文件路径
			File path = Environment.getExternalStorageDirectory();
			// StatFs看文件系统空间的使用情况
			StatFs statFs = new StatFs(path.getPath());
			// Block的size
			long blockSize = statFs.getBlockSize();
			// 总的Block数量
			long totalBlocks = statFs.getBlockCount();
			// 已使用的Block数
			long availableBlock = statFs.getAvailableBlocks();
			String total[] = fileSize(totalBlocks * blockSize);
			String available[] = fileSize(availableBlock * blockSize);
			// getMax取得在main.xml里ProgressBar设置的最大值
			int ss = Integer.parseInt(available[0]) * myProgressBar.getMax()
					/ Integer.parseInt(total[0]);
			myProgressBar.setProgress(ss);
			String text = "总共" + total[0] + total[1] + "\n";
			text += "可用" + available[0] + available[1];
			myTextView.setText(text);
		} else {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_REMOVED)) {
				AlertDialog d = new AlertDialog.Builder(Ex06_08Activity.this)
						.create();
				d.setTitle("提示");
				d.setMessage("SD卡不存在!");
				d.show();
			}
		}
	}

	private String[] fileSize(long size) {
		// TODO Auto-generated method stub
		String str = "";
		if (size >= 1024) {
			str = "KB";
			size = size / 1024;
			if (size > 1024) {
				str = "MB";
				size = size / 1024;
				if (size > 1024) {
					str = "GB";
					size = size / 1024;
				}
			}
		}
		String[] result = new String[2];
		result[0] = String.valueOf(size);
		result[1] = str;
		return result;
	}

布局文件很简单,只是有一个TextView、Button和ProgressBar,在这里就不再详述了。
下面我们就来看看程序运行后的结果:
取得SD卡的剩余容量_第1张图片

你可能感兴趣的:(String,存储,Class,action,Path,button)