在开发过程中有时候会获取手机的SD存储使用状况。
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/memory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
实现类
package com.example.phonememorystate;
import java.io.File;
import java.text.Format;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView memoryInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
memoryInfo = (TextView) findViewById(R.id.memory);
//外部存储的地址
File SDPath = Environment.getExternalStorageDirectory();
String SDMemory = getMemoryInfo(SDPath);
//手机内部存储的地址
File PhonePath = Environment.getDataDirectory();
String PhoneMemory = getMemoryInfo(PhonePath);
memoryInfo.setText("SD卡:" + SDMemory + "\n手机内存:" + PhoneMemory);
}
private String getMemoryInfo(File path){
//获取一个磁盘的状态对象
StatFs stat = new StatFs(path.getPath());
//获得一个扇区的大小
long blockSizes = stat.getBlockSize();
//获取扇区总数
long totalBlocks = stat.getBlockCount();
//获得可用扇区数量
long availableBlocks = stat.getAvailableBlocks();
//获得总空间
String totalMemory = Formatter.formatFileSize(this, blockSizes * totalBlocks);
//获得可用空间
String availableMemory = Formatter.formatFileSize(this, availableBlocks * blockSizes);
return "总空间:" + totalMemory + "\n可用空间" + availableMemory;
}
}