Debian Codegraph @

core/java/com/android/internal/util/ObservableServiceConnection.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2022 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.internal.util;
18
19 import android.annotation.CallbackExecutor;
20 import android.annotation.IntDef;
21 import android.annotation.NonNull;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.ServiceConnection;
26 import android.os.IBinder;
27
28 import com.android.internal.annotations.GuardedBy;
29 import com.android.internal.util.CallbackRegistry.NotifierCallback;
30
31 import java.lang.annotation.Retention;
32 import java.lang.annotation.RetentionPolicy;
33 import java.util.concurrent.Executor;
34
35 /**
36 * {@link ObservableServiceConnection} is a concrete implementation of {@link ServiceConnection}
37 * that enables monitoring the status of a binder connection. It also aides in automatically
38 * converting a proxy into an internal wrapper type.
39 *
40 * @param <T> The type of the wrapper over the resulting service.
41 */
42 public class ObservableServiceConnection<T> implements ServiceConnection {
43 /**
44 * An interface for converting the service proxy into a given internal wrapper type.
45 *
46 * @param <T> The type of the wrapper over the resulting service.
47 */
48 public interface ServiceTransformer<T> {
49 /**
50 * Called to convert the service proxy to the wrapper type.
51 *
52 * @param service The service proxy to create the wrapper type from.
53 * @return The wrapper type.
54 */
55 T convert(IBinder service);
56 }
57
58 /**
59 * An interface for listening to the connection status.
60 *
61 * @param <T> The wrapper type.
62 */
63 public interface Callback<T> {
64 /**
65 * Invoked when the service has been successfully connected to.
66 *
67 * @param connection The {@link ObservableServiceConnection} instance that is now connected
68 * @param service The service proxy converted into the typed wrapper.
69 */
70 void onConnected(ObservableServiceConnection<T> connection, T service);
71
72 /**
73 * Invoked when the service has been disconnected.
74 *
75 * @param connection The {@link ObservableServiceConnection} that is now disconnected.
76 * @param reason The reason for the disconnection.
77 */
78 void onDisconnected(ObservableServiceConnection<T> connection,
79 @DisconnectReason int reason);
80 }
81
82 /**
83 * Default state, service has not yet disconnected.
84 */
85 public static final int DISCONNECT_REASON_NONE = 0;
86 /**
87 * Disconnection was due to the resulting binding being {@code null}.
88 */
89 public static final int DISCONNECT_REASON_NULL_BINDING = 1;
90 /**
91 * Disconnection was due to the remote end disconnecting.
92 */
93 public static final int DISCONNECT_REASON_DISCONNECTED = 2;
94 /**
95 * Disconnection due to the binder dying.
96 */
97 public static final int DISCONNECT_REASON_BINDING_DIED = 3;
98 /**
99 * Disconnection from an explicit unbinding.
100 */
101 public static final int DISCONNECT_REASON_UNBIND = 4;
102
103 @Retention(RetentionPolicy.SOURCE)
104 @IntDef({
105 DISCONNECT_REASON_NONE,
106 DISCONNECT_REASON_NULL_BINDING,
107 DISCONNECT_REASON_DISCONNECTED,
108 DISCONNECT_REASON_BINDING_DIED,
109 DISCONNECT_REASON_UNBIND
110 })
111 public @interface DisconnectReason {
112 }
113
114 private final Object mLock = new Object();
115 private final Context mContext;
116 private final Executor mExecutor;
117 private final ServiceTransformer<T> mTransformer;
118 private final Intent mServiceIntent;
119 private final int mFlags;
120
121 @GuardedBy("mLock")
122 private T mService;
123 @GuardedBy("mLock")
124 private boolean mBoundCalled = false;
125 @GuardedBy("mLock")
126 private int mLastDisconnectReason = DISCONNECT_REASON_NONE;
127
128 private final CallbackRegistry<Callback<T>, ObservableServiceConnection<T>, T>
129 mCallbackRegistry = new CallbackRegistry<>(
130 new NotifierCallback<Callback<T>, ObservableServiceConnection<T>, T>() {
131 @Override
132 public void onNotifyCallback(Callback<T> callback,
133 ObservableServiceConnection<T> sender,
134 int disconnectReason, T service) {
135 mExecutor.execute(() -> {
136 synchronized (mLock) {
137 if (service != null) {
138 callback.onConnected(sender, service);
139 } else if (mLastDisconnectReason != DISCONNECT_REASON_NONE) {
140 callback.onDisconnected(sender, disconnectReason);
141 }
142 }
143 });
144 }
145 });
146
147 /**
148 * Default constructor for {@link ObservableServiceConnection}.
149 *
150 * @param context The context from which the service will be bound with.
151 * @param executor The executor for connection callbacks to be delivered on
152 * @param transformer A {@link ObservableServiceConnection.ServiceTransformer} for transforming
153 * the resulting service into a desired type.
154 */
155 public ObservableServiceConnection(@NonNull Context context,
156 @NonNull @CallbackExecutor Executor executor,
157 @NonNull ServiceTransformer<T> transformer,
158 Intent serviceIntent,
159 int flags) {
160 mContext = context;
161 mExecutor = executor;
162 mTransformer = transformer;
163 mServiceIntent = serviceIntent;
164 mFlags = flags;
165 }
166
167 /**
168 * Initiate binding to the service.
169 *
170 * @return {@code true} if initiating binding succeed, {@code false} if the binding failed or
171 * if this service is already bound. Regardless of the return value, you should later call
172 * {@link #unbind()} to release the connection.
173 */
174 public boolean bind() {
175 synchronized (mLock) {
176 if (mBoundCalled) {
177 return false;
178 }
179 final boolean bindResult =
180 mContext.bindService(mServiceIntent, mFlags, mExecutor, this);
181 mBoundCalled = true;
182 return bindResult;
183 }
184 }
185
186 /**
187 * Disconnect from the service if bound.
188 */
189 public void unbind() {
190 onDisconnected(DISCONNECT_REASON_UNBIND);
191 }
192
193 /**
194 * Adds a callback for receiving connection updates.
195 *
196 * @param callback The {@link Callback} to receive future updates.
197 */
198 public void addCallback(Callback<T> callback) {
199 mCallbackRegistry.add(callback);
200 mExecutor.execute(() -> {
201 synchronized (mLock) {
202 if (mService != null) {
203 callback.onConnected(this, mService);
204 } else if (mLastDisconnectReason != DISCONNECT_REASON_NONE) {
205 callback.onDisconnected(this, mLastDisconnectReason);
206 }
207 }
208 });
209 }
210
211 /**
212 * Removes previously added callback from receiving future connection updates.
213 *
214 * @param callback The {@link Callback} to be removed.
215 */
216 public void removeCallback(Callback<T> callback) {
217 synchronized (mLock) {
218 mCallbackRegistry.remove(callback);
219 }
220 }
221
222 private void onDisconnected(@DisconnectReason int reason) {
223 synchronized (mLock) {
224 if (!mBoundCalled) {
225 return;
226 }
227 mBoundCalled = false;
228 mLastDisconnectReason = reason;
229 mContext.unbindService(this);
230 mService = null;
231 mCallbackRegistry.notifyCallbacks(this, reason, null);
232 }
233 }
234
235 @Override
236 public final void onServiceConnected(ComponentName name, IBinder service) {
237 synchronized (mLock) {
238 mService = mTransformer.convert(service);
239 mLastDisconnectReason = DISCONNECT_REASON_NONE;
240 mCallbackRegistry.notifyCallbacks(this, mLastDisconnectReason, mService);
241 }
242 }
243
244 @Override
245 public final void onServiceDisconnected(ComponentName name) {
246 onDisconnected(DISCONNECT_REASON_DISCONNECTED);
247 }
248
249 @Override
250 public final void onBindingDied(ComponentName name) {
251 onDisconnected(DISCONNECT_REASON_BINDING_DIED);
252 }
253
254 @Override
255 public final void onNullBinding(ComponentName name) {
256 onDisconnected(DISCONNECT_REASON_NULL_BINDING);
257 }
258 }