1 package leakcanary
2 
3 import android.app.Application
4 import android.content.Context
5 import android.content.SharedPreferences
6 import leakcanary.HeapAnalysisInterceptor.Chain
7 import leakcanary.HeapAnalysisJob.Result
8 import java.util.concurrent.TimeUnit
9 
10 /**
11  * Proceeds once per [period] (of time) and then cancels all follow up jobs until [period] has
12  * passed.
13  */
14 class OncePerPeriodInterceptor(
15   application: Application,
16   private val periodMillis: Long = TimeUnit.DAYS.toMillis(1)
17 ) : HeapAnalysisInterceptor {
18 
<lambda>null19   private val preference: SharedPreferences by lazy {
20     application.getSharedPreferences("OncePerPeriodInterceptor", Context.MODE_PRIVATE)!!
21   }
22 
interceptnull23   override fun intercept(chain: Chain): Result {
24     val lastStartTimestamp = preference.getLong(LAST_START_TIMESTAMP_KEY, 0)
25     val now = System.currentTimeMillis()
26     val elapsedMillis = now - lastStartTimestamp
27 
28     if (elapsedMillis < periodMillis) {
29       chain.job.cancel("not enough time elapsed since last analysis: elapsed $elapsedMillis ms < period $periodMillis ms")
30     }
31 
32     return chain.proceed().apply {
33       if (this is Result.Done) {
34         preference.edit().putLong(LAST_START_TIMESTAMP_KEY, now).apply()
35       }
36     }
37   }
38 
forgetnull39   fun forget() {
40     preference.edit().clear().apply()
41   }
42 
43   companion object {
44     private const val LAST_START_TIMESTAMP_KEY = "last_start_timestamp"
45   }
46 }