1 /*
2  * Copyright (C) 2020 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.car.connecteddevice.util;
18 
19 import static com.android.car.connecteddevice.util.SafeLog.logd;
20 
21 import android.os.IBinder;
22 import android.os.RemoteException;
23 
24 import java.util.function.Consumer;
25 
26 /**
27  * Class that holds the binder of a remote callback and an action to be executed when this
28  * binder dies.
29  * It registers for death notification of the {@link #mCallbackBinder} and executes
30  * {@link #mOnDiedConsumer} when {@link #mCallbackBinder} dies.
31  */
32 public class RemoteCallbackBinder implements IBinder.DeathRecipient {
33     private static final String TAG = "BinderClient";
34     private final IBinder mCallbackBinder;
35     private final Consumer<IBinder> mOnDiedConsumer;
36 
RemoteCallbackBinder(IBinder binder, Consumer<IBinder> onBinderDied)37     public RemoteCallbackBinder(IBinder binder, Consumer<IBinder> onBinderDied) {
38         mCallbackBinder = binder;
39         mOnDiedConsumer = onBinderDied;
40         try {
41             binder.linkToDeath(this, 0);
42         } catch (RemoteException e) {
43             logd(TAG, "Cannot link death recipient to binder " + mCallbackBinder + ", "
44                     + e);
45         }
46     }
47 
48     @Override
binderDied()49     public void binderDied() {
50         logd(TAG, "Binder died " + mCallbackBinder);
51         mOnDiedConsumer.accept(mCallbackBinder);
52         cleanUp();
53     }
54 
55     /** Clean up the client. */
cleanUp()56     public void cleanUp() {
57         mCallbackBinder.unlinkToDeath(this, 0);
58     }
59 
60     /** Get the callback binder of the client. */
getCallbackBinder()61     public IBinder getCallbackBinder() {
62         return mCallbackBinder;
63     }
64 
65     @Override
equals(Object obj)66     public boolean equals(Object obj) {
67         return mCallbackBinder.equals(obj);
68     }
69 
70     @Override
hashCode()71     public int hashCode() {
72         return mCallbackBinder.hashCode();
73     }
74 }
75