Get Internal and External Memory size in MarshMallow

南楼画角 提交于 2019-12-12 03:05:21

问题


I am trying to show the size of Internal and External(SD card) memory in my application.My code is working fine for kitkat and below api versions but My app is crashing in Marshmallow or lollipop .Here is my code ...

 public static long getAvailableInternalMemorySize() 

{
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    public static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    public static long getAvailableExternalMemorySize() {


        String secStore = System.getenv("SECONDARY_STORAGE");
        File path = new File(secStore);
        StatFs stat = new StatFs(path.getPath());

        long blockSize = stat.getBlockSize();

        long availableBlocks = stat.getAvailableBlocks();

        long total = availableBlocks * blockSize;

        return total;
    }


    public static long getTotalExternalMemorySize() {

        String secStore = System.getenv("SECONDARY_STORAGE");
        File path = new File(secStore);
        StatFs stat = new StatFs(path.getPath());

        long blockSize = stat.getBlockSize();

        long availableBlocks = stat.getBlockCount();

        long total = availableBlocks * blockSize;


        return total;

    }

Can you tell me the solution to get the memory sizes in above api versions...?


回答1:


In lolipop or marshmallo you must use
Environment.getExternalStorageDirectory().getAbsolutePath();

to get external storage path instead of System.getenv("SECONDARY_STORAGE");

Refer beolw code for get external and internal storage in >android 5.0

public static String getTotalInternalMemorySize() {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return formatSize(totalBlocks * blockSize);
        }

        public static String getAvailableExternalMemorySize() {
                File path = Environment.getExternalStorageDirectory();
                StatFs stat = new StatFs(path.getPath());
                long blockSize = stat.getBlockSize();
                long availableBlocks = stat.getAvailableBlocks();
                return formatSize(availableBlocks * blockSize);
            }   


来源:https://stackoverflow.com/questions/40258998/get-internal-and-external-memory-size-in-marshmallow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!