• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 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 android.os
18 
19 import com.android.launcher3.util.Executors.MAIN_EXECUTOR
20 import com.android.launcher3.util.WeakCleanupSet
21 import com.android.launcher3.util.WeakCleanupSet.OnOwnerDestroyedCallback
22 
23 /** Utility methods related to Binder */
24 object BinderUtils {
25 
26     /** Creates a binder wrapper which is tied to the [lifecycle] */
27     @JvmStatic
wrapLifecyclenull28     fun <T : Binder> T.wrapLifecycle(cleanupSet: WeakCleanupSet): Binder =
29         LifecycleBinderWrapper(this, cleanupSet)
30 
31     private class LifecycleBinderWrapper<T : Binder>(
32         private var realBinder: T?,
33         cleanupSet: WeakCleanupSet,
34     ) : Binder(realBinder?.interfaceDescriptor), OnOwnerDestroyedCallback {
35 
36         init {
37             MAIN_EXECUTOR.execute { cleanupSet.addOnOwnerDestroyedCallback(this) }
38         }
39 
40         override fun queryLocalInterface(descriptor: String): IInterface? =
41             realBinder?.queryLocalInterface(descriptor)
42 
43         override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean =
44             realBinder?.transact(code, data, reply, flags)
45                 ?: throw RemoteException("Original binder cleaned up")
46 
47         override fun onOwnerDestroyed() {
48             realBinder = null
49         }
50     }
51 }
52