[monilesafe] 08_软件管理——获取可用内部存储空间和SDcard空间大小

Android 4.0

// a)rom可用
tv_rom_available.setText(getResources().getString(R.string.internal_storage_available)
        +":"+getAvailableStorage(Environment.getDataDirectory().getAbsolutePath()));
// b)sdcard可用
tv_sdcard_available.setText(getResources().getString(R.string.sdcard_storage_available)
        + "" + getAvailableStorage(Environment.getExternalStorageDirectory().getAbsolutePath()));  

核心代码:
package cn.zengfansheng.mobilesafe;
 
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;
 
/**
* 17、软件管理Activity
*
* @author hacket
*/

public class AppManageActivity extends Activity {
 
    private TextView tv_rom_available;//rom可用空间
    private TextView tv_sdcard_available;//sdcard可用空间
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_app_manager);
 
        tv_rom_available = (TextView) this.findViewById(R.id.tv_available_internal_storage);
        tv_sdcard_available = (TextView) this.findViewById(R.id.tv_available_sdcard_storage);
 
        // 获取目录时注意:
        // android 1.5 1.6 2.1 /sdcard
        // android 2.2 ~4.1 /mnt/sdcard
        // android 4.2 /mnt/sdcard01
        // /mnt/storage/sdcard01
 
        // a)rom可用
        tv_rom_available.setText(getResources().getString(R.string.internal_storage_available)
                +":"+getAvailableStorage(Environment.getDataDirectory().getAbsolutePath()));
        // b)sdcard可用
        tv_sdcard_available.setText(getResources().getString(R.string.sdcard_storage_available)
                + "" + getAvailableStorage(Environment.getExternalStorageDirectory().getAbsolutePath()));
    }
 
    /**
     * 1、获取某个目录的大小
     *
     * @param path 要判断的路径
     * @return 返回可用空间
     */

    public String getAvailableStorage(String path) {
        StatFs statFs = new StatFs(path);
        int countSize = statFs.getAvailableBlocks() * statFs.getBlockSize();
        String formatFileSize = Formatter.formatFileSize(this, countSize);
        return formatFileSize;
    }
}

结果: