用到的API
StatFs类
public int getAvailableBlocks ()
文件系统上可用且可用于应用程序的块的数量
public int getBlockSize ()
文件系统上块的大小(以字节为单位)
1.布局文件
<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 style="@style/TitleStyle" android:text="软件管理" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" > <TextView android:id="@+id/tv_rom_avail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="内部存储:0MB" /> <TextView android:id="@+id/tv_sdcard_avail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="sdcard可用:0MB" /> </RelativeLayout> </LinearLayout>
2.测试类
public class AppManagerActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_manager); // 得到sd卡可用空间 String sdcardSpace = getAvailSpace(Environment .getExternalStorageDirectory().getAbsolutePath()); // 内部存储可用空间(data目录的可用空间) String romSpace = getAvailSpace(Environment.getDataDirectory() .getAbsolutePath()); TextView tvSdcard = (TextView) findViewById(R.id.tv_sdcard_avail); TextView tvRom = (TextView) findViewById(R.id.tv_rom_avail); //设置显示文本内容 tvSdcard.setText("sdcard可用:" + sdcardSpace); tvRom.setText("内部存储可用:" + romSpace); } /** * 获取可用空间 */ private String getAvailSpace(String path) { // 获取可用空间 StatFs stat = new StatFs(path); // 获取可用存储块数量 long availableBlocks = stat.getAvailableBlocks(); // 每个存储块的大小 long blockSize = stat.getBlockSize(); // 可用存储空间 long availSize = availableBlocks * blockSize; // Integer.MAX_VALUE 可以表示2G大小, 2G太少, 需要用Long // 将字节转为带有相应单位(MB, G)的字符串 return Formatter.formatFileSize(this, availSize); } }