blob: 44ce75ed64e6dd8933e018eafa54b1264661ef9c [file] [log] [blame]
Santos Cordon8e8b8d22013-12-19 14:14:05 -08001/*
2 * Copyright (C) 2013 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
17package com.android.telecomm;
18
19import android.content.ComponentName;
20import android.content.Context;
21import android.content.Intent;
Ben Giladd17443c2014-01-06 11:04:15 -080022import android.content.ServiceConnection;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080023import android.content.pm.PackageManager;
24import android.content.pm.ResolveInfo;
25import android.content.pm.ServiceInfo;
Evan Charlton0958f532014-01-10 16:58:02 -080026import android.os.Handler;
Ben Giladd17443c2014-01-06 11:04:15 -080027import android.os.IBinder;
Evan Charlton0958f532014-01-10 16:58:02 -080028import android.os.Looper;
Santos Cordoncb83fb62014-01-06 10:57:57 -080029import android.os.RemoteException;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080030import android.telecomm.ICallService;
Santos Cordoncb83fb62014-01-06 10:57:57 -080031import android.telecomm.ICallServiceLookupResponse;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080032import android.telecomm.ICallServiceProvider;
33import android.util.Log;
34
Ben Giladd17443c2014-01-06 11:04:15 -080035import com.google.common.base.Preconditions;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080036import com.google.common.collect.Lists;
Ben Giladd17443c2014-01-06 11:04:15 -080037import com.google.common.collect.Sets;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080038
39import java.util.List;
Ben Giladd17443c2014-01-06 11:04:15 -080040import java.util.Set;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080041
42/**
43 * Finds {@link ICallService} and {@link ICallServiceProvider} implementations on the device.
44 * Uses binder APIs to find ICallServiceProviders and calls method on ICallServiceProvider to
45 * find ICallService implementations.
46 * TODO(santoscordon): Add performance timing to async calls.
47 */
48final class CallServiceFinder {
Ben Giladd17443c2014-01-06 11:04:15 -080049
Ben Giladd17443c2014-01-06 11:04:15 -080050 private static final String TAG = CallServiceFinder.class.getSimpleName();
Santos Cordon8e8b8d22013-12-19 14:14:05 -080051
52 /**
Evan Charlton0958f532014-01-10 16:58:02 -080053 * The longest period in milliseconds each lookup cycle is allowed to span over, see
54 * {@link #mLookupTerminator}.
Ben Giladd17443c2014-01-06 11:04:15 -080055 * TODO(gilad): Likely requires tuning.
Santos Cordon8e8b8d22013-12-19 14:14:05 -080056 */
Evan Charlton0958f532014-01-10 16:58:02 -080057 private static final int LOOKUP_TIMEOUT_MS = 100;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080058
Ben Giladd17443c2014-01-06 11:04:15 -080059 /**
60 * Used to retrieve all known ICallServiceProvider implementations from the framework.
61 * TODO(gilad): Move to a more logical place for this to be shared.
62 */
63 static final String CALL_SERVICE_PROVIDER_CLASS_NAME = ICallServiceProvider.class.getName();
Santos Cordon8e8b8d22013-12-19 14:14:05 -080064
Ben Gilad0407fb22014-01-09 16:18:41 -080065 private final Switchboard mSwitchboard;
66
Ben Giladd17443c2014-01-06 11:04:15 -080067 /**
68 * Determines whether or not a lookup cycle is already running.
69 */
70 private boolean mIsLookupInProgress = false;
Santos Cordon8e8b8d22013-12-19 14:14:05 -080071
Ben Giladd17443c2014-01-06 11:04:15 -080072 /**
73 * Used to generate unique lookup-cycle identifiers. Incremented upon initiateLookup calls.
Ben Giladb59769e2014-01-16 11:41:10 -080074 * TODO(gilad): If at all useful, consider porting the cycle ID concept to switchboard and
75 * have it centralized/shared between the two finders.
Ben Giladd17443c2014-01-06 11:04:15 -080076 */
77 private int mNextLookupId = 0;
78
79 /**
Ben Gilad03292d42014-01-16 15:06:16 -080080 * The set of bound call-services. Only populated via initiateLookup scenarios. Entries should
81 * only be removed upon unbinding.
82 * TODO(gilad): Add the necessary logic to keep this set up to date.
83 */
84 private Set<ICallService> mCallServiceRegistry = Sets.newHashSet();
85
86 /**
Ben Giladd17443c2014-01-06 11:04:15 -080087 * The set of bound call-service providers. Only populated via initiateLookup scenarios.
88 * Providers should only be removed upon unbinding.
89 */
90 private Set<ICallServiceProvider> mProviderRegistry = Sets.newHashSet();
91
92 /**
93 * Stores the names of the providers to bind to in one lookup cycle. The set size represents
94 * the number of call-service providers this finder expects to hear back from upon initiating
95 * call-service lookups, see initiateLookup. Whenever all providers respond before the lookup
96 * timeout occurs, the complete set of (available) call services is passed to the switchboard
97 * for further processing of outgoing calls etc. When the timeout occurs before all responds
98 * are received, the partial (potentially empty) set gets passed (to the switchboard) instead.
Ben Giladb59769e2014-01-16 11:41:10 -080099 * Cached providers do not require finding and hence are excluded from this set. Entries are
100 * removed from this set as providers register.
Ben Giladd17443c2014-01-06 11:04:15 -0800101 */
102 private Set<ComponentName> mUnregisteredProviders;
103
104 /**
105 * Used to interrupt lookup cycles that didn't terminate naturally within the allowed
106 * period, see LOOKUP_TIMEOUT.
107 */
Evan Charlton0958f532014-01-10 16:58:02 -0800108 private final Runnable mLookupTerminator = new Runnable() {
109 @Override
110 public void run() {
111 terminateLookup();
112 }
113 };
114
115 /** Used to run code (e.g. messages, Runnables) on the main (UI) thread. */
116 private final Handler mHandler = new Handler(Looper.getMainLooper());
Ben Giladd17443c2014-01-06 11:04:15 -0800117
118 /**
Ben Gilad0407fb22014-01-09 16:18:41 -0800119 * Persists the specified parameters.
120 *
121 * @param switchboard The switchboard for this finer to work against.
122 */
123 CallServiceFinder(Switchboard switchboard) {
124 mSwitchboard = switchboard;
125 }
126
127 /**
Evan Charlton0958f532014-01-10 16:58:02 -0800128 * Initiates a lookup cycle for call-service providers. Must be called from the UI thread.
Ben Giladd17443c2014-01-06 11:04:15 -0800129 * TODO(gilad): Expand this comment to describe the lookup flow in more detail.
130 *
131 * @param context The relevant application context.
132 */
Evan Charlton0958f532014-01-10 16:58:02 -0800133 void initiateLookup(Context context) {
134 ThreadUtil.checkOnMainThread();
Ben Giladd17443c2014-01-06 11:04:15 -0800135 if (mIsLookupInProgress) {
136 // At most one active lookup is allowed at any given time, bail out.
137 return;
138 }
139
140 List<ComponentName> providerNames = getProviderNames(context);
141 if (providerNames.isEmpty()) {
142 Log.i(TAG, "No ICallServiceProvider implementations found.");
143 updateSwitchboard();
144 return;
145 }
146
147 mIsLookupInProgress = true;
148 mUnregisteredProviders = Sets.newHashSet();
149
150 int lookupId = mNextLookupId++;
151 for (ComponentName name : providerNames) {
152 if (!mProviderRegistry.contains(name)) {
153 // The provider is either not yet registered or has been unregistered
154 // due to unbinding etc.
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800155 bindProvider(name, lookupId, context);
Ben Giladd17443c2014-01-06 11:04:15 -0800156 mUnregisteredProviders.add(name);
157 }
158 }
159
160 int providerCount = providerNames.size();
161 int unregisteredProviderCount = mUnregisteredProviders.size();
162
Ben Giladb59769e2014-01-16 11:41:10 -0800163 Log.i(TAG, "Found " + providerCount + " implementations of ICallServiceProvider, "
Ben Giladd17443c2014-01-06 11:04:15 -0800164 + unregisteredProviderCount + " of which are not currently registered.");
165
166 if (unregisteredProviderCount == 0) {
167 // All known (provider) implementations are already registered, pass control
168 // back to the switchboard.
169 updateSwitchboard();
170 } else {
Evan Charlton0958f532014-01-10 16:58:02 -0800171 // Schedule a lookup terminator to run after LOOKUP_TIMEOUT_MS milliseconds.
172 mHandler.removeCallbacks(mLookupTerminator);
173 mHandler.postDelayed(mLookupTerminator, LOOKUP_TIMEOUT_MS);
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800174 }
175 }
176
177 /**
Ben Giladd17443c2014-01-06 11:04:15 -0800178 * Returns the all-inclusive list of call-service-provider names.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800179 *
Ben Giladd17443c2014-01-06 11:04:15 -0800180 * @param context The relevant/application context to query against.
181 * @return The list containing the (component) names of all known ICallServiceProvider
182 * implementations or the empty list upon no available providers.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800183 */
Ben Giladd17443c2014-01-06 11:04:15 -0800184 private List<ComponentName> getProviderNames(Context context) {
185 // The list of provider names to return to the caller, may be populated below.
186 List<ComponentName> providerNames = Lists.newArrayList();
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800187
188 PackageManager packageManager = context.getPackageManager();
Ben Giladd17443c2014-01-06 11:04:15 -0800189 Intent intent = new Intent(CALL_SERVICE_PROVIDER_CLASS_NAME);
190 for (ResolveInfo entry : packageManager.queryIntentServices(intent, 0)) {
191 ServiceInfo serviceInfo = entry.serviceInfo;
192 if (serviceInfo != null) {
193 // The entry resolves to a proper service, add it to the list of provider names.
194 providerNames.add(
195 new ComponentName(serviceInfo.packageName, serviceInfo.name));
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800196 }
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800197 }
198
Ben Giladd17443c2014-01-06 11:04:15 -0800199 return providerNames;
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800200 }
201
202 /**
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800203 * Attempts to bind the specified provider and have it register upon successful binding. Also
204 * performs the necessary wiring to unregister the provider upon un-binding.
205 *
206 * @param providerName The component name of the relevant provider.
207 * @param lookupId The lookup-cycle ID.
208 * @param context The relevant application context.
209 */
Ben Giladb59769e2014-01-16 11:41:10 -0800210 private void bindProvider(
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800211 final ComponentName providerName, final int lookupId, Context context) {
212
213 Preconditions.checkNotNull(providerName);
214 Preconditions.checkNotNull(context);
215
216 Intent serviceIntent =
217 new Intent(CALL_SERVICE_PROVIDER_CLASS_NAME).setComponent(providerName);
218 Log.i(TAG, "Binding to ICallServiceProvider through " + serviceIntent);
219
220 // Connection object for the service binding.
221 ServiceConnection connection = new ServiceConnection() {
222 @Override
223 public void onServiceConnected(ComponentName className, IBinder service) {
224 ICallServiceProvider provider = ICallServiceProvider.Stub.asInterface(service);
225 registerProvider(lookupId, providerName, provider);
226 }
227
228 @Override
229 public void onServiceDisconnected(ComponentName className) {
230 unregisterProvider(providerName);
231 }
232 };
233
234 if (!context.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE)) {
235 // TODO(santoscordon): Handle error.
236 }
237 }
238
239 /**
Santos Cordoncb83fb62014-01-06 10:57:57 -0800240 * Queries the supplied provider asynchronously for its CallServices and passes the list through
241 * to {@link #registerCallServices} which will relinquish control back to switchboard.
Ben Giladd17443c2014-01-06 11:04:15 -0800242 *
243 * @param lookupId The lookup-cycle ID.
244 * @param providerName The component name of the relevant provider.
245 * @param provider The provider object to register.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800246 */
Ben Giladd17443c2014-01-06 11:04:15 -0800247 private void registerProvider(
Santos Cordoncb83fb62014-01-06 10:57:57 -0800248 final int lookupId,
249 final ComponentName providerName,
250 final ICallServiceProvider provider) {
Ben Giladd17443c2014-01-06 11:04:15 -0800251
Santos Cordoncb83fb62014-01-06 10:57:57 -0800252 // Query the provider for {@link ICallService} implementations.
253 try {
254 provider.lookupCallServices(new ICallServiceLookupResponse.Stub() {
255 @Override
Evan Charlton18cc42f2014-01-28 14:44:11 -0800256 public void setCallServices(final List<IBinder> binderList) {
257 mHandler.post(new Runnable() {
258 @Override public void run() {
259 Set<ICallService> callServices = Sets.newHashSet();
260 for (IBinder binder : binderList) {
261 callServices.add(ICallService.Stub.asInterface(binder));
262 }
263 registerCallServices(lookupId, providerName, provider, callServices);
264 }
265 });
Santos Cordoncb83fb62014-01-06 10:57:57 -0800266 }
267 });
268 } catch (RemoteException e) {
269 Log.e(TAG, "Could not retrieve call services from: " + providerName);
270 }
271 }
272
273 /**
274 * Registers the {@link CallService}s for the specified provider and performs the necessary
275 * bookkeeping to potentially return control to the switchboard before the timeout for the
276 * current lookup cycle.
Santos Cordoncb83fb62014-01-06 10:57:57 -0800277 *
278 * @param lookupId The lookup-cycle ID.
279 * @param providerName The component name of the relevant provider.
280 * @param provider The provider associated with callServices.
281 * @param callServices The {@link CallService}s to register.
282 */
Evan Charlton18cc42f2014-01-28 14:44:11 -0800283 private void registerCallServices(
Santos Cordoncb83fb62014-01-06 10:57:57 -0800284 int lookupId,
285 ComponentName providerName,
286 ICallServiceProvider provider,
Evan Charlton18cc42f2014-01-28 14:44:11 -0800287 Set<ICallService> callServices) {
288 ThreadUtil.checkOnMainThread();
Santos Cordoncb83fb62014-01-06 10:57:57 -0800289
290 // TODO(santoscordon): When saving the call services into this class, also add code to
Ben Giladb59769e2014-01-16 11:41:10 -0800291 // unregister (remove) the call services upon disconnect. Potentially use RemoteCallbackList.
Santos Cordoncb83fb62014-01-06 10:57:57 -0800292
293 if (mUnregisteredProviders.remove(providerName)) {
294 mProviderRegistry.add(provider);
Ben Gilad03292d42014-01-16 15:06:16 -0800295 mCallServiceRegistry.addAll(callServices);
296
297 // TODO(gilad): Introduce a map to retain the association between call services
298 // and the corresponding provider such that mCallServiceRegistry can be updated
299 // upon unregisterProvider calls.
300
Santos Cordoncb83fb62014-01-06 10:57:57 -0800301 if (mUnregisteredProviders.size() < 1) {
302 terminateLookup(); // No other providers to wait for.
303 }
304 } else {
305 Log.i(TAG, "Received multiple lists of call services in lookup " + lookupId +
306 " from " + providerName);
307 }
Ben Giladd17443c2014-01-06 11:04:15 -0800308 }
309
310 /**
311 * Unregisters the specified provider.
312 *
313 * @param providerName The component name of the relevant provider.
314 */
315 private void unregisterProvider(ComponentName providerName) {
Evan Charlton18cc42f2014-01-28 14:44:11 -0800316 ThreadUtil.checkOnMainThread();
Ben Giladd17443c2014-01-06 11:04:15 -0800317 mProviderRegistry.remove(providerName);
318 }
319
320 /**
321 * Timeouts the current lookup cycle, see LookupTerminator.
322 */
323 private void terminateLookup() {
Evan Charlton0958f532014-01-10 16:58:02 -0800324 mHandler.removeCallbacks(mLookupTerminator);
Ben Giladd17443c2014-01-06 11:04:15 -0800325
326 updateSwitchboard();
327 mIsLookupInProgress = false;
328 }
329
330 /**
331 * Updates the switchboard passing the relevant call services (as opposed
332 * to call-service providers).
333 */
334 private void updateSwitchboard() {
Evan Charlton0958f532014-01-10 16:58:02 -0800335 ThreadUtil.checkOnMainThread();
Ben Gilad03292d42014-01-16 15:06:16 -0800336 mSwitchboard.setCallServices(mCallServiceRegistry);
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800337 }
338}