开发者

Internal phone storage in Android

开发者 https://www.devze.com 2022-12-27 16:40 出处:网络
How can you retr开发者_StackOverflowieve your phone internal storage from an app?I found MemoryInfo, but it seems that returns information on how much memory use your currently running tasks.

How can you retr开发者_StackOverflowieve your phone internal storage from an app? I found MemoryInfo, but it seems that returns information on how much memory use your currently running tasks.

I am trying to get my app to retrieve how much internal phone storage is available.


Use android.os.Environment to find the internal directory, then use android.os.StatFs to call the Unix statfs system call on it. Shamelessly stolen from the Android settings app:

File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(this, availableBlocks * blockSize);


I had a hard time having mine works. So I would like to share my working code to save some guys some time.
Tested on a 32GB device and 1GB device.

// Return size is in Megabytes
public class DeviceMemory {

        public static long getInternalStorageSpace()
        {
            StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            //StatFs statFs = new StatFs("/data");
            long total = ((long)statFs.getBlockCount() * (long)statFs.getBlockSize()) / 1048576;
            return total;
        }

        public static long getInternalFreeSpace()
        {
            StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            //StatFs statFs = new StatFs("/data");
            long free  = ((long)statFs.getAvailableBlocks() * (long)statFs.getBlockSize()) / 1048576;
            return free;
        }

        public static long getInternalUsedSpace()
        {
            StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            //StatFs statFs = new StatFs("/data");
            long total = ((long)statFs.getBlockCount() * (long)statFs.getBlockSize()) / 1048576;
            long free  = ((long)statFs.getAvailableBlocks() * (long)statFs.getBlockSize()) / 1048576;
            long busy  = total - free;
            return busy;
        }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号