blob: 898877f442dc01a98f43f36245a7a09468812a20 [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.
74 */
75 private int mNextLookupId = 0;
76
77 /**
78 * The set of bound call-service providers. Only populated via initiateLookup scenarios.
79 * Providers should only be removed upon unbinding.
80 */
81 private Set<ICallServiceProvider> mProviderRegistry = Sets.newHashSet();
82
83 /**
84 * Stores the names of the providers to bind to in one lookup cycle. The set size represents
85 * the number of call-service providers this finder expects to hear back from upon initiating
86 * call-service lookups, see initiateLookup. Whenever all providers respond before the lookup
87 * timeout occurs, the complete set of (available) call services is passed to the switchboard
88 * for further processing of outgoing calls etc. When the timeout occurs before all responds
89 * are received, the partial (potentially empty) set gets passed (to the switchboard) instead.
90 * Note that cached providers do not require finding and hence are excluded from this count.
91 * Also noteworthy is that providers are dynamically removed from this set as they register.
92 */
93 private Set<ComponentName> mUnregisteredProviders;
94
95 /**
96 * Used to interrupt lookup cycles that didn't terminate naturally within the allowed
97 * period, see LOOKUP_TIMEOUT.
98 */
Evan Charlton0958f532014-01-10 16:58:02 -080099 private final Runnable mLookupTerminator = new Runnable() {
100 @Override
101 public void run() {
102 terminateLookup();
103 }
104 };
105
106 /** Used to run code (e.g. messages, Runnables) on the main (UI) thread. */
107 private final Handler mHandler = new Handler(Looper.getMainLooper());
Ben Giladd17443c2014-01-06 11:04:15 -0800108
109 /**
Ben Gilad0407fb22014-01-09 16:18:41 -0800110 * Persists the specified parameters.
111 *
112 * @param switchboard The switchboard for this finer to work against.
113 */
114 CallServiceFinder(Switchboard switchboard) {
115 mSwitchboard = switchboard;
116 }
117
118 /**
Evan Charlton0958f532014-01-10 16:58:02 -0800119 * Initiates a lookup cycle for call-service providers. Must be called from the UI thread.
Ben Giladd17443c2014-01-06 11:04:15 -0800120 * TODO(gilad): Expand this comment to describe the lookup flow in more detail.
121 *
122 * @param context The relevant application context.
123 */
Evan Charlton0958f532014-01-10 16:58:02 -0800124 void initiateLookup(Context context) {
125 ThreadUtil.checkOnMainThread();
Ben Giladd17443c2014-01-06 11:04:15 -0800126 if (mIsLookupInProgress) {
127 // At most one active lookup is allowed at any given time, bail out.
128 return;
129 }
130
131 List<ComponentName> providerNames = getProviderNames(context);
132 if (providerNames.isEmpty()) {
133 Log.i(TAG, "No ICallServiceProvider implementations found.");
134 updateSwitchboard();
135 return;
136 }
137
138 mIsLookupInProgress = true;
139 mUnregisteredProviders = Sets.newHashSet();
140
141 int lookupId = mNextLookupId++;
142 for (ComponentName name : providerNames) {
143 if (!mProviderRegistry.contains(name)) {
144 // The provider is either not yet registered or has been unregistered
145 // due to unbinding etc.
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800146 bindProvider(name, lookupId, context);
Ben Giladd17443c2014-01-06 11:04:15 -0800147 mUnregisteredProviders.add(name);
148 }
149 }
150
151 int providerCount = providerNames.size();
152 int unregisteredProviderCount = mUnregisteredProviders.size();
153
154 Log.i(TAG, "Found " + providerCount + " implementations for ICallServiceProvider, "
155 + unregisteredProviderCount + " of which are not currently registered.");
156
157 if (unregisteredProviderCount == 0) {
158 // All known (provider) implementations are already registered, pass control
159 // back to the switchboard.
160 updateSwitchboard();
161 } else {
Evan Charlton0958f532014-01-10 16:58:02 -0800162 // Schedule a lookup terminator to run after LOOKUP_TIMEOUT_MS milliseconds.
163 mHandler.removeCallbacks(mLookupTerminator);
164 mHandler.postDelayed(mLookupTerminator, LOOKUP_TIMEOUT_MS);
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800165 }
166 }
167
168 /**
Ben Giladd17443c2014-01-06 11:04:15 -0800169 * Returns the all-inclusive list of call-service-provider names.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800170 *
Ben Giladd17443c2014-01-06 11:04:15 -0800171 * @param context The relevant/application context to query against.
172 * @return The list containing the (component) names of all known ICallServiceProvider
173 * implementations or the empty list upon no available providers.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800174 */
Ben Giladd17443c2014-01-06 11:04:15 -0800175 private List<ComponentName> getProviderNames(Context context) {
176 // The list of provider names to return to the caller, may be populated below.
177 List<ComponentName> providerNames = Lists.newArrayList();
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800178
179 PackageManager packageManager = context.getPackageManager();
Ben Giladd17443c2014-01-06 11:04:15 -0800180 Intent intent = new Intent(CALL_SERVICE_PROVIDER_CLASS_NAME);
181 for (ResolveInfo entry : packageManager.queryIntentServices(intent, 0)) {
182 ServiceInfo serviceInfo = entry.serviceInfo;
183 if (serviceInfo != null) {
184 // The entry resolves to a proper service, add it to the list of provider names.
185 providerNames.add(
186 new ComponentName(serviceInfo.packageName, serviceInfo.name));
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800187 }
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800188 }
189
Ben Giladd17443c2014-01-06 11:04:15 -0800190 return providerNames;
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800191 }
192
193 /**
Ben Gilad80ddb5d2014-01-15 14:48:29 -0800194 * Attempts to bind the specified provider and have it register upon successful binding. Also
195 * performs the necessary wiring to unregister the provider upon un-binding.
196 *
197 * @param providerName The component name of the relevant provider.
198 * @param lookupId The lookup-cycle ID.
199 * @param context The relevant application context.
200 */
201 void bindProvider(
202 final ComponentName providerName, final int lookupId, Context context) {
203
204 Preconditions.checkNotNull(providerName);
205 Preconditions.checkNotNull(context);
206
207 Intent serviceIntent =
208 new Intent(CALL_SERVICE_PROVIDER_CLASS_NAME).setComponent(providerName);
209 Log.i(TAG, "Binding to ICallServiceProvider through " + serviceIntent);
210
211 // Connection object for the service binding.
212 ServiceConnection connection = new ServiceConnection() {
213 @Override
214 public void onServiceConnected(ComponentName className, IBinder service) {
215 ICallServiceProvider provider = ICallServiceProvider.Stub.asInterface(service);
216 registerProvider(lookupId, providerName, provider);
217 }
218
219 @Override
220 public void onServiceDisconnected(ComponentName className) {
221 unregisterProvider(providerName);
222 }
223 };
224
225 if (!context.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE)) {
226 // TODO(santoscordon): Handle error.
227 }
228 }
229
230 /**
Santos Cordoncb83fb62014-01-06 10:57:57 -0800231 * Queries the supplied provider asynchronously for its CallServices and passes the list through
232 * to {@link #registerCallServices} which will relinquish control back to switchboard.
Ben Giladd17443c2014-01-06 11:04:15 -0800233 *
234 * @param lookupId The lookup-cycle ID.
235 * @param providerName The component name of the relevant provider.
236 * @param provider The provider object to register.
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800237 */
Ben Giladd17443c2014-01-06 11:04:15 -0800238 private void registerProvider(
Santos Cordoncb83fb62014-01-06 10:57:57 -0800239 final int lookupId,
240 final ComponentName providerName,
241 final ICallServiceProvider provider) {
Ben Giladd17443c2014-01-06 11:04:15 -0800242
Santos Cordoncb83fb62014-01-06 10:57:57 -0800243 // Query the provider for {@link ICallService} implementations.
244 try {
245 provider.lookupCallServices(new ICallServiceLookupResponse.Stub() {
246 @Override
247 public void onResult(List<IBinder> binderList) {
248 List<ICallService> callServices = Lists.newArrayList();
249 for (IBinder binder : binderList) {
250 callServices.add(ICallService.Stub.asInterface(binder));
251 }
252 registerCallServices(lookupId, providerName, provider, callServices);
253 }
254 });
255 } catch (RemoteException e) {
256 Log.e(TAG, "Could not retrieve call services from: " + providerName);
257 }
258 }
259
260 /**
261 * Registers the {@link CallService}s for the specified provider and performs the necessary
262 * bookkeeping to potentially return control to the switchboard before the timeout for the
263 * current lookup cycle.
264 * TODO(santoscordon): Consider replacing this method's use of synchronized with a Handler
265 * queue.
266 *
267 * @param lookupId The lookup-cycle ID.
268 * @param providerName The component name of the relevant provider.
269 * @param provider The provider associated with callServices.
270 * @param callServices The {@link CallService}s to register.
271 */
272 synchronized private void registerCallServices(
273 int lookupId,
274 ComponentName providerName,
275 ICallServiceProvider provider,
276 List<ICallService> callServices) {
277
278 // TODO(santoscordon): When saving the call services into this class, also add code to
279 // unregister (remove) the call services upon disconnect. Potenially use RemoteCallbackList.
280
281 if (mUnregisteredProviders.remove(providerName)) {
282 mProviderRegistry.add(provider);
283 if (mUnregisteredProviders.size() < 1) {
284 terminateLookup(); // No other providers to wait for.
285 }
286 } else {
287 Log.i(TAG, "Received multiple lists of call services in lookup " + lookupId +
288 " from " + providerName);
289 }
Ben Giladd17443c2014-01-06 11:04:15 -0800290 }
291
292 /**
293 * Unregisters the specified provider.
294 *
295 * @param providerName The component name of the relevant provider.
296 */
297 private void unregisterProvider(ComponentName providerName) {
298 mProviderRegistry.remove(providerName);
299 }
300
301 /**
302 * Timeouts the current lookup cycle, see LookupTerminator.
303 */
304 private void terminateLookup() {
Evan Charlton0958f532014-01-10 16:58:02 -0800305 mHandler.removeCallbacks(mLookupTerminator);
Ben Giladd17443c2014-01-06 11:04:15 -0800306
307 updateSwitchboard();
308 mIsLookupInProgress = false;
309 }
310
311 /**
312 * Updates the switchboard passing the relevant call services (as opposed
313 * to call-service providers).
314 */
315 private void updateSwitchboard() {
Evan Charlton0958f532014-01-10 16:58:02 -0800316 ThreadUtil.checkOnMainThread();
317 // TODO(gilad): More here.
318 mSwitchboard.setCallServices(null);
Santos Cordon8e8b8d22013-12-19 14:14:05 -0800319 }
320}