2.Android进阶:获取设备可用空间

用到的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);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值