获取内存状态
问题:在安卓应用下,要想知道手机中SD卡,自带内存卡中的存储情况,该如何做?
[StatFs对象] 内存状态对象:
传一个路径参数,这个对象可以用一些方法帮你获得获得扇区个数,扇区大小。
实例代码:获取内存状态信息
package com.buluo.memorydemo;
import java.io.File;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.app.Activity;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_title = (TextView) findViewById(R.id.tv_title);
// 获取sd卡的内存状态
File storageDirectory = Environment.getExternalStorageDirectory(); //得到拓展内存目录,返回一个File
String sdCardmemory = getMemoryInfo(storageDirectory);
// 获取手机内部存储空间的状态
File dataDirectory = Environment.getDataDirectory();
String dataMemory = getMemoryInfo(dataDirectory);
tv_title.setText("SD卡 "+sdCardmemory+";内存卡"+dataMemory);
}
private String getMemoryInfo(File path) {
// 获得一个磁盘状态对象
StatFs stat = new StatFs(path.getPath());
int totalCount = stat.getBlockCount(); // 获取扇区总数
int blockSize = stat.getBlockSize(); // 获得一个扇区大小
int availableCount = stat.getAvailableBlocks(); // 获取可用扇区数
// 总空间
String totalMemory = Formatter.formatFileSize(this, totalCount * blockSize );
// 可用空间
String availableMenoty = Formatter.formatFileSize(this, availableCount * blockSize );
return "总空间:"+totalMemory +",可用空间"+availableMenoty;
}
}