ConnectionService.java revision 6b3db37f3cced17af107d452799f700f3cc56754
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 android.telecom; 18 19import android.annotation.SdkConstant; 20import android.app.Service; 21import android.content.ComponentName; 22import android.content.Intent; 23import android.net.Uri; 24import android.os.Bundle; 25import android.os.Handler; 26import android.os.IBinder; 27import android.os.Looper; 28import android.os.Message; 29 30import com.android.internal.os.SomeArgs; 31import com.android.internal.telecom.IConnectionService; 32import com.android.internal.telecom.IConnectionServiceAdapter; 33import com.android.internal.telecom.RemoteServiceCallback; 34 35import java.util.ArrayList; 36import java.util.Collection; 37import java.util.Collections; 38import java.util.List; 39import java.util.Map; 40import java.util.UUID; 41import java.util.concurrent.ConcurrentHashMap; 42 43/** 44 * An abstract service that should be implemented by any apps which can make phone calls (VoIP or 45 * otherwise) and want those calls to be integrated into the built-in phone app. 46 * Once implemented, the {@code ConnectionService} needs two additional steps before it will be 47 * integrated into the phone app: 48 * <p> 49 * 1. <i>Registration in AndroidManifest.xml</i> 50 * <br/> 51 * <pre> 52 * <service android:name="com.example.package.MyConnectionService" 53 * android:label="@string/some_label_for_my_connection_service" 54 * android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE"> 55 * <intent-filter> 56 * <action android:name="android.telecom.ConnectionService" /> 57 * </intent-filter> 58 * </service> 59 * </pre> 60 * <p> 61 * 2. <i> Registration of {@link PhoneAccount} with {@link TelecomManager}.</i> 62 * <br/> 63 * See {@link PhoneAccount} and {@link TelecomManager#registerPhoneAccount} for more information. 64 * <p> 65 * Once registered and enabled by the user in the phone app settings, telecom will bind to a 66 * {@code ConnectionService} implementation when it wants that {@code ConnectionService} to place 67 * a call or the service has indicated that is has an incoming call through 68 * {@link TelecomManager#addNewIncomingCall}. The {@code ConnectionService} can then expect a call 69 * to {@link #onCreateIncomingConnection} or {@link #onCreateOutgoingConnection} wherein it 70 * should provide a new instance of a {@link Connection} object. It is through this 71 * {@link Connection} object that telecom receives state updates and the {@code ConnectionService} 72 * receives call-commands such as answer, reject, hold and disconnect. 73 * <p> 74 * When there are no more live calls, telecom will unbind from the {@code ConnectionService}. 75 */ 76public abstract class ConnectionService extends Service { 77 /** 78 * The {@link Intent} that must be declared as handled by the service. 79 */ 80 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION) 81 public static final String SERVICE_INTERFACE = "android.telecom.ConnectionService"; 82 83 // Flag controlling whether PII is emitted into the logs 84 private static final boolean PII_DEBUG = Log.isLoggable(android.util.Log.DEBUG); 85 86 private static final int MSG_ADD_CONNECTION_SERVICE_ADAPTER = 1; 87 private static final int MSG_CREATE_CONNECTION = 2; 88 private static final int MSG_ABORT = 3; 89 private static final int MSG_ANSWER = 4; 90 private static final int MSG_REJECT = 5; 91 private static final int MSG_DISCONNECT = 6; 92 private static final int MSG_HOLD = 7; 93 private static final int MSG_UNHOLD = 8; 94 private static final int MSG_ON_CALL_AUDIO_STATE_CHANGED = 9; 95 private static final int MSG_PLAY_DTMF_TONE = 10; 96 private static final int MSG_STOP_DTMF_TONE = 11; 97 private static final int MSG_CONFERENCE = 12; 98 private static final int MSG_SPLIT_FROM_CONFERENCE = 13; 99 private static final int MSG_ON_POST_DIAL_CONTINUE = 14; 100 private static final int MSG_REMOVE_CONNECTION_SERVICE_ADAPTER = 16; 101 private static final int MSG_ANSWER_VIDEO = 17; 102 private static final int MSG_MERGE_CONFERENCE = 18; 103 private static final int MSG_SWAP_CONFERENCE = 19; 104 private static final int MSG_REJECT_WITH_MESSAGE = 20; 105 106 private static Connection sNullConnection; 107 108 private final Map<String, Connection> mConnectionById = new ConcurrentHashMap<>(); 109 private final Map<Connection, String> mIdByConnection = new ConcurrentHashMap<>(); 110 private final Map<String, Conference> mConferenceById = new ConcurrentHashMap<>(); 111 private final Map<Conference, String> mIdByConference = new ConcurrentHashMap<>(); 112 private final RemoteConnectionManager mRemoteConnectionManager = 113 new RemoteConnectionManager(this); 114 private final List<Runnable> mPreInitializationConnectionRequests = new ArrayList<>(); 115 private final ConnectionServiceAdapter mAdapter = new ConnectionServiceAdapter(); 116 117 private boolean mAreAccountsInitialized = false; 118 private Conference sNullConference; 119 private Object mIdSyncRoot = new Object(); 120 private int mId = 0; 121 122 private final IBinder mBinder = new IConnectionService.Stub() { 123 @Override 124 public void addConnectionServiceAdapter(IConnectionServiceAdapter adapter) { 125 mHandler.obtainMessage(MSG_ADD_CONNECTION_SERVICE_ADAPTER, adapter).sendToTarget(); 126 } 127 128 public void removeConnectionServiceAdapter(IConnectionServiceAdapter adapter) { 129 mHandler.obtainMessage(MSG_REMOVE_CONNECTION_SERVICE_ADAPTER, adapter).sendToTarget(); 130 } 131 132 @Override 133 public void createConnection( 134 PhoneAccountHandle connectionManagerPhoneAccount, 135 String id, 136 ConnectionRequest request, 137 boolean isIncoming, 138 boolean isUnknown) { 139 SomeArgs args = SomeArgs.obtain(); 140 args.arg1 = connectionManagerPhoneAccount; 141 args.arg2 = id; 142 args.arg3 = request; 143 args.argi1 = isIncoming ? 1 : 0; 144 args.argi2 = isUnknown ? 1 : 0; 145 mHandler.obtainMessage(MSG_CREATE_CONNECTION, args).sendToTarget(); 146 } 147 148 @Override 149 public void abort(String callId) { 150 mHandler.obtainMessage(MSG_ABORT, callId).sendToTarget(); 151 } 152 153 @Override 154 public void answerVideo(String callId, int videoState) { 155 SomeArgs args = SomeArgs.obtain(); 156 args.arg1 = callId; 157 args.argi1 = videoState; 158 mHandler.obtainMessage(MSG_ANSWER_VIDEO, args).sendToTarget(); 159 } 160 161 @Override 162 public void answer(String callId) { 163 mHandler.obtainMessage(MSG_ANSWER, callId).sendToTarget(); 164 } 165 166 @Override 167 public void reject(String callId) { 168 mHandler.obtainMessage(MSG_REJECT, callId).sendToTarget(); 169 } 170 171 @Override 172 public void rejectWithMessage(String callId, String message) { 173 SomeArgs args = SomeArgs.obtain(); 174 args.arg1 = callId; 175 args.arg2 = message; 176 mHandler.obtainMessage(MSG_REJECT_WITH_MESSAGE, args).sendToTarget(); 177 } 178 179 @Override 180 public void disconnect(String callId) { 181 mHandler.obtainMessage(MSG_DISCONNECT, callId).sendToTarget(); 182 } 183 184 @Override 185 public void hold(String callId) { 186 mHandler.obtainMessage(MSG_HOLD, callId).sendToTarget(); 187 } 188 189 @Override 190 public void unhold(String callId) { 191 mHandler.obtainMessage(MSG_UNHOLD, callId).sendToTarget(); 192 } 193 194 @Override 195 public void onCallAudioStateChanged(String callId, CallAudioState callAudioState) { 196 SomeArgs args = SomeArgs.obtain(); 197 args.arg1 = callId; 198 args.arg2 = callAudioState; 199 mHandler.obtainMessage(MSG_ON_CALL_AUDIO_STATE_CHANGED, args).sendToTarget(); 200 } 201 202 @Override 203 public void playDtmfTone(String callId, char digit) { 204 mHandler.obtainMessage(MSG_PLAY_DTMF_TONE, digit, 0, callId).sendToTarget(); 205 } 206 207 @Override 208 public void stopDtmfTone(String callId) { 209 mHandler.obtainMessage(MSG_STOP_DTMF_TONE, callId).sendToTarget(); 210 } 211 212 @Override 213 public void conference(String callId1, String callId2) { 214 SomeArgs args = SomeArgs.obtain(); 215 args.arg1 = callId1; 216 args.arg2 = callId2; 217 mHandler.obtainMessage(MSG_CONFERENCE, args).sendToTarget(); 218 } 219 220 @Override 221 public void splitFromConference(String callId) { 222 mHandler.obtainMessage(MSG_SPLIT_FROM_CONFERENCE, callId).sendToTarget(); 223 } 224 225 @Override 226 public void mergeConference(String callId) { 227 mHandler.obtainMessage(MSG_MERGE_CONFERENCE, callId).sendToTarget(); 228 } 229 230 @Override 231 public void swapConference(String callId) { 232 mHandler.obtainMessage(MSG_SWAP_CONFERENCE, callId).sendToTarget(); 233 } 234 235 @Override 236 public void onPostDialContinue(String callId, boolean proceed) { 237 SomeArgs args = SomeArgs.obtain(); 238 args.arg1 = callId; 239 args.argi1 = proceed ? 1 : 0; 240 mHandler.obtainMessage(MSG_ON_POST_DIAL_CONTINUE, args).sendToTarget(); 241 } 242 }; 243 244 private final Handler mHandler = new Handler(Looper.getMainLooper()) { 245 @Override 246 public void handleMessage(Message msg) { 247 switch (msg.what) { 248 case MSG_ADD_CONNECTION_SERVICE_ADAPTER: 249 mAdapter.addAdapter((IConnectionServiceAdapter) msg.obj); 250 onAdapterAttached(); 251 break; 252 case MSG_REMOVE_CONNECTION_SERVICE_ADAPTER: 253 mAdapter.removeAdapter((IConnectionServiceAdapter) msg.obj); 254 break; 255 case MSG_CREATE_CONNECTION: { 256 SomeArgs args = (SomeArgs) msg.obj; 257 try { 258 final PhoneAccountHandle connectionManagerPhoneAccount = 259 (PhoneAccountHandle) args.arg1; 260 final String id = (String) args.arg2; 261 final ConnectionRequest request = (ConnectionRequest) args.arg3; 262 final boolean isIncoming = args.argi1 == 1; 263 final boolean isUnknown = args.argi2 == 1; 264 if (!mAreAccountsInitialized) { 265 Log.d(this, "Enqueueing pre-init request %s", id); 266 mPreInitializationConnectionRequests.add(new Runnable() { 267 @Override 268 public void run() { 269 createConnection( 270 connectionManagerPhoneAccount, 271 id, 272 request, 273 isIncoming, 274 isUnknown); 275 } 276 }); 277 } else { 278 createConnection( 279 connectionManagerPhoneAccount, 280 id, 281 request, 282 isIncoming, 283 isUnknown); 284 } 285 } finally { 286 args.recycle(); 287 } 288 break; 289 } 290 case MSG_ABORT: 291 abort((String) msg.obj); 292 break; 293 case MSG_ANSWER: 294 answer((String) msg.obj); 295 break; 296 case MSG_ANSWER_VIDEO: { 297 SomeArgs args = (SomeArgs) msg.obj; 298 try { 299 String callId = (String) args.arg1; 300 int videoState = args.argi1; 301 answerVideo(callId, videoState); 302 } finally { 303 args.recycle(); 304 } 305 break; 306 } 307 case MSG_REJECT: 308 reject((String) msg.obj); 309 break; 310 case MSG_REJECT_WITH_MESSAGE: { 311 SomeArgs args = (SomeArgs) msg.obj; 312 try { 313 reject((String) args.arg1, (String) args.arg2); 314 } finally { 315 args.recycle(); 316 } 317 break; 318 } 319 case MSG_DISCONNECT: 320 disconnect((String) msg.obj); 321 break; 322 case MSG_HOLD: 323 hold((String) msg.obj); 324 break; 325 case MSG_UNHOLD: 326 unhold((String) msg.obj); 327 break; 328 case MSG_ON_CALL_AUDIO_STATE_CHANGED: { 329 SomeArgs args = (SomeArgs) msg.obj; 330 try { 331 String callId = (String) args.arg1; 332 CallAudioState audioState = (CallAudioState) args.arg2; 333 onCallAudioStateChanged(callId, new CallAudioState(audioState)); 334 } finally { 335 args.recycle(); 336 } 337 break; 338 } 339 case MSG_PLAY_DTMF_TONE: 340 playDtmfTone((String) msg.obj, (char) msg.arg1); 341 break; 342 case MSG_STOP_DTMF_TONE: 343 stopDtmfTone((String) msg.obj); 344 break; 345 case MSG_CONFERENCE: { 346 SomeArgs args = (SomeArgs) msg.obj; 347 try { 348 String callId1 = (String) args.arg1; 349 String callId2 = (String) args.arg2; 350 conference(callId1, callId2); 351 } finally { 352 args.recycle(); 353 } 354 break; 355 } 356 case MSG_SPLIT_FROM_CONFERENCE: 357 splitFromConference((String) msg.obj); 358 break; 359 case MSG_MERGE_CONFERENCE: 360 mergeConference((String) msg.obj); 361 break; 362 case MSG_SWAP_CONFERENCE: 363 swapConference((String) msg.obj); 364 break; 365 case MSG_ON_POST_DIAL_CONTINUE: { 366 SomeArgs args = (SomeArgs) msg.obj; 367 try { 368 String callId = (String) args.arg1; 369 boolean proceed = (args.argi1 == 1); 370 onPostDialContinue(callId, proceed); 371 } finally { 372 args.recycle(); 373 } 374 break; 375 } 376 default: 377 break; 378 } 379 } 380 }; 381 382 private final Conference.Listener mConferenceListener = new Conference.Listener() { 383 @Override 384 public void onStateChanged(Conference conference, int oldState, int newState) { 385 String id = mIdByConference.get(conference); 386 switch (newState) { 387 case Connection.STATE_ACTIVE: 388 mAdapter.setActive(id); 389 break; 390 case Connection.STATE_HOLDING: 391 mAdapter.setOnHold(id); 392 break; 393 case Connection.STATE_DISCONNECTED: 394 // handled by onDisconnected 395 break; 396 } 397 } 398 399 @Override 400 public void onDisconnected(Conference conference, DisconnectCause disconnectCause) { 401 String id = mIdByConference.get(conference); 402 mAdapter.setDisconnected(id, disconnectCause); 403 } 404 405 @Override 406 public void onConnectionAdded(Conference conference, Connection connection) { 407 } 408 409 @Override 410 public void onConnectionRemoved(Conference conference, Connection connection) { 411 } 412 413 @Override 414 public void onConferenceableConnectionsChanged( 415 Conference conference, List<Connection> conferenceableConnections) { 416 mAdapter.setConferenceableConnections( 417 mIdByConference.get(conference), 418 createConnectionIdList(conferenceableConnections)); 419 } 420 421 @Override 422 public void onDestroyed(Conference conference) { 423 removeConference(conference); 424 } 425 426 @Override 427 public void onConnectionCapabilitiesChanged( 428 Conference conference, 429 int connectionCapabilities) { 430 String id = mIdByConference.get(conference); 431 Log.d(this, "call capabilities: conference: %s", 432 Connection.capabilitiesToString(connectionCapabilities)); 433 mAdapter.setConnectionCapabilities(id, connectionCapabilities); 434 } 435 436 @Override 437 public void onVideoStateChanged(Conference c, int videoState) { 438 String id = mIdByConference.get(c); 439 Log.d(this, "onVideoStateChanged set video state %d", videoState); 440 mAdapter.setVideoState(id, videoState); 441 } 442 443 @Override 444 public void onVideoProviderChanged(Conference c, Connection.VideoProvider videoProvider) { 445 String id = mIdByConference.get(c); 446 Log.d(this, "onVideoProviderChanged: Connection: %s, VideoProvider: %s", c, 447 videoProvider); 448 mAdapter.setVideoProvider(id, videoProvider); 449 } 450 451 @Override 452 public void onStatusHintsChanged(Conference conference, StatusHints statusHints) { 453 String id = mIdByConference.get(conference); 454 mAdapter.setStatusHints(id, statusHints); 455 } 456 457 @Override 458 public void onExtrasChanged(Conference conference, Bundle extras) { 459 String id = mIdByConference.get(conference); 460 mAdapter.setExtras(id, extras); 461 } 462 }; 463 464 private final Connection.Listener mConnectionListener = new Connection.Listener() { 465 @Override 466 public void onStateChanged(Connection c, int state) { 467 String id = mIdByConnection.get(c); 468 Log.d(this, "Adapter set state %s %s", id, Connection.stateToString(state)); 469 switch (state) { 470 case Connection.STATE_ACTIVE: 471 mAdapter.setActive(id); 472 break; 473 case Connection.STATE_DIALING: 474 mAdapter.setDialing(id); 475 break; 476 case Connection.STATE_DISCONNECTED: 477 // Handled in onDisconnected() 478 break; 479 case Connection.STATE_HOLDING: 480 mAdapter.setOnHold(id); 481 break; 482 case Connection.STATE_NEW: 483 // Nothing to tell Telecom 484 break; 485 case Connection.STATE_RINGING: 486 mAdapter.setRinging(id); 487 break; 488 } 489 } 490 491 @Override 492 public void onDisconnected(Connection c, DisconnectCause disconnectCause) { 493 String id = mIdByConnection.get(c); 494 Log.d(this, "Adapter set disconnected %s", disconnectCause); 495 mAdapter.setDisconnected(id, disconnectCause); 496 } 497 498 @Override 499 public void onVideoStateChanged(Connection c, int videoState) { 500 String id = mIdByConnection.get(c); 501 Log.d(this, "Adapter set video state %d", videoState); 502 mAdapter.setVideoState(id, videoState); 503 } 504 505 @Override 506 public void onAddressChanged(Connection c, Uri address, int presentation) { 507 String id = mIdByConnection.get(c); 508 mAdapter.setAddress(id, address, presentation); 509 } 510 511 @Override 512 public void onCallerDisplayNameChanged( 513 Connection c, String callerDisplayName, int presentation) { 514 String id = mIdByConnection.get(c); 515 mAdapter.setCallerDisplayName(id, callerDisplayName, presentation); 516 } 517 518 @Override 519 public void onDestroyed(Connection c) { 520 removeConnection(c); 521 } 522 523 @Override 524 public void onPostDialWait(Connection c, String remaining) { 525 String id = mIdByConnection.get(c); 526 Log.d(this, "Adapter onPostDialWait %s, %s", c, remaining); 527 mAdapter.onPostDialWait(id, remaining); 528 } 529 530 @Override 531 public void onPostDialChar(Connection c, char nextChar) { 532 String id = mIdByConnection.get(c); 533 Log.d(this, "Adapter onPostDialChar %s, %s", c, nextChar); 534 mAdapter.onPostDialChar(id, nextChar); 535 } 536 537 @Override 538 public void onRingbackRequested(Connection c, boolean ringback) { 539 String id = mIdByConnection.get(c); 540 Log.d(this, "Adapter onRingback %b", ringback); 541 mAdapter.setRingbackRequested(id, ringback); 542 } 543 544 @Override 545 public void onConnectionCapabilitiesChanged(Connection c, int capabilities) { 546 String id = mIdByConnection.get(c); 547 Log.d(this, "capabilities: parcelableconnection: %s", 548 Connection.capabilitiesToString(capabilities)); 549 mAdapter.setConnectionCapabilities(id, capabilities); 550 } 551 552 @Override 553 public void onVideoProviderChanged(Connection c, Connection.VideoProvider videoProvider) { 554 String id = mIdByConnection.get(c); 555 Log.d(this, "onVideoProviderChanged: Connection: %s, VideoProvider: %s", c, 556 videoProvider); 557 mAdapter.setVideoProvider(id, videoProvider); 558 } 559 560 @Override 561 public void onAudioModeIsVoipChanged(Connection c, boolean isVoip) { 562 String id = mIdByConnection.get(c); 563 mAdapter.setIsVoipAudioMode(id, isVoip); 564 } 565 566 @Override 567 public void onStatusHintsChanged(Connection c, StatusHints statusHints) { 568 String id = mIdByConnection.get(c); 569 mAdapter.setStatusHints(id, statusHints); 570 } 571 572 @Override 573 public void onConferenceablesChanged( 574 Connection connection, List<Conferenceable> conferenceables) { 575 mAdapter.setConferenceableConnections( 576 mIdByConnection.get(connection), 577 createIdList(conferenceables)); 578 } 579 580 @Override 581 public void onConferenceChanged(Connection connection, Conference conference) { 582 String id = mIdByConnection.get(connection); 583 if (id != null) { 584 String conferenceId = null; 585 if (conference != null) { 586 conferenceId = mIdByConference.get(conference); 587 } 588 mAdapter.setIsConferenced(id, conferenceId); 589 } 590 } 591 592 @Override 593 public void onConferenceMergeFailed(Connection connection) { 594 String id = mIdByConnection.get(connection); 595 if (id != null) { 596 mAdapter.onConferenceMergeFailed(id); 597 } 598 } 599 600 @Override 601 public void onExtrasChanged(Connection connection, Bundle extras) { 602 String id = mIdByConnection.get(connection); 603 if (id != null) { 604 mAdapter.setExtras(id, extras); 605 } 606 } 607 }; 608 609 /** {@inheritDoc} */ 610 @Override 611 public final IBinder onBind(Intent intent) { 612 return mBinder; 613 } 614 615 /** {@inheritDoc} */ 616 @Override 617 public boolean onUnbind(Intent intent) { 618 endAllConnections(); 619 return super.onUnbind(intent); 620 } 621 622 /** 623 * This can be used by telecom to either create a new outgoing call or attach to an existing 624 * incoming call. In either case, telecom will cycle through a set of services and call 625 * createConnection util a connection service cancels the process or completes it successfully. 626 */ 627 private void createConnection( 628 final PhoneAccountHandle callManagerAccount, 629 final String callId, 630 final ConnectionRequest request, 631 boolean isIncoming, 632 boolean isUnknown) { 633 Log.d(this, "createConnection, callManagerAccount: %s, callId: %s, request: %s, " + 634 "isIncoming: %b, isUnknown: %b", callManagerAccount, callId, request, 635 isIncoming, 636 isUnknown); 637 638 Connection connection = isUnknown ? onCreateUnknownConnection(callManagerAccount, request) 639 : isIncoming ? onCreateIncomingConnection(callManagerAccount, request) 640 : onCreateOutgoingConnection(callManagerAccount, request); 641 Log.d(this, "createConnection, connection: %s", connection); 642 if (connection == null) { 643 connection = Connection.createFailedConnection( 644 new DisconnectCause(DisconnectCause.ERROR)); 645 } 646 647 connection.setTelecomCallId(callId); 648 if (connection.getState() != Connection.STATE_DISCONNECTED) { 649 addConnection(callId, connection); 650 } 651 652 Uri address = connection.getAddress(); 653 String number = address == null ? "null" : address.getSchemeSpecificPart(); 654 Log.v(this, "createConnection, number: %s, state: %s, capabilities: %s", 655 Connection.toLogSafePhoneNumber(number), 656 Connection.stateToString(connection.getState()), 657 Connection.capabilitiesToString(connection.getConnectionCapabilities())); 658 659 Log.d(this, "createConnection, calling handleCreateConnectionSuccessful %s", callId); 660 mAdapter.handleCreateConnectionComplete( 661 callId, 662 request, 663 new ParcelableConnection( 664 request.getAccountHandle(), 665 connection.getState(), 666 connection.getConnectionCapabilities(), 667 connection.getAddress(), 668 connection.getAddressPresentation(), 669 connection.getCallerDisplayName(), 670 connection.getCallerDisplayNamePresentation(), 671 connection.getVideoProvider() == null ? 672 null : connection.getVideoProvider().getInterface(), 673 connection.getVideoState(), 674 connection.isRingbackRequested(), 675 connection.getAudioModeIsVoip(), 676 connection.getConnectTimeMillis(), 677 connection.getStatusHints(), 678 connection.getDisconnectCause(), 679 createIdList(connection.getConferenceables()), 680 connection.getExtras())); 681 if (isUnknown) { 682 triggerConferenceRecalculate(); 683 } 684 } 685 686 private void abort(String callId) { 687 Log.d(this, "abort %s", callId); 688 findConnectionForAction(callId, "abort").onAbort(); 689 } 690 691 private void answerVideo(String callId, int videoState) { 692 Log.d(this, "answerVideo %s", callId); 693 findConnectionForAction(callId, "answer").onAnswer(videoState); 694 } 695 696 private void answer(String callId) { 697 Log.d(this, "answer %s", callId); 698 findConnectionForAction(callId, "answer").onAnswer(); 699 } 700 701 private void reject(String callId) { 702 Log.d(this, "reject %s", callId); 703 findConnectionForAction(callId, "reject").onReject(); 704 } 705 706 private void reject(String callId, String rejectWithMessage) { 707 Log.d(this, "reject %s with message", callId); 708 findConnectionForAction(callId, "reject").onReject(rejectWithMessage); 709 } 710 711 private void disconnect(String callId) { 712 Log.d(this, "disconnect %s", callId); 713 if (mConnectionById.containsKey(callId)) { 714 findConnectionForAction(callId, "disconnect").onDisconnect(); 715 } else { 716 findConferenceForAction(callId, "disconnect").onDisconnect(); 717 } 718 } 719 720 private void hold(String callId) { 721 Log.d(this, "hold %s", callId); 722 if (mConnectionById.containsKey(callId)) { 723 findConnectionForAction(callId, "hold").onHold(); 724 } else { 725 findConferenceForAction(callId, "hold").onHold(); 726 } 727 } 728 729 private void unhold(String callId) { 730 Log.d(this, "unhold %s", callId); 731 if (mConnectionById.containsKey(callId)) { 732 findConnectionForAction(callId, "unhold").onUnhold(); 733 } else { 734 findConferenceForAction(callId, "unhold").onUnhold(); 735 } 736 } 737 738 private void onCallAudioStateChanged(String callId, CallAudioState callAudioState) { 739 Log.d(this, "onAudioStateChanged %s %s", callId, callAudioState); 740 if (mConnectionById.containsKey(callId)) { 741 findConnectionForAction(callId, "onCallAudioStateChanged").setCallAudioState( 742 callAudioState); 743 } else { 744 findConferenceForAction(callId, "onCallAudioStateChanged").setCallAudioState( 745 callAudioState); 746 } 747 } 748 749 private void playDtmfTone(String callId, char digit) { 750 Log.d(this, "playDtmfTone %s %c", callId, digit); 751 if (mConnectionById.containsKey(callId)) { 752 findConnectionForAction(callId, "playDtmfTone").onPlayDtmfTone(digit); 753 } else { 754 findConferenceForAction(callId, "playDtmfTone").onPlayDtmfTone(digit); 755 } 756 } 757 758 private void stopDtmfTone(String callId) { 759 Log.d(this, "stopDtmfTone %s", callId); 760 if (mConnectionById.containsKey(callId)) { 761 findConnectionForAction(callId, "stopDtmfTone").onStopDtmfTone(); 762 } else { 763 findConferenceForAction(callId, "stopDtmfTone").onStopDtmfTone(); 764 } 765 } 766 767 private void conference(String callId1, String callId2) { 768 Log.d(this, "conference %s, %s", callId1, callId2); 769 770 // Attempt to get second connection or conference. 771 Connection connection2 = findConnectionForAction(callId2, "conference"); 772 Conference conference2 = getNullConference(); 773 if (connection2 == getNullConnection()) { 774 conference2 = findConferenceForAction(callId2, "conference"); 775 if (conference2 == getNullConference()) { 776 Log.w(this, "Connection2 or Conference2 missing in conference request %s.", 777 callId2); 778 return; 779 } 780 } 781 782 // Attempt to get first connection or conference and perform merge. 783 Connection connection1 = findConnectionForAction(callId1, "conference"); 784 if (connection1 == getNullConnection()) { 785 Conference conference1 = findConferenceForAction(callId1, "addConnection"); 786 if (conference1 == getNullConference()) { 787 Log.w(this, 788 "Connection1 or Conference1 missing in conference request %s.", 789 callId1); 790 } else { 791 // Call 1 is a conference. 792 if (connection2 != getNullConnection()) { 793 // Call 2 is a connection so merge via call 1 (conference). 794 conference1.onMerge(connection2); 795 } else { 796 // Call 2 is ALSO a conference; this should never happen. 797 Log.wtf(this, "There can only be one conference and an attempt was made to " + 798 "merge two conferences."); 799 return; 800 } 801 } 802 } else { 803 // Call 1 is a connection. 804 if (conference2 != getNullConference()) { 805 // Call 2 is a conference, so merge via call 2. 806 conference2.onMerge(connection1); 807 } else { 808 // Call 2 is a connection, so merge together. 809 onConference(connection1, connection2); 810 } 811 } 812 } 813 814 private void splitFromConference(String callId) { 815 Log.d(this, "splitFromConference(%s)", callId); 816 817 Connection connection = findConnectionForAction(callId, "splitFromConference"); 818 if (connection == getNullConnection()) { 819 Log.w(this, "Connection missing in conference request %s.", callId); 820 return; 821 } 822 823 Conference conference = connection.getConference(); 824 if (conference != null) { 825 conference.onSeparate(connection); 826 } 827 } 828 829 private void mergeConference(String callId) { 830 Log.d(this, "mergeConference(%s)", callId); 831 Conference conference = findConferenceForAction(callId, "mergeConference"); 832 if (conference != null) { 833 conference.onMerge(); 834 } 835 } 836 837 private void swapConference(String callId) { 838 Log.d(this, "swapConference(%s)", callId); 839 Conference conference = findConferenceForAction(callId, "swapConference"); 840 if (conference != null) { 841 conference.onSwap(); 842 } 843 } 844 845 private void onPostDialContinue(String callId, boolean proceed) { 846 Log.d(this, "onPostDialContinue(%s)", callId); 847 findConnectionForAction(callId, "stopDtmfTone").onPostDialContinue(proceed); 848 } 849 850 private void onAdapterAttached() { 851 if (mAreAccountsInitialized) { 852 // No need to query again if we already did it. 853 return; 854 } 855 856 mAdapter.queryRemoteConnectionServices(new RemoteServiceCallback.Stub() { 857 @Override 858 public void onResult( 859 final List<ComponentName> componentNames, 860 final List<IBinder> services) { 861 mHandler.post(new Runnable() { 862 @Override 863 public void run() { 864 for (int i = 0; i < componentNames.size() && i < services.size(); i++) { 865 mRemoteConnectionManager.addConnectionService( 866 componentNames.get(i), 867 IConnectionService.Stub.asInterface(services.get(i))); 868 } 869 onAccountsInitialized(); 870 Log.d(this, "remote connection services found: " + services); 871 } 872 }); 873 } 874 875 @Override 876 public void onError() { 877 mHandler.post(new Runnable() { 878 @Override 879 public void run() { 880 mAreAccountsInitialized = true; 881 } 882 }); 883 } 884 }); 885 } 886 887 /** 888 * Ask some other {@code ConnectionService} to create a {@code RemoteConnection} given an 889 * incoming request. This is used by {@code ConnectionService}s that are registered with 890 * {@link PhoneAccount#CAPABILITY_CONNECTION_MANAGER} and want to be able to manage 891 * SIM-based incoming calls. 892 * 893 * @param connectionManagerPhoneAccount See description at 894 * {@link #onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}. 895 * @param request Details about the incoming call. 896 * @return The {@code Connection} object to satisfy this call, or {@code null} to 897 * not handle the call. 898 */ 899 public final RemoteConnection createRemoteIncomingConnection( 900 PhoneAccountHandle connectionManagerPhoneAccount, 901 ConnectionRequest request) { 902 return mRemoteConnectionManager.createRemoteConnection( 903 connectionManagerPhoneAccount, request, true); 904 } 905 906 /** 907 * Ask some other {@code ConnectionService} to create a {@code RemoteConnection} given an 908 * outgoing request. This is used by {@code ConnectionService}s that are registered with 909 * {@link PhoneAccount#CAPABILITY_CONNECTION_MANAGER} and want to be able to use the 910 * SIM-based {@code ConnectionService} to place its outgoing calls. 911 * 912 * @param connectionManagerPhoneAccount See description at 913 * {@link #onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}. 914 * @param request Details about the incoming call. 915 * @return The {@code Connection} object to satisfy this call, or {@code null} to 916 * not handle the call. 917 */ 918 public final RemoteConnection createRemoteOutgoingConnection( 919 PhoneAccountHandle connectionManagerPhoneAccount, 920 ConnectionRequest request) { 921 return mRemoteConnectionManager.createRemoteConnection( 922 connectionManagerPhoneAccount, request, false); 923 } 924 925 /** 926 * Indicates to the relevant {@code RemoteConnectionService} that the specified 927 * {@link RemoteConnection}s should be merged into a conference call. 928 * <p> 929 * If the conference request is successful, the method {@link #onRemoteConferenceAdded} will 930 * be invoked. 931 * 932 * @param remoteConnection1 The first of the remote connections to conference. 933 * @param remoteConnection2 The second of the remote connections to conference. 934 */ 935 public final void conferenceRemoteConnections( 936 RemoteConnection remoteConnection1, 937 RemoteConnection remoteConnection2) { 938 mRemoteConnectionManager.conferenceRemoteConnections(remoteConnection1, remoteConnection2); 939 } 940 941 /** 942 * Adds a new conference call. When a conference call is created either as a result of an 943 * explicit request via {@link #onConference} or otherwise, the connection service should supply 944 * an instance of {@link Conference} by invoking this method. A conference call provided by this 945 * method will persist until {@link Conference#destroy} is invoked on the conference instance. 946 * 947 * @param conference The new conference object. 948 */ 949 public final void addConference(Conference conference) { 950 Log.d(this, "addConference: conference=%s", conference); 951 952 String id = addConferenceInternal(conference); 953 if (id != null) { 954 List<String> connectionIds = new ArrayList<>(2); 955 for (Connection connection : conference.getConnections()) { 956 if (mIdByConnection.containsKey(connection)) { 957 connectionIds.add(mIdByConnection.get(connection)); 958 } 959 } 960 conference.setTelecomCallId(id); 961 ParcelableConference parcelableConference = new ParcelableConference( 962 conference.getPhoneAccountHandle(), 963 conference.getState(), 964 conference.getConnectionCapabilities(), 965 connectionIds, 966 conference.getVideoProvider() == null ? 967 null : conference.getVideoProvider().getInterface(), 968 conference.getVideoState(), 969 conference.getConnectTimeMillis(), 970 conference.getStatusHints(), 971 conference.getExtras()); 972 973 mAdapter.addConferenceCall(id, parcelableConference); 974 mAdapter.setVideoProvider(id, conference.getVideoProvider()); 975 mAdapter.setVideoState(id, conference.getVideoState()); 976 977 // Go through any child calls and set the parent. 978 for (Connection connection : conference.getConnections()) { 979 String connectionId = mIdByConnection.get(connection); 980 if (connectionId != null) { 981 mAdapter.setIsConferenced(connectionId, id); 982 } 983 } 984 } 985 } 986 987 /** 988 * Adds a connection created by the {@link ConnectionService} and informs telecom of the new 989 * connection. 990 * 991 * @param phoneAccountHandle The phone account handle for the connection. 992 * @param connection The connection to add. 993 */ 994 public final void addExistingConnection(PhoneAccountHandle phoneAccountHandle, 995 Connection connection) { 996 997 String id = addExistingConnectionInternal(phoneAccountHandle, connection); 998 if (id != null) { 999 List<String> emptyList = new ArrayList<>(0); 1000 1001 ParcelableConnection parcelableConnection = new ParcelableConnection( 1002 phoneAccountHandle, 1003 connection.getState(), 1004 connection.getConnectionCapabilities(), 1005 connection.getAddress(), 1006 connection.getAddressPresentation(), 1007 connection.getCallerDisplayName(), 1008 connection.getCallerDisplayNamePresentation(), 1009 connection.getVideoProvider() == null ? 1010 null : connection.getVideoProvider().getInterface(), 1011 connection.getVideoState(), 1012 connection.isRingbackRequested(), 1013 connection.getAudioModeIsVoip(), 1014 connection.getConnectTimeMillis(), 1015 connection.getStatusHints(), 1016 connection.getDisconnectCause(), 1017 emptyList, 1018 connection.getExtras()); 1019 mAdapter.addExistingConnection(id, parcelableConnection); 1020 } 1021 } 1022 1023 /** 1024 * Returns all the active {@code Connection}s for which this {@code ConnectionService} 1025 * has taken responsibility. 1026 * 1027 * @return A collection of {@code Connection}s created by this {@code ConnectionService}. 1028 */ 1029 public final Collection<Connection> getAllConnections() { 1030 return mConnectionById.values(); 1031 } 1032 1033 /** 1034 * Create a {@code Connection} given an incoming request. This is used to attach to existing 1035 * incoming calls. 1036 * 1037 * @param connectionManagerPhoneAccount See description at 1038 * {@link #onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}. 1039 * @param request Details about the incoming call. 1040 * @return The {@code Connection} object to satisfy this call, or {@code null} to 1041 * not handle the call. 1042 */ 1043 public Connection onCreateIncomingConnection( 1044 PhoneAccountHandle connectionManagerPhoneAccount, 1045 ConnectionRequest request) { 1046 return null; 1047 } 1048 1049 /** 1050 * Trigger recalculate functinality for conference calls. This is used when a Telephony 1051 * Connection is part of a conference controller but is not yet added to Connection 1052 * Service and hence cannot be added to the conference call. 1053 * 1054 * @hide 1055 */ 1056 public void triggerConferenceRecalculate() { 1057 } 1058 1059 /** 1060 * Create a {@code Connection} given an outgoing request. This is used to initiate new 1061 * outgoing calls. 1062 * 1063 * @param connectionManagerPhoneAccount The connection manager account to use for managing 1064 * this call. 1065 * <p> 1066 * If this parameter is not {@code null}, it means that this {@code ConnectionService} 1067 * has registered one or more {@code PhoneAccount}s having 1068 * {@link PhoneAccount#CAPABILITY_CONNECTION_MANAGER}. This parameter will contain 1069 * one of these {@code PhoneAccount}s, while the {@code request} will contain another 1070 * (usually but not always distinct) {@code PhoneAccount} to be used for actually 1071 * making the connection. 1072 * <p> 1073 * If this parameter is {@code null}, it means that this {@code ConnectionService} is 1074 * being asked to make a direct connection. The 1075 * {@link ConnectionRequest#getAccountHandle()} of parameter {@code request} will be 1076 * a {@code PhoneAccount} registered by this {@code ConnectionService} to use for 1077 * making the connection. 1078 * @param request Details about the outgoing call. 1079 * @return The {@code Connection} object to satisfy this call, or the result of an invocation 1080 * of {@link Connection#createFailedConnection(DisconnectCause)} to not handle the call. 1081 */ 1082 public Connection onCreateOutgoingConnection( 1083 PhoneAccountHandle connectionManagerPhoneAccount, 1084 ConnectionRequest request) { 1085 return null; 1086 } 1087 1088 /** 1089 * Create a {@code Connection} for a new unknown call. An unknown call is a call originating 1090 * from the ConnectionService that was neither a user-initiated outgoing call, nor an incoming 1091 * call created using 1092 * {@code TelecomManager#addNewIncomingCall(PhoneAccountHandle, android.os.Bundle)}. 1093 * 1094 * @param connectionManagerPhoneAccount 1095 * @param request 1096 * @return 1097 * 1098 * @hide 1099 */ 1100 public Connection onCreateUnknownConnection(PhoneAccountHandle connectionManagerPhoneAccount, 1101 ConnectionRequest request) { 1102 return null; 1103 } 1104 1105 /** 1106 * Conference two specified connections. Invoked when the user has made a request to merge the 1107 * specified connections into a conference call. In response, the connection service should 1108 * create an instance of {@link Conference} and pass it into {@link #addConference}. 1109 * 1110 * @param connection1 A connection to merge into a conference call. 1111 * @param connection2 A connection to merge into a conference call. 1112 */ 1113 public void onConference(Connection connection1, Connection connection2) {} 1114 1115 /** 1116 * Indicates that a remote conference has been created for existing {@link RemoteConnection}s. 1117 * When this method is invoked, this {@link ConnectionService} should create its own 1118 * representation of the conference call and send it to telecom using {@link #addConference}. 1119 * <p> 1120 * This is only relevant to {@link ConnectionService}s which are registered with 1121 * {@link PhoneAccount#CAPABILITY_CONNECTION_MANAGER}. 1122 * 1123 * @param conference The remote conference call. 1124 */ 1125 public void onRemoteConferenceAdded(RemoteConference conference) {} 1126 1127 /** 1128 * Called when an existing connection is added remotely. 1129 * @param connection The existing connection which was added. 1130 */ 1131 public void onRemoteExistingConnectionAdded(RemoteConnection connection) {} 1132 1133 /** 1134 * @hide 1135 */ 1136 public boolean containsConference(Conference conference) { 1137 return mIdByConference.containsKey(conference); 1138 } 1139 1140 /** {@hide} */ 1141 void addRemoteConference(RemoteConference remoteConference) { 1142 onRemoteConferenceAdded(remoteConference); 1143 } 1144 1145 /** {@hide} */ 1146 void addRemoteExistingConnection(RemoteConnection remoteConnection) { 1147 onRemoteExistingConnectionAdded(remoteConnection); 1148 } 1149 1150 private void onAccountsInitialized() { 1151 mAreAccountsInitialized = true; 1152 for (Runnable r : mPreInitializationConnectionRequests) { 1153 r.run(); 1154 } 1155 mPreInitializationConnectionRequests.clear(); 1156 } 1157 1158 /** 1159 * Adds an existing connection to the list of connections, identified by a new call ID unique 1160 * to this connection service. 1161 * 1162 * @param connection The connection. 1163 * @return The ID of the connection (e.g. the call-id). 1164 */ 1165 private String addExistingConnectionInternal(PhoneAccountHandle handle, Connection connection) { 1166 String id; 1167 if (handle == null) { 1168 // If no phone account handle was provided, we cannot be sure the call ID is unique, 1169 // so just use a random UUID. 1170 id = UUID.randomUUID().toString(); 1171 } else { 1172 // Phone account handle was provided, so use the ConnectionService class name as a 1173 // prefix for a unique incremental call ID. 1174 id = handle.getComponentName().getClassName() + "@" + getNextCallId(); 1175 } 1176 addConnection(id, connection); 1177 return id; 1178 } 1179 1180 private void addConnection(String callId, Connection connection) { 1181 connection.setTelecomCallId(callId); 1182 mConnectionById.put(callId, connection); 1183 mIdByConnection.put(connection, callId); 1184 connection.addConnectionListener(mConnectionListener); 1185 connection.setConnectionService(this); 1186 } 1187 1188 /** {@hide} */ 1189 protected void removeConnection(Connection connection) { 1190 String id = mIdByConnection.get(connection); 1191 connection.unsetConnectionService(this); 1192 connection.removeConnectionListener(mConnectionListener); 1193 mConnectionById.remove(mIdByConnection.get(connection)); 1194 mIdByConnection.remove(connection); 1195 mAdapter.removeCall(id); 1196 } 1197 1198 private String addConferenceInternal(Conference conference) { 1199 if (mIdByConference.containsKey(conference)) { 1200 Log.w(this, "Re-adding an existing conference: %s.", conference); 1201 } else if (conference != null) { 1202 // Conferences do not (yet) have a PhoneAccountHandle associated with them, so we 1203 // cannot determine a ConnectionService class name to associate with the ID, so use 1204 // a unique UUID (for now). 1205 String id = UUID.randomUUID().toString(); 1206 mConferenceById.put(id, conference); 1207 mIdByConference.put(conference, id); 1208 conference.addListener(mConferenceListener); 1209 return id; 1210 } 1211 1212 return null; 1213 } 1214 1215 private void removeConference(Conference conference) { 1216 if (mIdByConference.containsKey(conference)) { 1217 conference.removeListener(mConferenceListener); 1218 1219 String id = mIdByConference.get(conference); 1220 mConferenceById.remove(id); 1221 mIdByConference.remove(conference); 1222 mAdapter.removeCall(id); 1223 } 1224 } 1225 1226 private Connection findConnectionForAction(String callId, String action) { 1227 if (mConnectionById.containsKey(callId)) { 1228 return mConnectionById.get(callId); 1229 } 1230 Log.w(this, "%s - Cannot find Connection %s", action, callId); 1231 return getNullConnection(); 1232 } 1233 1234 static synchronized Connection getNullConnection() { 1235 if (sNullConnection == null) { 1236 sNullConnection = new Connection() {}; 1237 } 1238 return sNullConnection; 1239 } 1240 1241 private Conference findConferenceForAction(String conferenceId, String action) { 1242 if (mConferenceById.containsKey(conferenceId)) { 1243 return mConferenceById.get(conferenceId); 1244 } 1245 Log.w(this, "%s - Cannot find conference %s", action, conferenceId); 1246 return getNullConference(); 1247 } 1248 1249 private List<String> createConnectionIdList(List<Connection> connections) { 1250 List<String> ids = new ArrayList<>(); 1251 for (Connection c : connections) { 1252 if (mIdByConnection.containsKey(c)) { 1253 ids.add(mIdByConnection.get(c)); 1254 } 1255 } 1256 Collections.sort(ids); 1257 return ids; 1258 } 1259 1260 /** 1261 * Builds a list of {@link Connection} and {@link Conference} IDs based on the list of 1262 * {@link Conferenceable}s passed in. 1263 * 1264 * @param conferenceables The {@link Conferenceable} connections and conferences. 1265 * @return List of string conference and call Ids. 1266 */ 1267 private List<String> createIdList(List<Conferenceable> conferenceables) { 1268 List<String> ids = new ArrayList<>(); 1269 for (Conferenceable c : conferenceables) { 1270 // Only allow Connection and Conference conferenceables. 1271 if (c instanceof Connection) { 1272 Connection connection = (Connection) c; 1273 if (mIdByConnection.containsKey(connection)) { 1274 ids.add(mIdByConnection.get(connection)); 1275 } 1276 } else if (c instanceof Conference) { 1277 Conference conference = (Conference) c; 1278 if (mIdByConference.containsKey(conference)) { 1279 ids.add(mIdByConference.get(conference)); 1280 } 1281 } 1282 } 1283 Collections.sort(ids); 1284 return ids; 1285 } 1286 1287 private Conference getNullConference() { 1288 if (sNullConference == null) { 1289 sNullConference = new Conference(null) {}; 1290 } 1291 return sNullConference; 1292 } 1293 1294 private void endAllConnections() { 1295 // Unbound from telecomm. We should end all connections and conferences. 1296 for (Connection connection : mIdByConnection.keySet()) { 1297 // only operate on top-level calls. Conference calls will be removed on their own. 1298 if (connection.getConference() == null) { 1299 connection.onDisconnect(); 1300 } 1301 } 1302 for (Conference conference : mIdByConference.keySet()) { 1303 conference.onDisconnect(); 1304 } 1305 } 1306 1307 /** 1308 * Retrieves the next call ID as maintainted by the connection service. 1309 * 1310 * @return The call ID. 1311 */ 1312 private int getNextCallId() { 1313 synchronized(mIdSyncRoot) { 1314 return ++mId; 1315 } 1316 } 1317} 1318