Debian Codegraph @

core/java/com/android/internal/util/PersistentServiceConnection.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.content.Context;
20 import android.content.Intent;
21 import android.content.ServiceConnection;
22 import android.os.Handler;
23 import android.os.SystemClock;
24
25 import com.android.internal.annotations.GuardedBy;
26 import com.android.internal.annotations.VisibleForTesting;
27
28 import java.util.concurrent.Executor;
29
30 /**
31 * {@link PersistentServiceConnection} is a concrete implementation of {@link ServiceConnection}
32 * that maintains the binder connection by handling reconnection when a failure occurs.
33 *
34 * @param <T> The transformed connection type handled by the service.
35 *
36 * When the target process is killed (by OOM-killer, force-stopped, crash, etc..) then this class
37 * will trigger a reconnection to the target. This should be used carefully.
38 *
39 * NOTE: This class does *not* handle package-updates -- i.e. even if the binding dies due to
40 * the target package being updated, this class won't reconnect. This is because this class doesn't
41 * know what to do when the service component has gone missing, for example. If the user of this
42 * class wants to restore the connection, then it should call {@link #unbind()} and {@link #bind}
43 * explicitly.
44 */
45 public class PersistentServiceConnection<T> extends ObservableServiceConnection<T> {
46 private final Callback<T> mConnectionCallback = new Callback<T>() {
47 private long mConnectedTime;
48
49 @Override
50 public void onConnected(ObservableServiceConnection<T> connection, T service) {
51 mConnectedTime = mInjector.uptimeMillis();
52 }
53
54 @Override
55 public void onDisconnected(ObservableServiceConnection<T> connection,
56 @DisconnectReason int reason) {
57 if (reason == DISCONNECT_REASON_UNBIND) return;
58 synchronized (mLock) {
59 if ((mInjector.uptimeMillis() - mConnectedTime) > mMinConnectionDurationMs) {
60 mReconnectAttempts = 0;
61 bindInternalLocked();
62 } else {
63 scheduleConnectionAttemptLocked();
64 }
65 }
66 }
67 };
68
69 private final Object mLock = new Object();
70 private final Injector mInjector;
71 private final Handler mHandler;
72 private final int mMinConnectionDurationMs;
73 private final int mMaxReconnectAttempts;
74 private final int mBaseReconnectDelayMs;
75 @GuardedBy("mLock")
76 private int mReconnectAttempts;
77 @GuardedBy("mLock")
78 private Object mCancelToken;
79
80 private final Runnable mConnectRunnable = new Runnable() {
81 @Override
82 public void run() {
83 synchronized (mLock) {
84 mCancelToken = null;
85 bindInternalLocked();
86 }
87 }
88 };
89
90 /**
91 * Default constructor for {@link PersistentServiceConnection}.
92 *
93 * @param context The context from which the service will be bound with.
94 * @param executor The executor for connection callbacks to be delivered on
95 * @param transformer A {@link ServiceTransformer} for transforming
96 */
97 public PersistentServiceConnection(Context context,
98 Executor executor,
99 Handler handler,
100 ServiceTransformer<T> transformer,
101 Intent serviceIntent,
102 int flags,
103 int minConnectionDurationMs,
104 int maxReconnectAttempts,
105 int baseReconnectDelayMs) {
106 this(context,
107 executor,
108 handler,
109 transformer,
110 serviceIntent,
111 flags,
112 minConnectionDurationMs,
113 maxReconnectAttempts,
114 baseReconnectDelayMs,
115 new Injector());
116 }
117
118 @VisibleForTesting
119 public PersistentServiceConnection(
120 Context context,
121 Executor executor,
122 Handler handler,
123 ServiceTransformer<T> transformer,
124 Intent serviceIntent,
125 int flags,
126 int minConnectionDurationMs,
127 int maxReconnectAttempts,
128 int baseReconnectDelayMs,
129 Injector injector) {
130 super(context, executor, transformer, serviceIntent, flags);
131 mHandler = handler;
132 mMinConnectionDurationMs = minConnectionDurationMs;
133 mMaxReconnectAttempts = maxReconnectAttempts;
134 mBaseReconnectDelayMs = baseReconnectDelayMs;
135 mInjector = injector;
136 }
137
138 /** {@inheritDoc} */
139 @Override
140 public boolean bind() {
141 synchronized (mLock) {
142 addCallback(mConnectionCallback);
143 mReconnectAttempts = 0;
144 return bindInternalLocked();
145 }
146 }
147
148 @GuardedBy("mLock")
149 private boolean bindInternalLocked() {
150 return super.bind();
151 }
152
153 /** {@inheritDoc} */
154 @Override
155 public void unbind() {
156 synchronized (mLock) {
157 removeCallback(mConnectionCallback);
158 cancelPendingConnectionAttemptLocked();
159 super.unbind();
160 }
161 }
162
163 @GuardedBy("mLock")
164 private void cancelPendingConnectionAttemptLocked() {
165 if (mCancelToken != null) {
166 mHandler.removeCallbacksAndMessages(mCancelToken);
167 mCancelToken = null;
168 }
169 }
170
171 @GuardedBy("mLock")
172 private void scheduleConnectionAttemptLocked() {
173 cancelPendingConnectionAttemptLocked();
174
175 if (mReconnectAttempts >= mMaxReconnectAttempts) {
176 return;
177 }
178
179 final long reconnectDelayMs =
180 (long) Math.scalb(mBaseReconnectDelayMs, mReconnectAttempts);
181
182 mCancelToken = new Object();
183 mHandler.postDelayed(mConnectRunnable, mCancelToken, reconnectDelayMs);
184 mReconnectAttempts++;
185 }
186
187 /**
188 * Injector for testing
189 */
190 @VisibleForTesting
191 public static class Injector {
192 /**
193 * Returns milliseconds since boot, not counting time spent in deep sleep. Can be overridden
194 * in tests with a fake clock.
195 */
196 public long uptimeMillis() {
197 return SystemClock.uptimeMillis();
198 }
199 }
200 }