概述
/*
* 取得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,在这里就不再详述了。
下面我们就来看看程序运行后的结果:
![](https://file2.kaopuke.com:8081/files_image/2023110823/1342258230_9007.png)
最后
以上就是英勇秋天为你收集整理的取得SD卡的剩余容量的全部内容,希望文章能够帮你解决取得SD卡的剩余容量所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复