当前位置: 代码迷 >> Android >> Android 惯用的SDCARD和内存操作
  详细解决方案

Android 惯用的SDCARD和内存操作

热度:22   发布时间:2016-05-01 12:00:00.0
Android 常用的SDCARD和内存操作
public class MemoryStatus {    static final int ERROR = -1;    /**     * 外部存储是否可用     * @return     */    static public boolean externalMemoryAvailable() {        return android.os.Environment.getExternalStorageState().equals(                android.os.Environment.MEDIA_MOUNTED);    }    /**     * 获取手机内部可用空间大小     * @return     */    static public long getAvailableInternalMemorySize() {        File path = Environment.getDataDirectory();        StatFs stat = new StatFs(path.getPath());        long blockSize = stat.getBlockSize();        long availableBlocks = stat.getAvailableBlocks();        return availableBlocks * blockSize;    }    /**     * 获取手机内部空间大小     * @return     */    static public long getTotalInternalMemorySize() {        File path = Environment.getDataDirectory();        StatFs stat = new StatFs(path.getPath());        long blockSize = stat.getBlockSize();        long totalBlocks = stat.getBlockCount();        return totalBlocks * blockSize;    }    /**     * 获取手机外部可用空间大小     * @return     */    static public long getAvailableExternalMemorySize() {        if (externalMemoryAvailable()) {            File path = Environment.getExternalStorageDirectory();            StatFs stat = new StatFs(path.getPath());            long blockSize = stat.getBlockSize();            long availableBlocks = stat.getAvailableBlocks();            return availableBlocks * blockSize;        } else {            return ERROR;        }    }    /**     * 获取手机外部空间大小     * @return     */    static public long getTotalExternalMemorySize() {        if (externalMemoryAvailable()) {            File path = Environment.getExternalStorageDirectory();            StatFs stat = new StatFs(path.getPath());            long blockSize = stat.getBlockSize();            long totalBlocks = stat.getBlockCount();            return totalBlocks * blockSize;        } else {            return ERROR;        }    }    static public String formatSize(long size) {        String suffix = null;        if (size >= 1024) {            suffix = "KiB";            size /= 1024;            if (size >= 1024) {                suffix = "MiB";                size /= 1024;            }        }        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));        int commaOffset = resultBuffer.length() - 3;        while (commaOffset > 0) {            resultBuffer.insert(commaOffset, ',');            commaOffset -= 3;        }        if (suffix != null)            resultBuffer.append(suffix);        return resultBuffer.toString();    }}

?

?来源网络

?

?

  相关解决方案