Android get free size of internal/external memory

前端 未结 13 1150
眼角桃花
眼角桃花 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: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 {
        val dirs: Array = 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 {
        val dirs: Array = 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 {
        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 {
        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 {
        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 = 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 {
        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 {
        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)
            }
        }
    
    }}
    

提交回复
热议问题