• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.fuelgauge.batteryusage
18 
19 import android.os.AsyncTask
20 import androidx.annotation.CallSuper
21 import androidx.annotation.OpenForTesting
22 import androidx.lifecycle.DefaultLifecycleObserver
23 import androidx.lifecycle.Lifecycle
24 import androidx.lifecycle.LifecycleOwner
25 import com.android.settingslib.datastore.HandlerExecutor.Companion.main as mainExecutor
26 
27 /**
28  * Lifecycle aware [AsyncTask] to cancel task automatically when [lifecycle] is stopped.
29  *
30  * Must call [start] instead of [execute] to run the task.
31  */
32 abstract class LifecycleAwareAsyncTask<Result>(private val lifecycle: Lifecycle?) :
33     AsyncTask<Void, Void, Result>(), DefaultLifecycleObserver {
34 
35     @CallSuper
onPostExecutenull36     override fun onPostExecute(result: Result) {
37         lifecycle?.removeObserver(this)
38     }
39 
onStopnull40     override fun onStop(owner: LifecycleOwner) {
41         cancel(false)
42         lifecycle?.removeObserver(this)
43     }
44 
45     /**
46      * Starts the task, which invokes [execute] (cannot override [execute] as it is final).
47      *
48      * This method is expected to be invoked from main thread but current usage might call from
49      * background thread.
50      */
startnull51     fun start() {
52         execute() // expects main thread
53         val lifecycle = lifecycle ?: return
54         mainExecutor.execute { maybeAddObserver(lifecycle) }
55     }
56 
57     @OpenForTesting
maybeAddObservernull58     open fun maybeAddObserver(lifecycle: Lifecycle) {
59         // Status is updated to FINISHED if onPoseExecute happened before. And task is cancelled
60         // if lifecycle is stopped.
61         if (status == Status.RUNNING && !isCancelled) {
62             lifecycle.addObserver(this) // requires main thread
63         }
64     }
65 }
66