main

square/leakcanary

Last updated at: 29/12/2023 09:38

MinimumMemoryInterceptor.kt

TLDR

The provided file MinimumMemoryInterceptor.kt is a Kotlin class in the leakcanary package. It implements the HeapAnalysisInterceptor interface. This class is responsible for intercepting Heap Analysis Jobs and determining if they should be cancelled based on the available memory of the device.

Methods

None

Classes

MinimumMemoryInterceptor

This class is a part of the LeakCanary library. It implements the HeapAnalysisInterceptor interface. The purpose of this class is to intercept Heap Analysis Jobs and check the available memory of the device. If the available memory is below a certain threshold or if the device is a low memory device, the corresponding job is cancelled.

package leakcanary

import android.app.Application
import leakcanary.HeapAnalysisInterceptor.Chain
import leakcanary.ProcessInfo.AvailableRam.BelowThreshold
import leakcanary.ProcessInfo.AvailableRam.LowRamDevice
import leakcanary.ProcessInfo.AvailableRam.Memory

class MinimumMemoryInterceptor(
  private val application: Application,
  private val minimumRequiredAvailableMemoryBytes: Long = 100_000_000,
  private val processInfo: ProcessInfo = ProcessInfo.Real
) : HeapAnalysisInterceptor {

  override fun intercept(chain: Chain): HeapAnalysisJob.Result {
    when (val memory = processInfo.availableRam(application)) {
      LowRamDevice -> {
        chain.job.cancel("low ram device")
      }
      BelowThreshold -> {
        chain.job.cancel("low memory")
      }
      is Memory -> {
        if (memory.bytes < minimumRequiredAvailableMemoryBytes) {
          chain.job.cancel(
            "not enough free memory: available ${memory.bytes} < min $minimumRequiredAvailableMemoryBytes"
          )
        }
      }
    }

    return chain.proceed()
  }
}