main

square/leakcanary

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

ReleaseExampleApplication.kt

TLDR

This file contains the ReleaseExampleApplication class which extends the ExampleApplication class. It initializes and configures the HeapAnalysisClient and sets up triggers for background and screen off heap analysis.

Classes

ReleaseExampleApplication

This class extends the ExampleApplication and overrides the onCreate method. In the onCreate method, it performs the following tasks:

  • Installs the LogcatSharkLog for debugging purposes in release builds.
  • Creates an instance of HeapAnalysisClient.
  • Creates a single-threaded executor for running heap analysis tasks.
  • Deletes any existing heap dump files.
  • Sets up a callback function for receiving analysis results.
  • Starts the BackgroundTrigger and ScreenOffTrigger for initiating heap analysis.
package com.example.leakcanary

import android.os.Process.THREAD_PRIORITY_BACKGROUND
import android.util.Log
import leakcanary.BackgroundTrigger
import leakcanary.HeapAnalysisClient
import leakcanary.HeapAnalysisConfig
import leakcanary.HeapAnalysisJob.Result
import leakcanary.LogcatSharkLog
import leakcanary.LogcatSharkLog.Companion
import leakcanary.ScreenOffTrigger
import shark.SharkLog
import shark.SharkLog.Logger
import java.util.concurrent.Executors
import kotlin.concurrent.thread

class ReleaseExampleApplication : ExampleApplication() {

  override fun onCreate() {
    super.onCreate()
    // Useful to debug in release builds. Don't use in real builds.
    LogcatSharkLog.install()

    val analysisClient = HeapAnalysisClient(
      heapDumpDirectoryProvider = { cacheDir },
      config = HeapAnalysisConfig(),
      interceptors = HeapAnalysisClient.defaultInterceptors(this)
    )

    val analysisExecutor = Executors.newSingleThreadExecutor {
      thread(start = false, name = "Heap analysis executor") {
        android.os.Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND)
        it.run()
      }
    }
    analysisExecutor.execute {
      analysisClient.deleteHeapDumpFiles()
    }
    val analysisCallback: (Result) -> Unit = { result ->
      SharkLog.d { "$result" }
    }
    BackgroundTrigger(
      application = this,
      analysisClient = analysisClient,
      analysisExecutor = analysisExecutor,
      analysisCallback = analysisCallback
    ).start()

    ScreenOffTrigger(
      application = this,
      analysisClient = analysisClient,
      analysisExecutor = analysisExecutor,
      analysisCallback = analysisCallback
    ).start()
  }
}