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