Untitled

mail@pastecode.io avatar
unknown
kotlin
3 years ago
1.3 kB
1
Indexable
Never
package com.korewireless.gatewayapp.utils

import android.content.Context
import android.content.Intent
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.TimeUnit
import kotlin.math.round

class MemoryCheckerUtil(private val context: Context, thresholdMemory: Int) {
    init {
        val timer = Timer()
        timer.schedule(object: TimerTask() {
            override fun run() {
                if (getPercentageOfUsedMemory() >= thresholdMemory) {
                    val intent = Intent(MEMORY_THRESHOLD_REACHED)
                    LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
                }
            }
        }, 2000L, PERIOD)
    }
    private fun getPercentageOfUsedMemory(): Int {
        val availableMemory = MemoryUtil.getAvailableInternalMemoryInMegaBytes()
        val totalMemory = MemoryUtil.getTotalInternalMemoryInMegaBytes()
        val usedMemory = totalMemory - availableMemory
        return round(usedMemory * 1.0 / totalMemory * 100).toInt()
    }
    companion object {
        const val MEMORY_THRESHOLD_REACHED = "reached_threshold"
        val PERIOD = TimeUnit.MILLISECONDS.convert(1L, TimeUnit.HOURS)
    }
}