<lambda>null1 package leakcanary
2 
3 import android.app.Application
4 import leakcanary.internal.BackgroundListener
5 import leakcanary.internal.friendly.checkMainThread
6 import shark.SharkLog
7 import java.util.concurrent.Executor
8 
9 class BackgroundTrigger(
10   private val application: Application,
11   private val analysisClient: HeapAnalysisClient,
12   /**
13    * The executor on which the analysis is performed and on which [analysisCallback] is called.
14    * This should likely be a single thread executor with a background thread priority.
15    */
16   private val analysisExecutor: Executor,
17 
18   processInfo: ProcessInfo = ProcessInfo.Real,
19 
20   /**
21    * Called back with a [HeapAnalysisJob.Result] after the app has entered background and a
22    * heap analysis was attempted. This is called on the same thread that the analysis was
23    * performed on.
24    *
25    * Defaults to logging to [SharkLog] (don't forget to set [SharkLog.logger] if you do want to see
26    * logs).
27    */
28   private val analysisCallback: (HeapAnalysisJob.Result) -> Unit = { result ->
29     SharkLog.d { "$result" }
30   },
31 ) {
32 
33   @Volatile
34   private var currentJob: HeapAnalysisJob? = null
35 
appInBackgroundNownull36   private val backgroundListener = BackgroundListener(processInfo) { appInBackgroundNow ->
37     if (appInBackgroundNow) {
38       check(currentJob == null) {
39         "Current job set to null when leaving background"
40       }
41 
42       val job =
43         analysisClient.newJob(JobContext(BackgroundTrigger::class))
44       currentJob = job
45       analysisExecutor.execute {
46         val result = job.execute()
47         currentJob = null
48         analysisCallback(result)
49       }
50     } else {
51       currentJob?.cancel("app left background")
52       currentJob = null
53     }
54   }
55 
startnull56   fun start() {
57     checkMainThread()
58     backgroundListener.install(application)
59   }
60 
stopnull61   fun stop() {
62     checkMainThread()
63     backgroundListener.uninstall(application)
64   }
65 }