public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvMemoryInfo = (TextView) findViewById(R.id.tv_memory_info);
File sdCardFileDir = Environment.getExternalStorageDirectory();
String sdcardMemory = getMemoryInfo(sdCardFileDir);
File dataFileDir = Environment.getDataDirectory();
String dataMemory = getMemoryInfo(dataFileDir);
tvMemoryInfo.setText("sd卡" + sdcardMemory + "\n手机内部"+dataMemory);
}
/**
* 根据路径获取内存状态
* @param path
* @return
*/
private String getMemoryInfo(File path) {
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
String totalMemory = Formatter.formatFileSize(this, totalBlocks * blockSize);
String availableMemory = Formatter.formatFileSize(this, blockSize * availableBlocks);
return "总空间" + totalMemory + "\n可用空间"+availableMemory;
}
}