blob: 4ee73c3df9628e3841e443fad6b7684e3e59a69f [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 /**
80 * The set of bound call-service providers. Only populated via initiateLookup scenarios.
81 * Providers should only be removed upon unbinding.
82 */
83 private Set<ICallServiceProvider> mProviderRegistry = Sets.newHashSet();
84
85 /**
86 * Stores the names of the providers to bind to in one lookup cycle. The set size represents
87 * the number of call-service providers this finder expects to hear back from upon initiating
88 * call-service lookups, see initiateLookup. Whenever all providers respond before the lookup
89 * timeout occurs, the complete set of (available) call services is passed to the switchboard
90 * for further processing of outgoing calls etc. When the timeout occurs before all responds
91 * are received, the partial (potentially empty) set gets passed (to the switchboard) instead.
Ben Giladb59769e2014-01-16 11:41:10 -080092 * Cached providers do not require finding and hence are excluded from this set. Entries are
93 * removed from this set as providers register.
Ben Giladd17443c2014-01-06 11:04:15 -080094 */
95 private Set<ComponentName> mUnregisteredProviders;
96
97 /**
98 * Used to interrupt lookup cycles that didn't terminate naturally within the allowed
99 * period, see LOOKUP_TIMEOUT.
100 */
Evan Charlton0958f532014-01-10 16:58:02 -0800101 private final Runnable mLookupTerminator = new Runnable() {
102 @Override
103 public void run() {
104 terminateLookup();
105 }
106 };
107
108 /** Used to run code (e.g. messages, Runnables) on the main (UI) thread. */
109 private final Handler mHandler = new Handler(Looper.getMainLooper());
Ben Giladd17443c2014-01-06 11:04:15 -0800110
111 /**
Ben Gilad0407fb22014-01-09 16:18:41 -0800112 * Persists the specified parameters.
113 *
114 * @param switchboard The switchboard for this finer to work against.
115 */
116 CallServiceFinder(Switchboard switchboard) {
117 mSwitchboard = switchboard;
118 }
119
120 /**
Evan Charlton0958f532014-01-10 16:58:02 -0800121 * Initiates a lookup cycle for call-service providers. Must be called from the UI thread.
Ben Giladd17443c2014-01-06 11:04:15 -0800122 * TODO(gilad): Expand this comment to describe the lookup flow in more detail.
123 *
124 * @param context The relevant application context.
125 */
Evan Charlton0958f532014-01-10 16:58:02 -0800126 void initiateLookup(Context context) {
127 ThreadUtil.checkOnMainThread();
Ben Giladd17443c2014-01-06 11:04:15 -0800128 if (mIsLookupInProgress) {
129 // At most one active lookup is allowed at any given time, bail out.
130 return;
131 }
132
133 List<ComponentName> providerNames = getProviderNames(context);
134 if (providerNames.isEmpty()) {
135 Log.i(TAG, "No ICallServiceProvider implementations found.");
136 updateSwitchboard();
137 return;
138 }
139
140 mIsLookupInProgress = true;
141 mUnregisteredProviders = Sets.newHashSet();
142
143 int lookupId = mNextLookupId++;
144 for (ComponentName name : providerNames) {
145 if (!mProviderRegistry.contains(name)) {
146 // The provider is either not yet registered or has been unregistered
147 // due to unbinding etc.
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800148 bindProvider(name, lookupId, context);
Ben Giladd17443c2014-01-06 11:04:15 -0800149 mUnregisteredProviders.add(name);
150 }
151 }
152
153 int providerCount = providerNames.size();
154 int unregisteredProviderCount = mUnregisteredProviders.size();
155
Ben Giladb59769e2014-01-16 11:41:10 -0800156 Log.i(TAG, "Found " + providerCount + " implementations of ICallServiceProvider, "
Ben Giladd17443c2014-01-06 11:04:15 -0800157 + unregisteredProviderCount + " of which are not currently registered.");
158
159 if (unregisteredProviderCount == 0) {
160 // All known (provider) implementations are already registered, pass control
161 // back to the switchboard.
162 updateSwitchboard();
163 } else {
Evan Charlton0958f532014-01-10 16:58:02 -0800164 // Schedule a lookup terminator to run after LOOKUP_TIMEOUT_MS milliseconds.
165 mHandler.removeCallbacks(mLookupTerminator);
166 mHandler.postDelayed(mLookupTerminator, LOOKUP_TIMEOUT_MS);
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800167 }
168 }
169
170 /**
Ben Giladd17443c2014-01-06 11:04:15 -0800171 * Returns the all-inclusive list of call-service-provider names.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800172 *
Ben Giladd17443c2014-01-06 11:04:15 -0800173 * @param context The relevant/application context to query against.
174 * @return The list containing the (component) names of all known ICallServiceProvider
175 * implementations or the empty list upon no available providers.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800176 */
Ben Giladd17443c2014-01-06 11:04:15 -0800177 private List<ComponentName> getProviderNames(Context context) {
178 // The list of provider names to return to the caller, may be populated below.
179 List<ComponentName> providerNames = Lists.newArrayList();
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800180
181 PackageManager packageManager = context.getPackageManager();
Ben Giladd17443c2014-01-06 11:04:15 -0800182 Intent intent = new Intent(CALL_SERVICE_PROVIDER_CLASS_NAME);
183 for (ResolveInfo entry : packageManager.queryIntentServices(intent, 0)) {
184 ServiceInfo serviceInfo = entry.serviceInfo;
185 if (serviceInfo != null) {
186 // The entry resolves to a proper service, add it to the list of provider names.
187 providerNames.add(
188 new ComponentName(serviceInfo.packageName, serviceInfo.name));
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800189 }
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800190 }
191
Ben Giladd17443c2014-01-06 11:04:15 -0800192 return providerNames;
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800193 }
194
195 /**
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800196 * Attempts to bind the specified provider and have it register upon successful binding. Also
197 * performs the necessary wiring to unregister the provider upon un-binding.
198 *
199 * @param providerName The component name of the relevant provider.
200 * @param lookupId The lookup-cycle ID.
201 * @param context The relevant application context.
202 */
Ben Giladb59769e2014-01-16 11:41:10 -0800203 private void bindProvider(
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800204 final ComponentName providerName, final int lookupId, Context context) {
205
206 Preconditions.checkNotNull(providerName);
207 Preconditions.checkNotNull(context);
208
209 Intent serviceIntent =
210 new Intent(CALL_SERVICE_PROVIDER_CLASS_NAME).setComponent(providerName);
211 Log.i(TAG, "Binding to ICallServiceProvider through " + serviceIntent);
212
213 // Connection object for the service binding.
214 ServiceConnection connection = new ServiceConnection() {
215 @Override
216 public void onServiceConnected(ComponentName className, IBinder service) {
217 ICallServiceProvider provider = ICallServiceProvider.Stub.asInterface(service);
218 registerProvider(lookupId, providerName, provider);
219 }
220
221 @Override
222 public void onServiceDisconnected(ComponentName className) {
223 unregisterProvider(providerName);
224 }
225 };
226
227 if (!context.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE)) {
228 // TODO(santoscordon): Handle error.
229 }
230 }
231
232 /**
Santos Cordoncb83fb62014-01-06 10:57:57 -0800233 * Queries the supplied provider asynchronously for its CallServices and passes the list through
234 * to {@link #registerCallServices} which will relinquish control back to switchboard.
Ben Giladd17443c2014-01-06 11:04:15 -0800235 *
236 * @param lookupId The lookup-cycle ID.
237 * @param providerName The component name of the relevant provider.
238 * @param provider The provider object to register.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800239 */
Ben Giladd17443c2014-01-06 11:04:15 -0800240 private void registerProvider(
Santos Cordoncb83fb62014-01-06 10:57:57 -0800241 final int lookupId,
242 final ComponentName providerName,
243 final ICallServiceProvider provider) {
Ben Giladd17443c2014-01-06 11:04:15 -0800244
Santos Cordoncb83fb62014-01-06 10:57:57 -0800245 // Query the provider for {@link ICallService} implementations.
246 try {
247 provider.lookupCallServices(new ICallServiceLookupResponse.Stub() {
248 @Override
249 public void onResult(List<IBinder> binderList) {
250 List<ICallService> callServices = Lists.newArrayList();
251 for (IBinder binder : binderList) {
252 callServices.add(ICallService.Stub.asInterface(binder));
253 }
254 registerCallServices(lookupId, providerName, provider, callServices);
255 }
256 });
257 } catch (RemoteException e) {
258 Log.e(TAG, "Could not retrieve call services from: " + providerName);
259 }
260 }
261
262 /**
263 * Registers the {@link CallService}s for the specified provider and performs the necessary
264 * bookkeeping to potentially return control to the switchboard before the timeout for the
265 * current lookup cycle.
266 * TODO(santoscordon): Consider replacing this method's use of synchronized with a Handler
267 * queue.
Ben Giladb59769e2014-01-16 11:41:10 -0800268 * TODO(gilad): Santos has some POC code to make synchronized (below) unnecessary, either
269 * move to use that or remove this to-do.
Santos Cordoncb83fb62014-01-06 10:57:57 -0800270 *
271 * @param lookupId The lookup-cycle ID.
272 * @param providerName The component name of the relevant provider.
273 * @param provider The provider associated with callServices.
274 * @param callServices The {@link CallService}s to register.
275 */
276 synchronized private void registerCallServices(
277 int lookupId,
278 ComponentName providerName,
279 ICallServiceProvider provider,
280 List<ICallService> callServices) {
281
282 // TODO(santoscordon): When saving the call services into this class, also add code to
Ben Giladb59769e2014-01-16 11:41:10 -0800283 // unregister (remove) the call services upon disconnect. Potentially use RemoteCallbackList.
Santos Cordoncb83fb62014-01-06 10:57:57 -0800284
285 if (mUnregisteredProviders.remove(providerName)) {
286 mProviderRegistry.add(provider);
287 if (mUnregisteredProviders.size() < 1) {
288 terminateLookup(); // No other providers to wait for.
289 }
290 } else {
291 Log.i(TAG, "Received multiple lists of call services in lookup " + lookupId +
292 " from " + providerName);
293 }
Ben Giladd17443c2014-01-06 11:04:15 -0800294 }
295
296 /**
297 * Unregisters the specified provider.
298 *
299 * @param providerName The component name of the relevant provider.
300 */
301 private void unregisterProvider(ComponentName providerName) {
302 mProviderRegistry.remove(providerName);
303 }
304
305 /**
306 * Timeouts the current lookup cycle, see LookupTerminator.
307 */
308 private void terminateLookup() {
Evan Charlton0958f532014-01-10 16:58:02 -0800309 mHandler.removeCallbacks(mLookupTerminator);
Ben Giladd17443c2014-01-06 11:04:15 -0800310
311 updateSwitchboard();
312 mIsLookupInProgress = false;
313 }
314
315 /**
316 * Updates the switchboard passing the relevant call services (as opposed
317 * to call-service providers).
318 */
319 private void updateSwitchboard() {
Evan Charlton0958f532014-01-10 16:58:02 -0800320 ThreadUtil.checkOnMainThread();
Ben Giladb59769e2014-01-16 11:41:10 -0800321
Evan Charlton0958f532014-01-10 16:58:02 -0800322 // TODO(gilad): More here.
323 mSwitchboard.setCallServices(null);
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800324 }
325}