Android get free size of internal/external memory

前端 未结 13 1005
眼角桃花
眼角桃花 2020-11-22 15:20

I want to get the size of free memory on internal/external storage of my device programmatically. I\'m using this piece of code :

StatFs stat = new StatFs(En         


        
相关标签:
13条回答
  • 2020-11-22 15:25
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void showStorageVolumes() {
        StorageStatsManager storageStatsManager = (StorageStatsManager) getSystemService(Context.STORAGE_STATS_SERVICE);
        StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        if (storageManager == null || storageStatsManager == null) {
            return;
        }
        List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
        for (StorageVolume storageVolume : storageVolumes) {
            final String uuidStr = storageVolume.getUuid();
            final UUID uuid = uuidStr == null ? StorageManager.UUID_DEFAULT : UUID.fromString(uuidStr);
            try {
                Log.d("AppLog", "storage:" + uuid + " : " + storageVolume.getDescription(this) + " : " + storageVolume.getState());
                Log.d("AppLog", "getFreeBytes:" + Formatter.formatShortFileSize(this, storageStatsManager.getFreeBytes(uuid)));
                Log.d("AppLog", "getTotalBytes:" + Formatter.formatShortFileSize(this, storageStatsManager.getTotalBytes(uuid)));
            } catch (Exception e) {
                // IGNORED
            }
        }
    }
    

    StorageStatsManager class introduced Android O and above which can give you free and total byte in external/internal storage. For detailed with source code, you can read my following article. you can use reflection for lower than Android O

    https://medium.com/cashify-engineering/how-to-get-storage-stats-in-android-o-api-26-4b92eca6805b

    0 讨论(0)
  • 2020-11-22 15:27

    Since API 9 you can do:

    long freeBytesInternal = new File(ctx.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
    long freeBytesExternal = new File(getExternalFilesDir(null).toString()).getFreeSpace();
    
    0 讨论(0)
  • 2020-11-22 15:28

    Try this simple snippet

        public static String readableFileSize() {
        long availableSpace = -1L;
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
            availableSpace = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
        else
            availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
    
        if(availableSpace <= 0) return "0";
        final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(availableSpace)/Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(availableSpace/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
    
    0 讨论(0)
  • 2020-11-22 15:32

    After checking different solution write code myself this is complete code for finding

    • Total External Memory
    • Free External Memory
    • Used External Memory
    • TotaL Internal Memory
    • Used Internal Memory
    • Free Internal Memory

    ''''

    object DeviceMemoryUtil {
    private const val error: String = "Something went wrog"
    private const val noExternalMemoryDetected = "No external Storage detected"
    private var totalExternalMemory: Long = 0
    private var freeExternalMemory: Long = 0
    private var totalInternalStorage: Long = 0
    private var freeInternalStorage: Long = 0
    
    /**
     * Checks weather external memory is available or not
     */
    private fun externalMemoryAvailable(): Boolean {
        return Environment.getExternalStorageState() ==
                Environment.MEDIA_MOUNTED
    }
    
    /**
     *Gives total external memory
     * @return String Size of external memory
     * @return Boolean True if memory size is returned
     */
    fun getTotalExternalMemorySize(): Pair<String?, Boolean> {
        val dirs: Array<File> = ContextCompat.getExternalFilesDirs(CanonApplication.getCanonAppInstance(), null)
        return if (externalMemoryAvailable()) {
            if (dirs.size > 1) {
                val stat = StatFs(dirs[1].path)
                val blockSize = stat.blockSizeLong
                val totalBlocks = stat.blockCountLong
                var totalExternalSize = totalBlocks * blockSize
                totalExternalMemory = totalExternalSize
                Pair(formatSize(totalExternalSize), true)
            } else {
                Pair(error, false)
            }
        } else {
            Pair(noExternalMemoryDetected, false)
        }
    }
    
    /**
     * Gives free external memory size
     * @return String Size of free external memory
     * @return Boolean True if memory size is returned
     */
    fun getAvailableExternalMemorySize(): Pair<String?, Boolean> {
        val dirs: Array<File> = ContextCompat.getExternalFilesDirs(CanonApplication.getCanonAppInstance(), null)
        if (externalMemoryAvailable()) {
            return if (dirs.size > 1) {
                val stat = StatFs(dirs[1].path)
                val blockSize = stat.blockSizeLong
                val availableBlocks = stat.availableBlocksLong
                var freeExternalSize = blockSize * availableBlocks
                freeExternalMemory = freeExternalSize
                Pair(formatSize(freeExternalSize), true)
            } else {
                Pair(error, false)
            }
        } else {
            return Pair(noExternalMemoryDetected, false)
        }
    }
    
    /**
     * Gives used external memory size
     *  @return String Size of used external memory
     * @return Boolean True if memory size is returned
     */
    fun getUsedExternalMemorySize(): Pair<String?, Boolean> {
        return if (externalMemoryAvailable()) {
            val totalExternalSize = getTotalExternalMemorySize()
            val freeExternalSize = getAvailableExternalMemorySize()
            if (totalExternalSize.second && freeExternalSize.second) {
                var usedExternalVolume = totalExternalMemory - freeExternalMemory
                Pair(formatSize(usedExternalVolume), true)
            } else {
                Pair(error, false)
            }
        } else {
            Pair(noExternalMemoryDetected, false)
        }
    }
    
    /**
     *Formats the long to size of memory in gb,mb etc.
     * @param size Size of memory
     */
    fun formatSize(size: Long): String? {
        return android.text.format.Formatter.formatFileSize(CanonApplication.getCanonAppInstance(), size)
    }
    
    /**
     * Gives total internal memory size
     *  @return String Size of total internal memory
     * @return Boolean True if memory size is returned
     */
    fun getTotalInternalStorage(): Pair<String?, Boolean> {
        if (showStorageVolumes()) {
            return Pair(formatSize(totalInternalStorage), true)
        } else {
            return Pair(error, false)
        }
    
    }
    
    /**
     * Gives free or available internal memory size
     *  @return String Size of free internal memory
     * @return Boolean True if memory size is returned
     */
    fun getFreeInternalStorageVolume(): Pair<String?, Boolean> {
        return if (showStorageVolumes()) {
            Pair(formatSize(freeInternalStorage), true)
        } else {
            Pair(error, false)
        }
    }
    
    /**
     *For calculation of internal storage
     */
    private fun showStorageVolumes(): Boolean {
        val storageManager = CanonApplication.canonApplicationInstance.applicationContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager
        val storageStatsManager = CanonApplication.canonApplicationInstance.applicationContext.getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager
        if (storageManager == null || storageStatsManager == null) {
            return false
        }
        val storageVolumes: List<StorageVolume> = storageManager.storageVolumes
        for (storageVolume in storageVolumes) {
            var uuidStr: String? = null
            storageVolume.uuid?.let {
                uuidStr = it
            }
            val uuid: UUID = if (uuidStr == null) StorageManager.UUID_DEFAULT else UUID.fromString(uuidStr)
            return try {
                freeInternalStorage = storageStatsManager.getFreeBytes(uuid)
                totalInternalStorage = storageStatsManager.getTotalBytes(uuid)
                true
            } catch (e: Exception) {
                // IGNORED
                false
            }
        }
        return false
    }
    
    fun getTotalInternalExternalMemory(): Pair<Long?, Boolean> {
        if (externalMemoryAvailable()) {
            if (getTotalExternalMemorySize().second) {
                if (getTotalInternalStorage().second) {
                    return Pair(totalExternalMemory + totalInternalStorage, true)
                } else {
                    return Pair(0, false)
                }
            }
            return Pair(0, false)
        } else {
            if (getTotalInternalStorage().second) {
                return Pair(totalInternalStorage, true)
            } else {
                return Pair(0, false)
            }
        }
    
    }
    
    fun getTotalFreeStorage(): Pair<Long,Boolean> {
        if (externalMemoryAvailable()){
            if(getFreeInternalStorageVolume().second){
                getFreeInternalStorageVolume()
                getAvailableExternalMemorySize()
                    return Pair(freeExternalMemory + freeInternalStorage,true)
            }
            else{
                return Pair(0,false)
            }
        }
        else {
            if (getFreeInternalStorageVolume().second){
                getFreeInternalStorageVolume()
                return Pair(freeInternalStorage,true)
            }
          else{
                return Pair(0,false)
            }
        }
    
    }}
    
    0 讨论(0)
  • 2020-11-22 15:33

    None of the solutions mentioned here can be used for External Memory. Here is my code(for RAM, ROM, System Storage and External Storage). You can calculate free storage by using (total storage - used storage). And also, one must not use Environment.getExternalStorageDirectory() for external storage. It does not necessarily points to External SD Card. Also, this solution will work with all the Android versions (tested for API 16-30 on real devices and emulators).

        // Divide by (1024*1024*1024) to get in GB, by (1024*1024) to get in MB, by 1024 to get in KB..
    
        // RAM
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(memoryInfo);
        long totalRAM=memoryInfo.totalMem;
        long availRAM=memoryInfo.availMem;  // remember to convert in GB,MB or KB.
        long usedRAM=totalRAM-availRAM;
    
        // ROM
        getTotalStorageInfo(Environment.getDataDirectory().getPath());
        getUsedStorageInfo(Environment.getDataDirectory().getPath());
    
        // System Storage
        getTotalStorageInfo(Environment.getRootDirectory().getPath());
        getUsedStorageInfo(Environment.getRootDirectory().getPath());
    
        // External Storage (SD Card)
        File[] files = ContextCompat.getExternalFilesDirs(context, null);
        if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.JELLY_BEAN_MR2){
            if (files.length == 1) {
                Log.d("External Storage Memory","is present");
                getTotalStorageInfo(files[0].getPath());
                getUsedStorageInfo(files[0].getPath());
            }
        } else {
            if (files.length > 1 && files[0] != null && files[1] != null) {
                Log.d("External Storage Memory","is present");
                long t=getTotalStorageInfo(files[1].getPath());
                long u=getUsedStorageInfo(files[1].getPath());
                System.out.println("Total External Mem: "+t+" Used External Mem: "+u+" Storage path: "+files[1].getPath());
            }
        }
    }
    
    public long getTotalStorageInfo(String path) {
        StatFs statFs = new StatFs(path);
        long t;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            t = statFs.getTotalBytes();
        } else {
            t = statFs.getBlockCount() * statFs.getBlockCount();
        }
        return t;    // remember to convert in GB,MB or KB.
    }
    
    public long getUsedStorageInfo(String path) {
        StatFs statFs = new StatFs(path);
        long u;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            u = statFs.getTotalBytes() - statFs.getAvailableBytes();
        } else {
            u = statFs.getBlockCount() * statFs.getBlockSize() - statFs.getAvailableBlocks() * statFs.getBlockSize();
        }
        return u;  // remember to convert in GB,MB or KB.
    }
    

    Now here for ROM I have used path as "/data" and for System Storage path is "/system". And for External Storage I have used ContextCompat.getExternalFilesDirs(context, null); therefore it will work on Android Q and Android R also. I hope, this will help you.

    0 讨论(0)
  • 2020-11-22 15:36

    Below is the code for your purpose :

    public static boolean externalMemoryAvailable() {
            return android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED);
        }
    
        public static String getAvailableInternalMemorySize() {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSizeLong();
            long availableBlocks = stat.getAvailableBlocksLong();
            return formatSize(availableBlocks * blockSize);
        }
    
        public static String getTotalInternalMemorySize() {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSizeLong();
            long totalBlocks = stat.getBlockCountLong();
            return formatSize(totalBlocks * blockSize);
        }
    
        public static String getAvailableExternalMemorySize() {
            if (externalMemoryAvailable()) {
                File path = Environment.getExternalStorageDirectory();
                StatFs stat = new StatFs(path.getPath());
                long blockSize = stat.getBlockSizeLong();
                long availableBlocks = stat.getAvailableBlocksLong();
                return formatSize(availableBlocks * blockSize);
            } else {
                return ERROR;
            }
        }
    
        public static String getTotalExternalMemorySize() {
            if (externalMemoryAvailable()) {
                File path = Environment.getExternalStorageDirectory();
                StatFs stat = new StatFs(path.getPath());
                long blockSize = stat.getBlockSizeLong();
                long totalBlocks = stat.getBlockCountLong();
                return formatSize(totalBlocks * blockSize);
            } else {
                return ERROR;
            }
        }
    
        public static String formatSize(long size) {
            String suffix = null;
    
            if (size >= 1024) {
                suffix = "KB";
                size /= 1024;
                if (size >= 1024) {
                    suffix = "MB";
                    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();
        }
    

    Get RAM Size

    ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    MemoryInfo memInfo = new ActivityManager.MemoryInfo();
    actManager.getMemoryInfo(memInfo);
    long totalMemory = memInfo.totalMem;
    
    0 讨论(0)
提交回复
热议问题