获得手机内存空间状态

示例



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);

        //获取sd卡内存状态
        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) {
        // 得到路径
        // File path =Environment.getExternalStorageDirectory();

        // 获得一个 磁盘状态 对象
        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;
    }
}
posted @ 2015-03-30 10:35  rysinal  阅读(137)  评论(0编辑  收藏  举报