<lambda>null1 package leakcanary.internal
2 
3 import android.app.Notification
4 import android.content.Context
5 import androidx.work.Data
6 import androidx.work.ForegroundInfo
7 import androidx.work.Worker
8 import androidx.work.WorkerParameters
9 import androidx.work.impl.utils.futures.SettableFuture
10 import com.google.common.util.concurrent.ListenableFuture
11 import com.squareup.leakcanary.core.R
12 import leakcanary.EventListener.Event
13 
14 internal class HeapAnalyzerWorker(appContext: Context, workerParams: WorkerParameters) :
15   Worker(appContext, workerParams) {
16   override fun doWork(): Result {
17     val doneEvent =
18       AndroidDebugHeapAnalyzer.runAnalysisBlocking(inputData.asEvent()) { event ->
19         InternalLeakCanary.sendEvent(event)
20       }
21     InternalLeakCanary.sendEvent(doneEvent)
22     return Result.success()
23   }
24 
25   override fun getForegroundInfoAsync(): ListenableFuture<ForegroundInfo> {
26     return applicationContext.heapAnalysisForegroundInfoAsync()
27   }
28 
29   companion object {
30     private const val EVENT_BYTES = "EVENT_BYTES"
31 
32     fun Event.asWorkerInputData(dataBuilder: Data.Builder = Data.Builder()) = dataBuilder
33       .putByteArray(EVENT_BYTES, toByteArray())
34       .build()
35 
36     inline fun <reified T> Data.asEvent(): T =
37       Serializables.fromByteArray<T>(getByteArray(EVENT_BYTES)!!)!!
38 
39     fun Context.heapAnalysisForegroundInfoAsync(): ListenableFuture<ForegroundInfo> {
40       val infoFuture = SettableFuture.create<ForegroundInfo>()
41       val builder = Notification.Builder(this)
42         .setContentTitle(getString(R.string.leak_canary_notification_analysing))
43         .setContentText("LeakCanary is working.")
44         .setProgress(100, 0, true)
45       val notification =
46         Notifications.buildNotification(this, builder, NotificationType.LEAKCANARY_LOW)
47       infoFuture.set(
48         ForegroundInfo(
49           R.id.leak_canary_notification_analyzing_heap,
50           notification
51         )
52       )
53       return infoFuture
54     }
55   }
56 }
57