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