取得SD卡的剩余容量

来源:互联网 发布:java中什么叫单元测试 编辑:程序博客网 时间:2024/06/03 02:16
/*
 * 取得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. */@Overridepublic 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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubshowSize();}});}private void showSize() {// 将TextView和ProgressBar设置为空置及0myTextView.setText("");myProgressBar.setProgress(0);// 判断存储卡是否存在if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 取得SD卡文件路径File path = Environment.getExternalStorageDirectory();// StatFs看文件系统空间的使用情况StatFs statFs = new StatFs(path.getPath());// Block的sizelong 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 stubString 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,在这里就不再详述了。
下面我们就来看看程序运行后的结果: