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