InCallController.java revision 72e47d5843810c17cea5cf3aadc76556f89e720a
1/* 2 * Copyright (C) 2014 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.server.telecom; 18 19import android.Manifest; 20import android.content.ComponentName; 21import android.content.Context; 22import android.content.Intent; 23import android.content.ServiceConnection; 24import android.content.pm.PackageManager; 25import android.content.pm.ResolveInfo; 26import android.content.pm.ServiceInfo; 27import android.content.res.Resources; 28import android.net.Uri; 29import android.os.IBinder; 30import android.os.RemoteException; 31import android.os.Trace; 32import android.os.UserHandle; 33import android.telecom.AudioState; 34import android.telecom.CallProperties; 35import android.telecom.CallState; 36import android.telecom.Connection; 37import android.telecom.InCallService; 38import android.telecom.ParcelableCall; 39import android.telecom.TelecomManager; 40import android.util.ArrayMap; 41 42// TODO: Needed for move to system service: import com.android.internal.R; 43import com.android.internal.telecom.IInCallService; 44import com.android.internal.util.IndentingPrintWriter; 45 46import java.util.ArrayList; 47import java.util.Collection; 48import java.util.Iterator; 49import java.util.List; 50import java.util.Map; 51import java.util.concurrent.ConcurrentHashMap; 52 53/** 54 * Binds to {@link IInCallService} and provides the service to {@link CallsManager} through which it 55 * can send updates to the in-call app. This class is created and owned by CallsManager and retains 56 * a binding to the {@link IInCallService} (implemented by the in-call app). 57 */ 58public final class InCallController extends CallsManagerListenerBase { 59 /** 60 * Used to bind to the in-call app and triggers the start of communication between 61 * this class and in-call app. 62 */ 63 private class InCallServiceConnection implements ServiceConnection { 64 /** {@inheritDoc} */ 65 @Override public void onServiceConnected(ComponentName name, IBinder service) { 66 Log.d(this, "onServiceConnected: %s", name); 67 onConnected(name, service); 68 } 69 70 /** {@inheritDoc} */ 71 @Override public void onServiceDisconnected(ComponentName name) { 72 Log.d(this, "onDisconnected: %s", name); 73 onDisconnected(name); 74 } 75 } 76 77 private final Call.Listener mCallListener = new Call.ListenerBase() { 78 @Override 79 public void onConnectionCapabilitiesChanged(Call call) { 80 updateCall(call); 81 } 82 83 @Override 84 public void onCannedSmsResponsesLoaded(Call call) { 85 updateCall(call); 86 } 87 88 @Override 89 public void onVideoCallProviderChanged(Call call) { 90 updateCall(call); 91 } 92 93 @Override 94 public void onStatusHintsChanged(Call call) { 95 updateCall(call); 96 } 97 98 @Override 99 public void onHandleChanged(Call call) { 100 updateCall(call); 101 } 102 103 @Override 104 public void onCallerDisplayNameChanged(Call call) { 105 updateCall(call); 106 } 107 108 @Override 109 public void onVideoStateChanged(Call call) { 110 updateCall(call); 111 } 112 113 @Override 114 public void onTargetPhoneAccountChanged(Call call) { 115 updateCall(call); 116 } 117 118 @Override 119 public void onConferenceableCallsChanged(Call call) { 120 updateCall(call); 121 } 122 }; 123 124 /** 125 * Maintains a binding connection to the in-call app(s). 126 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is 127 * load factor before resizing, 1 means we only expect a single thread to 128 * access the map so make only a single shard 129 */ 130 private final Map<ComponentName, InCallServiceConnection> mServiceConnections = 131 new ConcurrentHashMap<ComponentName, InCallServiceConnection>(8, 0.9f, 1); 132 133 /** The in-call app implementations, see {@link IInCallService}. */ 134 private final Map<ComponentName, IInCallService> mInCallServices = new ArrayMap<>(); 135 136 private final CallIdMapper mCallIdMapper = new CallIdMapper("InCall"); 137 138 /** The {@link ComponentName} of the default InCall UI. */ 139 private final ComponentName mInCallComponentName; 140 141 private final Context mContext; 142 143 public InCallController(Context context) { 144 mContext = context; 145 Resources resources = mContext.getResources(); 146 147 mInCallComponentName = new ComponentName( 148 resources.getString(R.string.ui_default_package), 149 resources.getString(R.string.incall_default_class)); 150 } 151 152 @Override 153 public void onCallAdded(Call call) { 154 if (mInCallServices.isEmpty()) { 155 bind(call); 156 } else { 157 Log.i(this, "onCallAdded: %s", call); 158 // Track the call if we don't already know about it. 159 addCall(call); 160 161 for (Map.Entry<ComponentName, IInCallService> entry : mInCallServices.entrySet()) { 162 ComponentName componentName = entry.getKey(); 163 IInCallService inCallService = entry.getValue(); 164 165 ParcelableCall parcelableCall = toParcelableCall(call, 166 componentName.equals(mInCallComponentName) /* includeVideoProvider */); 167 try { 168 inCallService.addCall(parcelableCall); 169 } catch (RemoteException ignored) { 170 } 171 } 172 } 173 } 174 175 @Override 176 public void onCallRemoved(Call call) { 177 Log.i(this, "onCallRemoved: %s", call); 178 if (TelecomSystem.getInstance().getCallsManager().getCalls().isEmpty()) { 179 // TODO: Wait for all messages to be delivered to the service before unbinding. 180 unbind(); 181 } 182 call.removeListener(mCallListener); 183 mCallIdMapper.removeCall(call); 184 } 185 186 @Override 187 public void onCallStateChanged(Call call, int oldState, int newState) { 188 updateCall(call); 189 } 190 191 @Override 192 public void onConnectionServiceChanged( 193 Call call, 194 ConnectionServiceWrapper oldService, 195 ConnectionServiceWrapper newService) { 196 updateCall(call); 197 } 198 199 @Override 200 public void onAudioStateChanged(AudioState oldAudioState, AudioState newAudioState) { 201 if (!mInCallServices.isEmpty()) { 202 Log.i(this, "Calling onAudioStateChanged, audioState: %s -> %s", oldAudioState, 203 newAudioState); 204 for (IInCallService inCallService : mInCallServices.values()) { 205 try { 206 inCallService.onAudioStateChanged(newAudioState); 207 } catch (RemoteException ignored) { 208 } 209 } 210 } 211 } 212 213 @Override 214 public void onCanAddCallChanged(boolean canAddCall) { 215 if (!mInCallServices.isEmpty()) { 216 Log.i(this, "onCanAddCallChanged : %b", canAddCall); 217 for (IInCallService inCallService : mInCallServices.values()) { 218 try { 219 inCallService.onCanAddCallChanged(canAddCall); 220 } catch (RemoteException ignored) { 221 } 222 } 223 } 224 } 225 226 void onPostDialWait(Call call, String remaining) { 227 if (!mInCallServices.isEmpty()) { 228 Log.i(this, "Calling onPostDialWait, remaining = %s", remaining); 229 for (IInCallService inCallService : mInCallServices.values()) { 230 try { 231 inCallService.setPostDialWait(mCallIdMapper.getCallId(call), remaining); 232 } catch (RemoteException ignored) { 233 } 234 } 235 } 236 } 237 238 @Override 239 public void onIsConferencedChanged(Call call) { 240 Log.d(this, "onIsConferencedChanged %s", call); 241 updateCall(call); 242 } 243 244 void bringToForeground(boolean showDialpad) { 245 if (!mInCallServices.isEmpty()) { 246 for (IInCallService inCallService : mInCallServices.values()) { 247 try { 248 inCallService.bringToForeground(showDialpad); 249 } catch (RemoteException ignored) { 250 } 251 } 252 } else { 253 Log.w(this, "Asking to bring unbound in-call UI to foreground."); 254 } 255 } 256 257 /** 258 * Unbinds an existing bound connection to the in-call app. 259 */ 260 private void unbind() { 261 ThreadUtil.checkOnMainThread(); 262 Iterator<Map.Entry<ComponentName, InCallServiceConnection>> iterator = 263 mServiceConnections.entrySet().iterator(); 264 while (iterator.hasNext()) { 265 Log.i(this, "Unbinding from InCallService %s"); 266 mContext.unbindService(iterator.next().getValue()); 267 iterator.remove(); 268 } 269 mInCallServices.clear(); 270 } 271 272 /** 273 * Binds to the in-call app if not already connected by binding directly to the saved 274 * component name of the {@link IInCallService} implementation. 275 * 276 * @param call The newly added call that triggered the binding to the in-call services. 277 */ 278 private void bind(Call call) { 279 ThreadUtil.checkOnMainThread(); 280 if (mInCallServices.isEmpty()) { 281 PackageManager packageManager = mContext.getPackageManager(); 282 Intent serviceIntent = new Intent(InCallService.SERVICE_INTERFACE); 283 284 for (ResolveInfo entry : packageManager.queryIntentServices(serviceIntent, 0)) { 285 ServiceInfo serviceInfo = entry.serviceInfo; 286 if (serviceInfo != null) { 287 boolean hasServiceBindPermission = serviceInfo.permission != null && 288 serviceInfo.permission.equals( 289 Manifest.permission.BIND_INCALL_SERVICE); 290 boolean hasControlInCallPermission = packageManager.checkPermission( 291 Manifest.permission.CONTROL_INCALL_EXPERIENCE, 292 serviceInfo.packageName) == PackageManager.PERMISSION_GRANTED; 293 294 if (!hasServiceBindPermission) { 295 Log.w(this, "InCallService does not have BIND_INCALL_SERVICE permission: " + 296 serviceInfo.packageName); 297 continue; 298 } 299 300 if (!hasControlInCallPermission) { 301 Log.w(this, 302 "InCall UI does not have CONTROL_INCALL_EXPERIENCE permission: " + 303 serviceInfo.packageName); 304 continue; 305 } 306 307 InCallServiceConnection inCallServiceConnection = new InCallServiceConnection(); 308 ComponentName componentName = new ComponentName(serviceInfo.packageName, 309 serviceInfo.name); 310 311 Log.i(this, "Attempting to bind to InCall %s, is dupe? %b ", 312 serviceInfo.packageName, 313 mServiceConnections.containsKey(componentName)); 314 315 if (!mServiceConnections.containsKey(componentName)) { 316 Intent intent = new Intent(InCallService.SERVICE_INTERFACE); 317 intent.setComponent(componentName); 318 319 final int bindFlags; 320 if (mInCallComponentName.equals(componentName)) { 321 bindFlags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT; 322 if (!call.isIncoming()) { 323 intent.putExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, 324 call.getExtras()); 325 intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, 326 call.getTargetPhoneAccount()); 327 } 328 } else { 329 bindFlags = Context.BIND_AUTO_CREATE; 330 } 331 332 if (mContext.bindServiceAsUser(intent, inCallServiceConnection, bindFlags, 333 UserHandle.CURRENT)) { 334 mServiceConnections.put(componentName, inCallServiceConnection); 335 } 336 } 337 } 338 } 339 } 340 } 341 342 /** 343 * Persists the {@link IInCallService} instance and starts the communication between 344 * this class and in-call app by sending the first update to in-call app. This method is 345 * called after a successful binding connection is established. 346 * 347 * @param componentName The service {@link ComponentName}. 348 * @param service The {@link IInCallService} implementation. 349 */ 350 private void onConnected(ComponentName componentName, IBinder service) { 351 ThreadUtil.checkOnMainThread(); 352 Trace.beginSection("onConnected: " + componentName); 353 Log.i(this, "onConnected to %s", componentName); 354 355 IInCallService inCallService = IInCallService.Stub.asInterface(service); 356 357 try { 358 inCallService.setInCallAdapter( 359 new InCallAdapter( 360 TelecomSystem.getInstance().getCallsManager(), 361 mCallIdMapper)); 362 mInCallServices.put(componentName, inCallService); 363 } catch (RemoteException e) { 364 Log.e(this, e, "Failed to set the in-call adapter."); 365 Trace.endSection(); 366 return; 367 } 368 369 // Upon successful connection, send the state of the world to the service. 370 Collection<Call> calls = TelecomSystem.getInstance().getCallsManager().getCalls(); 371 if (!calls.isEmpty()) { 372 Log.i(this, "Adding %s calls to InCallService after onConnected: %s", calls.size(), 373 componentName); 374 for (Call call : calls) { 375 try { 376 // Track the call if we don't already know about it. 377 Log.i(this, "addCall after binding: %s", call); 378 addCall(call); 379 380 inCallService.addCall(toParcelableCall(call, 381 componentName.equals(mInCallComponentName) /* includeVideoProvider */)); 382 } catch (RemoteException ignored) { 383 } 384 } 385 onAudioStateChanged( 386 null, 387 TelecomSystem.getInstance().getCallsManager().getAudioState()); 388 onCanAddCallChanged(TelecomSystem.getInstance().getCallsManager().canAddCall()); 389 } else { 390 unbind(); 391 } 392 Trace.endSection(); 393 } 394 395 /** 396 * Cleans up an instance of in-call app after the service has been unbound. 397 * 398 * @param disconnectedComponent The {@link ComponentName} of the service which disconnected. 399 */ 400 private void onDisconnected(ComponentName disconnectedComponent) { 401 Log.i(this, "onDisconnected from %s", disconnectedComponent); 402 ThreadUtil.checkOnMainThread(); 403 404 if (mInCallServices.containsKey(disconnectedComponent)) { 405 mInCallServices.remove(disconnectedComponent); 406 } 407 408 if (mServiceConnections.containsKey(disconnectedComponent)) { 409 // One of the services that we were bound to has disconnected. If the default in-call UI 410 // has disconnected, disconnect all calls and un-bind all other InCallService 411 // implementations. 412 if (disconnectedComponent.equals(mInCallComponentName)) { 413 Log.i(this, "In-call UI %s disconnected.", disconnectedComponent); 414 TelecomSystem.getInstance().getCallsManager().disconnectAllCalls(); 415 unbind(); 416 } else { 417 Log.i(this, "In-Call Service %s suddenly disconnected", disconnectedComponent); 418 // Else, if it wasn't the default in-call UI, then one of the other in-call services 419 // disconnected and, well, that's probably their fault. Clear their state and 420 // ignore. 421 InCallServiceConnection serviceConnection = 422 mServiceConnections.get(disconnectedComponent); 423 424 // We still need to call unbind even though it disconnected. 425 mContext.unbindService(serviceConnection); 426 427 mServiceConnections.remove(disconnectedComponent); 428 mInCallServices.remove(disconnectedComponent); 429 } 430 } 431 } 432 433 /** 434 * Informs all {@link InCallService} instances of the updated call information. Changes to the 435 * video provider are only communicated to the default in-call UI. 436 * 437 * @param call The {@link Call}. 438 */ 439 private void updateCall(Call call) { 440 if (!mInCallServices.isEmpty()) { 441 for (Map.Entry<ComponentName, IInCallService> entry : mInCallServices.entrySet()) { 442 ComponentName componentName = entry.getKey(); 443 IInCallService inCallService = entry.getValue(); 444 ParcelableCall parcelableCall = toParcelableCall(call, 445 componentName.equals(mInCallComponentName) /* includeVideoProvider */); 446 Log.v(this, "updateCall %s ==> %s", call, parcelableCall); 447 try { 448 inCallService.updateCall(parcelableCall); 449 } catch (RemoteException ignored) { 450 } 451 } 452 } 453 } 454 455 /** 456 * Parcels all information for a {@link Call} into a new {@link ParcelableCall} instance. 457 * 458 * @param call The {@link Call} to parcel. 459 * @param includeVideoProvider When {@code true}, the {@link IVideoProvider} is included in the 460 * parceled call. When {@code false}, the {@link IVideoProvider} is not included. 461 * @return The {@link ParcelableCall} containing all call information from the {@link Call}. 462 */ 463 private ParcelableCall toParcelableCall(Call call, boolean includeVideoProvider) { 464 String callId = mCallIdMapper.getCallId(call); 465 466 int state = call.getState(); 467 int capabilities = convertConnectionToCallCapabilities(call.getConnectionCapabilities()); 468 469 // If this is a single-SIM device, the "default SIM" will always be the only SIM. 470 boolean isDefaultSmsAccount = 471 TelecomSystem.getInstance().getCallsManager().getPhoneAccountRegistrar() 472 .isUserSelectedSmsPhoneAccount(call.getTargetPhoneAccount()); 473 if (call.isRespondViaSmsCapable() && isDefaultSmsAccount) { 474 capabilities |= android.telecom.Call.Details.CAPABILITY_RESPOND_VIA_TEXT; 475 } 476 477 if (call.isEmergencyCall()) { 478 capabilities = removeCapability( 479 capabilities, android.telecom.Call.Details.CAPABILITY_MUTE); 480 } 481 482 if (state == CallState.DIALING) { 483 capabilities = removeCapability( 484 capabilities, android.telecom.Call.Details.CAPABILITY_SUPPORTS_VT_LOCAL); 485 capabilities = removeCapability( 486 capabilities, android.telecom.Call.Details.CAPABILITY_SUPPORTS_VT_REMOTE); 487 } 488 489 if (state == CallState.ABORTED) { 490 state = CallState.DISCONNECTED; 491 } 492 493 if (call.isLocallyDisconnecting() && state != CallState.DISCONNECTED) { 494 state = CallState.DISCONNECTING; 495 } 496 497 String parentCallId = null; 498 Call parentCall = call.getParentCall(); 499 if (parentCall != null) { 500 parentCallId = mCallIdMapper.getCallId(parentCall); 501 } 502 503 long connectTimeMillis = call.getConnectTimeMillis(); 504 List<Call> childCalls = call.getChildCalls(); 505 List<String> childCallIds = new ArrayList<>(); 506 if (!childCalls.isEmpty()) { 507 long childConnectTimeMillis = Long.MAX_VALUE; 508 for (Call child : childCalls) { 509 if (child.getConnectTimeMillis() > 0) { 510 childConnectTimeMillis = Math.min(child.getConnectTimeMillis(), 511 childConnectTimeMillis); 512 } 513 childCallIds.add(mCallIdMapper.getCallId(child)); 514 } 515 516 if (childConnectTimeMillis != Long.MAX_VALUE) { 517 connectTimeMillis = childConnectTimeMillis; 518 } 519 } 520 521 Uri handle = call.getHandlePresentation() == TelecomManager.PRESENTATION_ALLOWED ? 522 call.getHandle() : null; 523 String callerDisplayName = call.getCallerDisplayNamePresentation() == 524 TelecomManager.PRESENTATION_ALLOWED ? call.getCallerDisplayName() : null; 525 526 List<Call> conferenceableCalls = call.getConferenceableCalls(); 527 List<String> conferenceableCallIds = new ArrayList<String>(conferenceableCalls.size()); 528 for (Call otherCall : conferenceableCalls) { 529 String otherId = mCallIdMapper.getCallId(otherCall); 530 if (otherId != null) { 531 conferenceableCallIds.add(otherId); 532 } 533 } 534 535 int properties = call.isConference() ? CallProperties.CONFERENCE : 0; 536 return new ParcelableCall( 537 callId, 538 state, 539 call.getDisconnectCause(), 540 call.getCannedSmsResponses(), 541 capabilities, 542 properties, 543 connectTimeMillis, 544 handle, 545 call.getHandlePresentation(), 546 callerDisplayName, 547 call.getCallerDisplayNamePresentation(), 548 call.getGatewayInfo(), 549 call.getTargetPhoneAccount(), 550 includeVideoProvider ? call.getVideoProvider() : null, 551 parentCallId, 552 childCallIds, 553 call.getStatusHints(), 554 call.getVideoState(), 555 conferenceableCallIds, 556 call.getExtras()); 557 } 558 559 private static final int[] CONNECTION_TO_CALL_CAPABILITY = new int[] { 560 Connection.CAPABILITY_HOLD, 561 android.telecom.Call.Details.CAPABILITY_HOLD, 562 563 Connection.CAPABILITY_SUPPORT_HOLD, 564 android.telecom.Call.Details.CAPABILITY_SUPPORT_HOLD, 565 566 Connection.CAPABILITY_MERGE_CONFERENCE, 567 android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE, 568 569 Connection.CAPABILITY_SWAP_CONFERENCE, 570 android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE, 571 572 Connection.CAPABILITY_UNUSED, 573 android.telecom.Call.Details.CAPABILITY_UNUSED, 574 575 Connection.CAPABILITY_RESPOND_VIA_TEXT, 576 android.telecom.Call.Details.CAPABILITY_RESPOND_VIA_TEXT, 577 578 Connection.CAPABILITY_MUTE, 579 android.telecom.Call.Details.CAPABILITY_MUTE, 580 581 Connection.CAPABILITY_MANAGE_CONFERENCE, 582 android.telecom.Call.Details.CAPABILITY_MANAGE_CONFERENCE, 583 584 Connection.CAPABILITY_SUPPORTS_VT_LOCAL, 585 android.telecom.Call.Details.CAPABILITY_SUPPORTS_VT_LOCAL, 586 587 Connection.CAPABILITY_SUPPORTS_VT_REMOTE, 588 android.telecom.Call.Details.CAPABILITY_SUPPORTS_VT_REMOTE, 589 590 Connection.CAPABILITY_HIGH_DEF_AUDIO, 591 android.telecom.Call.Details.CAPABILITY_HIGH_DEF_AUDIO, 592 593 Connection.CAPABILITY_WIFI, 594 android.telecom.Call.Details.CAPABILITY_WIFI, 595 596 Connection.CAPABILITY_SEPARATE_FROM_CONFERENCE, 597 android.telecom.Call.Details.CAPABILITY_SEPARATE_FROM_CONFERENCE, 598 599 Connection.CAPABILITY_DISCONNECT_FROM_CONFERENCE, 600 android.telecom.Call.Details.CAPABILITY_DISCONNECT_FROM_CONFERENCE, 601 602 Connection.CAPABILITY_GENERIC_CONFERENCE, 603 android.telecom.Call.Details.CAPABILITY_GENERIC_CONFERENCE, 604 605 Connection.CAPABILITY_SHOW_CALLBACK_NUMBER, 606 android.telecom.Call.Details.CAPABILITY_SHOW_CALLBACK_NUMBER 607 }; 608 609 private static int convertConnectionToCallCapabilities(int connectionCapabilities) { 610 int callCapabilities = 0; 611 for (int i = 0; i < CONNECTION_TO_CALL_CAPABILITY.length; i += 2) { 612 if ((CONNECTION_TO_CALL_CAPABILITY[i] & connectionCapabilities) != 0) { 613 callCapabilities |= CONNECTION_TO_CALL_CAPABILITY[i + 1]; 614 } 615 } 616 return callCapabilities; 617 } 618 619 /** 620 * Adds the call to the list of calls tracked by the {@link InCallController}. 621 * @param call The call to add. 622 */ 623 private void addCall(Call call) { 624 if (mCallIdMapper.getCallId(call) == null) { 625 mCallIdMapper.addCall(call); 626 call.addListener(mCallListener); 627 } 628 } 629 630 /** 631 * Removes the specified capability from the set of capabilities bits and returns the new set. 632 */ 633 private static int removeCapability(int capabilities, int capability) { 634 return capabilities & ~capability; 635 } 636 637 /** 638 * Dumps the state of the {@link InCallController}. 639 * 640 * @param pw The {@code IndentingPrintWriter} to write the state to. 641 */ 642 public void dump(IndentingPrintWriter pw) { 643 pw.println("mInCallServices (InCalls registered):"); 644 pw.increaseIndent(); 645 for (ComponentName componentName : mInCallServices.keySet()) { 646 pw.println(componentName); 647 } 648 pw.decreaseIndent(); 649 650 pw.println("mServiceConnections (InCalls bound):"); 651 pw.increaseIndent(); 652 for (ComponentName componentName : mServiceConnections.keySet()) { 653 pw.println(componentName); 654 } 655 pw.decreaseIndent(); 656 } 657} 658