1 /*
2 * Copyright 2023 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 androidx.graphics.utils
18
19 import android.os.Handler
20 import android.os.HandlerThread
21 import android.os.SystemClock
22 import java.util.concurrent.Executor
23
24 /**
25 * Handler does not expose a post method that takes a token and a runnable. We need the token to be
26 * able to cancel pending requests so just call postAtTime with the default of
27 * SystemClock.uptimeMillis
28 */
postnull29 internal fun Handler.post(token: Any?, runnable: Runnable) {
30 postAtTime(runnable, token, SystemClock.uptimeMillis())
31 }
32
33 /**
34 * Helper class that wraps a Handler/HandlerThread combination and implements the [Executor]
35 * interface
36 */
37 internal class HandlerThreadExecutor(name: String) : Executor {
38
<lambda>null39 private val mHandlerThread = HandlerThread(name).apply { start() }
40 private val mHandler = Handler(mHandlerThread.looper)
41
postnull42 fun post(token: Any, runnable: Runnable) {
43 mHandler.post(token, runnable)
44 }
45
postnull46 fun post(runnable: Runnable) {
47 mHandler.post(runnable)
48 }
49
postDelayednull50 fun postDelayed(runnable: Runnable, delayMillis: Long) {
51 mHandler.postDelayed(runnable, delayMillis)
52 }
53
removeCallbacksAndMessagesnull54 fun removeCallbacksAndMessages(token: Any) {
55 mHandler.removeCallbacksAndMessages(token)
56 }
57
removeCallbacksnull58 fun removeCallbacks(runnable: Runnable) {
59 mHandler.removeCallbacks(runnable)
60 }
61
executenull62 override fun execute(runnable: Runnable?) {
63 runnable?.let { mHandler.post(it) }
64 }
65
66 private var mIsQuit = false
67
68 val isRunning: Boolean
69 get() = !mIsQuit
70
quitnull71 fun quit() {
72 mHandlerThread.quit()
73 mIsQuit = true
74 }
75 }
76