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 
17 package android.telecom;
18 
19 import android.annotation.IntDef;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.annotation.SystemApi;
23 import android.annotation.TestApi;
24 import android.compat.annotation.UnsupportedAppUsage;
25 import android.content.pm.ServiceInfo;
26 import android.net.Uri;
27 import android.os.Build;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.os.ParcelFileDescriptor;
31 
32 import com.android.internal.telecom.IVideoProvider;
33 
34 import java.io.IOException;
35 import java.io.InputStreamReader;
36 import java.io.OutputStreamWriter;
37 import java.lang.annotation.Retention;
38 import java.lang.annotation.RetentionPolicy;
39 import java.nio.charset.StandardCharsets;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Objects;
46 import java.util.concurrent.CopyOnWriteArrayList;
47 
48 /**
49  * Represents an ongoing phone call that the in-call app should present to the user.
50  */
51 public final class Call {
52     /**
53      * The state of a {@code Call} when newly created.
54      */
55     public static final int STATE_NEW = 0;
56 
57     /**
58      * The state of an outgoing {@code Call} when dialing the remote number, but not yet connected.
59      */
60     public static final int STATE_DIALING = 1;
61 
62     /**
63      * The state of an incoming {@code Call} when ringing locally, but not yet connected.
64      */
65     public static final int STATE_RINGING = 2;
66 
67     /**
68      * The state of a {@code Call} when in a holding state.
69      */
70     public static final int STATE_HOLDING = 3;
71 
72     /**
73      * The state of a {@code Call} when actively supporting conversation.
74      */
75     public static final int STATE_ACTIVE = 4;
76 
77     /**
78      * The state of a {@code Call} when no further voice or other communication is being
79      * transmitted, the remote side has been or will inevitably be informed that the {@code Call}
80      * is no longer active, and the local data transport has or inevitably will release resources
81      * associated with this {@code Call}.
82      */
83     public static final int STATE_DISCONNECTED = 7;
84 
85     /**
86      * The state of an outgoing {@code Call} when waiting on user to select a
87      * {@link PhoneAccount} through which to place the call.
88      */
89     public static final int STATE_SELECT_PHONE_ACCOUNT = 8;
90 
91     /**
92      * @hide
93      * @deprecated use STATE_SELECT_PHONE_ACCOUNT.
94      */
95     @Deprecated
96     @SystemApi
97     public static final int STATE_PRE_DIAL_WAIT = STATE_SELECT_PHONE_ACCOUNT;
98 
99     /**
100      * The initial state of an outgoing {@code Call}.
101      * Common transitions are to {@link #STATE_DIALING} state for a successful call or
102      * {@link #STATE_DISCONNECTED} if it failed.
103      */
104     public static final int STATE_CONNECTING = 9;
105 
106     /**
107      * The state of a {@code Call} when the user has initiated a disconnection of the call, but the
108      * call has not yet been disconnected by the underlying {@code ConnectionService}.  The next
109      * state of the call is (potentially) {@link #STATE_DISCONNECTED}.
110      */
111     public static final int STATE_DISCONNECTING = 10;
112 
113     /**
114      * The state of an external call which is in the process of being pulled from a remote device to
115      * the local device.
116      * <p>
117      * A call can only be in this state if the {@link Details#PROPERTY_IS_EXTERNAL_CALL} property
118      * and {@link Details#CAPABILITY_CAN_PULL_CALL} capability are set on the call.
119      * <p>
120      * An {@link InCallService} will only see this state if it has the
121      * {@link TelecomManager#METADATA_INCLUDE_EXTERNAL_CALLS} metadata set to {@code true} in its
122      * manifest.
123      */
124     public static final int STATE_PULLING_CALL = 11;
125 
126     /**
127      * The state of a call that is active with the network, but the audio from the call is
128      * being intercepted by an app on the local device. Telecom does not hold audio focus in this
129      * state, and the call will be invisible to the user except for a persistent notification.
130      */
131     public static final int STATE_AUDIO_PROCESSING = 12;
132 
133     /**
134      * The state of a call that is being presented to the user after being in
135      * {@link #STATE_AUDIO_PROCESSING}. The call is still active with the network in this case, and
136      * Telecom will hold audio focus and play a ringtone if appropriate.
137      */
138     public static final int STATE_SIMULATED_RINGING = 13;
139 
140     /**
141      * The key to retrieve the optional {@code PhoneAccount}s Telecom can bundle with its Call
142      * extras. Used to pass the phone accounts to display on the front end to the user in order to
143      * select phone accounts to (for example) place a call.
144      * @deprecated Use the list from {@link #EXTRA_SUGGESTED_PHONE_ACCOUNTS} instead.
145      */
146     @Deprecated
147     public static final String AVAILABLE_PHONE_ACCOUNTS = "selectPhoneAccountAccounts";
148 
149     /**
150      * Key for extra used to pass along a list of {@link PhoneAccountSuggestion}s to the in-call
151      * UI when a call enters the {@link #STATE_SELECT_PHONE_ACCOUNT} state. The list included here
152      * will have the same length and be in the same order as the list passed with
153      * {@link #AVAILABLE_PHONE_ACCOUNTS}.
154      */
155     public static final String EXTRA_SUGGESTED_PHONE_ACCOUNTS =
156             "android.telecom.extra.SUGGESTED_PHONE_ACCOUNTS";
157 
158     /**
159      * Extra key used to indicate the time (in milliseconds since midnight, January 1, 1970 UTC)
160      * when the last outgoing emergency call was made.  This is used to identify potential emergency
161      * callbacks.
162      */
163     public static final String EXTRA_LAST_EMERGENCY_CALLBACK_TIME_MILLIS =
164             "android.telecom.extra.LAST_EMERGENCY_CALLBACK_TIME_MILLIS";
165 
166 
167     /**
168      * Extra key used to indicate whether a {@link CallScreeningService} has requested to silence
169      * the ringtone for a call.  If the {@link InCallService} declares
170      * {@link TelecomManager#METADATA_IN_CALL_SERVICE_RINGING} in its manifest, it should not
171      * play a ringtone for an incoming call with this extra key set.
172      */
173     public static final String EXTRA_SILENT_RINGING_REQUESTED =
174             "android.telecom.extra.SILENT_RINGING_REQUESTED";
175 
176     /**
177      * Call event sent from a {@link Call} via {@link #sendCallEvent(String, Bundle)} to inform
178      * Telecom that the user has requested that the current {@link Call} should be handed over
179      * to another {@link ConnectionService}.
180      * <p>
181      * The caller must specify the {@link #EXTRA_HANDOVER_PHONE_ACCOUNT_HANDLE} to indicate to
182      * Telecom which {@link PhoneAccountHandle} the {@link Call} should be handed over to.
183      * @hide
184      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
185      * APIs instead.
186      */
187     public static final String EVENT_REQUEST_HANDOVER =
188             "android.telecom.event.REQUEST_HANDOVER";
189 
190     /**
191      * Extra key used with the {@link #EVENT_REQUEST_HANDOVER} call event.  Specifies the
192      * {@link PhoneAccountHandle} to which a call should be handed over to.
193      * @hide
194      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
195      * APIs instead.
196      */
197     public static final String EXTRA_HANDOVER_PHONE_ACCOUNT_HANDLE =
198             "android.telecom.extra.HANDOVER_PHONE_ACCOUNT_HANDLE";
199 
200     /**
201      * Integer extra key used with the {@link #EVENT_REQUEST_HANDOVER} call event.  Specifies the
202      * video state of the call when it is handed over to the new {@link PhoneAccount}.
203      * <p>
204      * Valid values: {@link VideoProfile#STATE_AUDIO_ONLY},
205      * {@link VideoProfile#STATE_BIDIRECTIONAL}, {@link VideoProfile#STATE_RX_ENABLED}, and
206      * {@link VideoProfile#STATE_TX_ENABLED}.
207      * @hide
208      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
209      * APIs instead.
210      */
211     public static final String EXTRA_HANDOVER_VIDEO_STATE =
212             "android.telecom.extra.HANDOVER_VIDEO_STATE";
213 
214     /**
215      * Extra key used with the {@link #EVENT_REQUEST_HANDOVER} call event.  Used by the
216      * {@link InCallService} initiating a handover to provide a {@link Bundle} with extra
217      * information to the handover {@link ConnectionService} specified by
218      * {@link #EXTRA_HANDOVER_PHONE_ACCOUNT_HANDLE}.
219      * <p>
220      * This {@link Bundle} is not interpreted by Telecom, but passed as-is to the
221      * {@link ConnectionService} via the request extras when
222      * {@link ConnectionService#onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}
223      * is called to initate the handover.
224      * @hide
225      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
226      * APIs instead.
227      */
228     public static final String EXTRA_HANDOVER_EXTRAS = "android.telecom.extra.HANDOVER_EXTRAS";
229 
230     /**
231      * Call event sent from Telecom to the handover {@link ConnectionService} via
232      * {@link Connection#onCallEvent(String, Bundle)} to inform a {@link Connection} that a handover
233      * to the {@link ConnectionService} has completed successfully.
234      * <p>
235      * A handover is initiated with the {@link #EVENT_REQUEST_HANDOVER} call event.
236      * @hide
237      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
238      * APIs instead.
239      */
240     public static final String EVENT_HANDOVER_COMPLETE =
241             "android.telecom.event.HANDOVER_COMPLETE";
242 
243     /**
244      * Call event sent from Telecom to the handover destination {@link ConnectionService} via
245      * {@link Connection#onCallEvent(String, Bundle)} to inform the handover destination that the
246      * source connection has disconnected.  The {@link Bundle} parameter for the call event will be
247      * {@code null}.
248      * <p>
249      * A handover is initiated with the {@link #EVENT_REQUEST_HANDOVER} call event.
250      * @hide
251      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
252      * APIs instead.
253      */
254     public static final String EVENT_HANDOVER_SOURCE_DISCONNECTED =
255             "android.telecom.event.HANDOVER_SOURCE_DISCONNECTED";
256 
257     /**
258      * Call event sent from Telecom to the handover {@link ConnectionService} via
259      * {@link Connection#onCallEvent(String, Bundle)} to inform a {@link Connection} that a handover
260      * to the {@link ConnectionService} has failed.
261      * <p>
262      * A handover is initiated with the {@link #EVENT_REQUEST_HANDOVER} call event.
263      * @hide
264      * @deprecated Use {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} and its associated
265      * APIs instead.
266      */
267     public static final String EVENT_HANDOVER_FAILED =
268             "android.telecom.event.HANDOVER_FAILED";
269 
270 
271     /**
272      * Reject reason used with {@link #reject(int)} to indicate that the user is rejecting this
273      * call because they have declined to answer it.  This typically means that they are unable
274      * to answer the call at this time and would prefer it be sent to voicemail.
275      */
276     public static final int REJECT_REASON_DECLINED = 1;
277 
278     /**
279      * Reject reason used with {@link #reject(int)} to indicate that the user is rejecting this
280      * call because it is an unwanted call.  This allows the user to indicate that they are
281      * rejecting a call because it is likely a nuisance call.
282      */
283     public static final int REJECT_REASON_UNWANTED = 2;
284 
285     /**
286      * @hide
287      */
288     @IntDef(prefix = { "REJECT_REASON_" },
289             value = {REJECT_REASON_DECLINED, REJECT_REASON_UNWANTED})
290     @Retention(RetentionPolicy.SOURCE)
291     public @interface RejectReason {};
292 
293     public static class Details {
294         /** @hide */
295         @Retention(RetentionPolicy.SOURCE)
296         @IntDef(
297                 prefix = { "DIRECTION_" },
298                 value = {DIRECTION_UNKNOWN, DIRECTION_INCOMING, DIRECTION_OUTGOING})
299         public @interface CallDirection {}
300 
301         /**
302          * Indicates that the call is neither and incoming nor an outgoing call.  This can be the
303          * case for calls reported directly by a {@link ConnectionService} in special cases such as
304          * call handovers.
305          */
306         public static final int DIRECTION_UNKNOWN = -1;
307 
308         /**
309          * Indicates that the call is an incoming call.
310          */
311         public static final int DIRECTION_INCOMING = 0;
312 
313         /**
314          * Indicates that the call is an outgoing call.
315          */
316         public static final int DIRECTION_OUTGOING = 1;
317 
318         /** Call can currently be put on hold or unheld. */
319         public static final int CAPABILITY_HOLD = 0x00000001;
320 
321         /** Call supports the hold feature. */
322         public static final int CAPABILITY_SUPPORT_HOLD = 0x00000002;
323 
324         /**
325          * Calls within a conference can be merged. A {@link ConnectionService} has the option to
326          * add a {@link Conference} call before the child {@link Connection}s are merged. This is how
327          * CDMA-based {@link Connection}s are implemented. For these unmerged {@link Conference}s, this
328          * capability allows a merge button to be shown while the conference call is in the foreground
329          * of the in-call UI.
330          * <p>
331          * This is only intended for use by a {@link Conference}.
332          */
333         public static final int CAPABILITY_MERGE_CONFERENCE = 0x00000004;
334 
335         /**
336          * Calls within a conference can be swapped between foreground and background.
337          * See {@link #CAPABILITY_MERGE_CONFERENCE} for additional information.
338          * <p>
339          * This is only intended for use by a {@link Conference}.
340          */
341         public static final int CAPABILITY_SWAP_CONFERENCE = 0x00000008;
342 
343         /**
344          * @hide
345          */
346         public static final int CAPABILITY_UNUSED_1 = 0x00000010;
347 
348         /** Call supports responding via text option. */
349         public static final int CAPABILITY_RESPOND_VIA_TEXT = 0x00000020;
350 
351         /** Call can be muted. */
352         public static final int CAPABILITY_MUTE = 0x00000040;
353 
354         /**
355          * Call supports conference call management. This capability only applies to {@link Conference}
356          * calls which can have {@link Connection}s as children.
357          */
358         public static final int CAPABILITY_MANAGE_CONFERENCE = 0x00000080;
359 
360         /**
361          * Local device supports receiving video.
362          */
363         public static final int CAPABILITY_SUPPORTS_VT_LOCAL_RX = 0x00000100;
364 
365         /**
366          * Local device supports transmitting video.
367          */
368         public static final int CAPABILITY_SUPPORTS_VT_LOCAL_TX = 0x00000200;
369 
370         /**
371          * Local device supports bidirectional video calling.
372          */
373         public static final int CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL =
374                 CAPABILITY_SUPPORTS_VT_LOCAL_RX | CAPABILITY_SUPPORTS_VT_LOCAL_TX;
375 
376         /**
377          * Remote device supports receiving video.
378          */
379         public static final int CAPABILITY_SUPPORTS_VT_REMOTE_RX = 0x00000400;
380 
381         /**
382          * Remote device supports transmitting video.
383          */
384         public static final int CAPABILITY_SUPPORTS_VT_REMOTE_TX = 0x00000800;
385 
386         /**
387          * Remote device supports bidirectional video calling.
388          */
389         public static final int CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL =
390                 CAPABILITY_SUPPORTS_VT_REMOTE_RX | CAPABILITY_SUPPORTS_VT_REMOTE_TX;
391 
392         /**
393          * Call is able to be separated from its parent {@code Conference}, if any.
394          */
395         public static final int CAPABILITY_SEPARATE_FROM_CONFERENCE = 0x00001000;
396 
397         /**
398          * Call is able to be individually disconnected when in a {@code Conference}.
399          */
400         public static final int CAPABILITY_DISCONNECT_FROM_CONFERENCE = 0x00002000;
401 
402         /**
403          * Speed up audio setup for MT call.
404          * @hide
405          */
406         public static final int CAPABILITY_SPEED_UP_MT_AUDIO = 0x00040000;
407 
408         /**
409          * Call can be upgraded to a video call.
410          * @hide
411          * @deprecated Use {@link #CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL} and
412          * {@link #CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL} to indicate for a call
413          * whether or not video calling is supported.
414          */
415         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 119305590)
416         public static final int CAPABILITY_CAN_UPGRADE_TO_VIDEO = 0x00080000;
417 
418         /**
419          * For video calls, indicates whether the outgoing video for the call can be paused using
420          * the {@link android.telecom.VideoProfile#STATE_PAUSED} VideoState.
421          */
422         public static final int CAPABILITY_CAN_PAUSE_VIDEO = 0x00100000;
423 
424         /**
425          * Call sends responses through connection.
426          * @hide
427          */
428         public static final int CAPABILITY_CAN_SEND_RESPONSE_VIA_CONNECTION = 0x00200000;
429 
430         /**
431          * When set, prevents a video {@code Call} from being downgraded to an audio-only call.
432          * <p>
433          * Should be set when the VideoState has the {@link VideoProfile#STATE_TX_ENABLED} or
434          * {@link VideoProfile#STATE_RX_ENABLED} bits set to indicate that the connection cannot be
435          * downgraded from a video call back to a VideoState of
436          * {@link VideoProfile#STATE_AUDIO_ONLY}.
437          * <p>
438          * Intuitively, a call which can be downgraded to audio should also have local and remote
439          * video
440          * capabilities (see {@link #CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL} and
441          * {@link #CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL}).
442          */
443         public static final int CAPABILITY_CANNOT_DOWNGRADE_VIDEO_TO_AUDIO = 0x00400000;
444 
445         /**
446          * When set for an external call, indicates that this {@code Call} can be pulled from a
447          * remote device to the current device.
448          * <p>
449          * Should only be set on a {@code Call} where {@link #PROPERTY_IS_EXTERNAL_CALL} is set.
450          * <p>
451          * An {@link InCallService} will only see calls with this capability if it has the
452          * {@link TelecomManager#METADATA_INCLUDE_EXTERNAL_CALLS} metadata set to {@code true}
453          * in its manifest.
454          * <p>
455          * See {@link Connection#CAPABILITY_CAN_PULL_CALL} and
456          * {@link Connection#PROPERTY_IS_EXTERNAL_CALL}.
457          */
458         public static final int CAPABILITY_CAN_PULL_CALL = 0x00800000;
459 
460         /** Call supports the deflect feature. */
461         public static final int CAPABILITY_SUPPORT_DEFLECT = 0x01000000;
462 
463         /**
464          * Call supports adding participants to the call via
465          * {@link #addConferenceParticipants(List)}.
466          * @hide
467          */
468         public static final int CAPABILITY_ADD_PARTICIPANT = 0x02000000;
469 
470         /**
471          * When set for a call, indicates that this {@code Call} can be transferred to another
472          * number.
473          * Call supports the blind and assured call transfer feature.
474          *
475          * @hide
476          */
477         public static final int CAPABILITY_TRANSFER = 0x04000000;
478 
479         /**
480          * When set for a call, indicates that this {@code Call} can be transferred to another
481          * ongoing call.
482          * Call supports the consultative call transfer feature.
483          *
484          * @hide
485          */
486         public static final int CAPABILITY_TRANSFER_CONSULTATIVE = 0x08000000;
487 
488         //******************************************************************************************
489         // Next CAPABILITY value: 0x10000000
490         //******************************************************************************************
491 
492         /**
493          * Whether the call is currently a conference.
494          */
495         public static final int PROPERTY_CONFERENCE = 0x00000001;
496 
497         /**
498          * Whether the call is a generic conference, where we do not know the precise state of
499          * participants in the conference (eg. on CDMA).
500          */
501         public static final int PROPERTY_GENERIC_CONFERENCE = 0x00000002;
502 
503         /**
504          * Whether the call is made while the device is in emergency callback mode.
505          */
506         public static final int PROPERTY_EMERGENCY_CALLBACK_MODE = 0x00000004;
507 
508         /**
509          * Connection is using WIFI.
510          */
511         public static final int PROPERTY_WIFI = 0x00000008;
512 
513         /**
514          * When set, the UI should indicate to the user that a call is using high definition
515          * audio.
516          * <p>
517          * The underlying {@link ConnectionService} is responsible for reporting this
518          * property.  It is important to note that this property is not intended to report the
519          * actual audio codec being used for a Call, but whether the call should be indicated
520          * to the user as high definition.
521          * <p>
522          * The Android Telephony stack reports this property for calls based on a number
523          * of factors, including which audio codec is used and whether a call is using an HD
524          * codec end-to-end.  Some mobile operators choose to suppress display of an HD indication,
525          * and in these cases this property will not be set for a call even if the underlying audio
526          * codec is in fact "high definition".
527          */
528         public static final int PROPERTY_HIGH_DEF_AUDIO = 0x00000010;
529 
530         /**
531          * Whether the call is associated with the work profile.
532          */
533         public static final int PROPERTY_ENTERPRISE_CALL = 0x00000020;
534 
535         /**
536          * When set, indicates that this {@code Call} does not actually exist locally for the
537          * {@link ConnectionService}.
538          * <p>
539          * Consider, for example, a scenario where a user has two phones with the same phone number.
540          * When a user places a call on one device, the telephony stack can represent that call on
541          * the other device by adding it to the {@link ConnectionService} with the
542          * {@link Connection#PROPERTY_IS_EXTERNAL_CALL} property set.
543          * <p>
544          * An {@link InCallService} will only see calls with this property if it has the
545          * {@link TelecomManager#METADATA_INCLUDE_EXTERNAL_CALLS} metadata set to {@code true}
546          * in its manifest.
547          * <p>
548          * See {@link Connection#PROPERTY_IS_EXTERNAL_CALL}.
549          */
550         public static final int PROPERTY_IS_EXTERNAL_CALL = 0x00000040;
551 
552         /**
553          * Indicates that the call has CDMA Enhanced Voice Privacy enabled.
554          */
555         public static final int PROPERTY_HAS_CDMA_VOICE_PRIVACY = 0x00000080;
556 
557         /**
558          * Indicates that the call is from a self-managed {@link ConnectionService}.
559          * <p>
560          * See also {@link Connection#PROPERTY_SELF_MANAGED}
561          */
562         public static final int PROPERTY_SELF_MANAGED = 0x00000100;
563 
564         /**
565          * Indicates the call used Assisted Dialing.
566          *
567          * @see TelecomManager#EXTRA_USE_ASSISTED_DIALING
568          */
569         public static final int PROPERTY_ASSISTED_DIALING = 0x00000200;
570 
571         /**
572          * Indicates that the call is an RTT call. Use {@link #getRttCall()} to get the
573          * {@link RttCall} object that is used to send and receive text.
574          */
575         public static final int PROPERTY_RTT = 0x00000400;
576 
577         /**
578          * Indicates that the call has been identified as the network as an emergency call. This
579          * property may be set for both incoming and outgoing calls which the network identifies as
580          * emergency calls.
581          */
582         public static final int PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL = 0x00000800;
583 
584         /**
585          * Indicates that the call is using VoIP audio mode.
586          * <p>
587          * When this property is set, the {@link android.media.AudioManager} audio mode for this
588          * call will be {@link android.media.AudioManager#MODE_IN_COMMUNICATION}.  When this
589          * property is not set, the audio mode for this call will be
590          * {@link android.media.AudioManager#MODE_IN_CALL}.
591          * <p>
592          * This property reflects changes made using {@link Connection#setAudioModeIsVoip(boolean)}.
593          * <p>
594          * You can use this property to determine whether an un-answered incoming call or a held
595          * call will use VoIP audio mode (if the call does not currently have focus, the system
596          * audio mode may not reflect the mode the call will use).
597          */
598         public static final int PROPERTY_VOIP_AUDIO_MODE = 0x00001000;
599 
600         /**
601          * Indicates that the call is an adhoc conference call. This property can be set for both
602          * incoming and outgoing calls.
603          * @hide
604          */
605         public static final int PROPERTY_IS_ADHOC_CONFERENCE = 0x00002000;
606 
607         //******************************************************************************************
608         // Next PROPERTY value: 0x00004000
609         //******************************************************************************************
610 
611         private final String mTelecomCallId;
612         private final Uri mHandle;
613         private final int mHandlePresentation;
614         private final String mCallerDisplayName;
615         private final int mCallerDisplayNamePresentation;
616         private final PhoneAccountHandle mAccountHandle;
617         private final int mCallCapabilities;
618         private final int mCallProperties;
619         private final int mSupportedAudioRoutes = CallAudioState.ROUTE_ALL;
620         private final DisconnectCause mDisconnectCause;
621         private final long mConnectTimeMillis;
622         private final GatewayInfo mGatewayInfo;
623         private final int mVideoState;
624         private final StatusHints mStatusHints;
625         private final Bundle mExtras;
626         private final Bundle mIntentExtras;
627         private final long mCreationTimeMillis;
628         private final String mContactDisplayName;
629         private final @CallDirection int mCallDirection;
630         private final @Connection.VerificationStatus int mCallerNumberVerificationStatus;
631 
632         /**
633          * Whether the supplied capabilities  supports the specified capability.
634          *
635          * @param capabilities A bit field of capabilities.
636          * @param capability The capability to check capabilities for.
637          * @return Whether the specified capability is supported.
638          */
can(int capabilities, int capability)639         public static boolean can(int capabilities, int capability) {
640             return (capabilities & capability) == capability;
641         }
642 
643         /**
644          * Whether the capabilities of this {@code Details} supports the specified capability.
645          *
646          * @param capability The capability to check capabilities for.
647          * @return Whether the specified capability is supported.
648          */
can(int capability)649         public boolean can(int capability) {
650             return can(mCallCapabilities, capability);
651         }
652 
653         /**
654          * Render a set of capability bits ({@code CAPABILITY_*}) as a human readable string.
655          *
656          * @param capabilities A capability bit field.
657          * @return A human readable string representation.
658          */
capabilitiesToString(int capabilities)659         public static String capabilitiesToString(int capabilities) {
660             StringBuilder builder = new StringBuilder();
661             builder.append("[Capabilities:");
662             if (can(capabilities, CAPABILITY_HOLD)) {
663                 builder.append(" CAPABILITY_HOLD");
664             }
665             if (can(capabilities, CAPABILITY_SUPPORT_HOLD)) {
666                 builder.append(" CAPABILITY_SUPPORT_HOLD");
667             }
668             if (can(capabilities, CAPABILITY_MERGE_CONFERENCE)) {
669                 builder.append(" CAPABILITY_MERGE_CONFERENCE");
670             }
671             if (can(capabilities, CAPABILITY_SWAP_CONFERENCE)) {
672                 builder.append(" CAPABILITY_SWAP_CONFERENCE");
673             }
674             if (can(capabilities, CAPABILITY_RESPOND_VIA_TEXT)) {
675                 builder.append(" CAPABILITY_RESPOND_VIA_TEXT");
676             }
677             if (can(capabilities, CAPABILITY_MUTE)) {
678                 builder.append(" CAPABILITY_MUTE");
679             }
680             if (can(capabilities, CAPABILITY_MANAGE_CONFERENCE)) {
681                 builder.append(" CAPABILITY_MANAGE_CONFERENCE");
682             }
683             if (can(capabilities, CAPABILITY_SUPPORTS_VT_LOCAL_RX)) {
684                 builder.append(" CAPABILITY_SUPPORTS_VT_LOCAL_RX");
685             }
686             if (can(capabilities, CAPABILITY_SUPPORTS_VT_LOCAL_TX)) {
687                 builder.append(" CAPABILITY_SUPPORTS_VT_LOCAL_TX");
688             }
689             if (can(capabilities, CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL)) {
690                 builder.append(" CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL");
691             }
692             if (can(capabilities, CAPABILITY_SUPPORTS_VT_REMOTE_RX)) {
693                 builder.append(" CAPABILITY_SUPPORTS_VT_REMOTE_RX");
694             }
695             if (can(capabilities, CAPABILITY_SUPPORTS_VT_REMOTE_TX)) {
696                 builder.append(" CAPABILITY_SUPPORTS_VT_REMOTE_TX");
697             }
698             if (can(capabilities, CAPABILITY_CANNOT_DOWNGRADE_VIDEO_TO_AUDIO)) {
699                 builder.append(" CAPABILITY_CANNOT_DOWNGRADE_VIDEO_TO_AUDIO");
700             }
701             if (can(capabilities, CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL)) {
702                 builder.append(" CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL");
703             }
704             if (can(capabilities, CAPABILITY_SPEED_UP_MT_AUDIO)) {
705                 builder.append(" CAPABILITY_SPEED_UP_MT_AUDIO");
706             }
707             if (can(capabilities, CAPABILITY_CAN_UPGRADE_TO_VIDEO)) {
708                 builder.append(" CAPABILITY_CAN_UPGRADE_TO_VIDEO");
709             }
710             if (can(capabilities, CAPABILITY_CAN_PAUSE_VIDEO)) {
711                 builder.append(" CAPABILITY_CAN_PAUSE_VIDEO");
712             }
713             if (can(capabilities, CAPABILITY_CAN_PULL_CALL)) {
714                 builder.append(" CAPABILITY_CAN_PULL_CALL");
715             }
716             if (can(capabilities, CAPABILITY_SUPPORT_DEFLECT)) {
717                 builder.append(" CAPABILITY_SUPPORT_DEFLECT");
718             }
719             if (can(capabilities, CAPABILITY_ADD_PARTICIPANT)) {
720                 builder.append(" CAPABILITY_ADD_PARTICIPANT");
721             }
722             if (can(capabilities, CAPABILITY_TRANSFER)) {
723                 builder.append(" CAPABILITY_TRANSFER");
724             }
725             if (can(capabilities, CAPABILITY_TRANSFER_CONSULTATIVE)) {
726                 builder.append(" CAPABILITY_TRANSFER_CONSULTATIVE");
727             }
728             builder.append("]");
729             return builder.toString();
730         }
731 
732         /**
733          * Whether the supplied properties includes the specified property.
734          *
735          * @param properties A bit field of properties.
736          * @param property The property to check properties for.
737          * @return Whether the specified property is supported.
738          */
hasProperty(int properties, int property)739         public static boolean hasProperty(int properties, int property) {
740             return (properties & property) == property;
741         }
742 
743         /**
744          * Whether the properties of this {@code Details} includes the specified property.
745          *
746          * @param property The property to check properties for.
747          * @return Whether the specified property is supported.
748          */
hasProperty(int property)749         public boolean hasProperty(int property) {
750             return hasProperty(mCallProperties, property);
751         }
752 
753         /**
754          * Render a set of property bits ({@code PROPERTY_*}) as a human readable string.
755          *
756          * @param properties A property bit field.
757          * @return A human readable string representation.
758          */
propertiesToString(int properties)759         public static String propertiesToString(int properties) {
760             StringBuilder builder = new StringBuilder();
761             builder.append("[Properties:");
762             if (hasProperty(properties, PROPERTY_CONFERENCE)) {
763                 builder.append(" PROPERTY_CONFERENCE");
764             }
765             if (hasProperty(properties, PROPERTY_GENERIC_CONFERENCE)) {
766                 builder.append(" PROPERTY_GENERIC_CONFERENCE");
767             }
768             if (hasProperty(properties, PROPERTY_WIFI)) {
769                 builder.append(" PROPERTY_WIFI");
770             }
771             if (hasProperty(properties, PROPERTY_HIGH_DEF_AUDIO)) {
772                 builder.append(" PROPERTY_HIGH_DEF_AUDIO");
773             }
774             if (hasProperty(properties, PROPERTY_EMERGENCY_CALLBACK_MODE)) {
775                 builder.append(" PROPERTY_EMERGENCY_CALLBACK_MODE");
776             }
777             if (hasProperty(properties, PROPERTY_IS_EXTERNAL_CALL)) {
778                 builder.append(" PROPERTY_IS_EXTERNAL_CALL");
779             }
780             if (hasProperty(properties, PROPERTY_HAS_CDMA_VOICE_PRIVACY)) {
781                 builder.append(" PROPERTY_HAS_CDMA_VOICE_PRIVACY");
782             }
783             if (hasProperty(properties, PROPERTY_ASSISTED_DIALING)) {
784                 builder.append(" PROPERTY_ASSISTED_DIALING_USED");
785             }
786             if (hasProperty(properties, PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL)) {
787                 builder.append(" PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL");
788             }
789             if (hasProperty(properties, PROPERTY_RTT)) {
790                 builder.append(" PROPERTY_RTT");
791             }
792             if (hasProperty(properties, PROPERTY_VOIP_AUDIO_MODE)) {
793                 builder.append(" PROPERTY_VOIP_AUDIO_MODE");
794             }
795             if (hasProperty(properties, PROPERTY_IS_ADHOC_CONFERENCE)) {
796                 builder.append(" PROPERTY_IS_ADHOC_CONFERENCE");
797             }
798             builder.append("]");
799             return builder.toString();
800         }
801 
802         /** {@hide} */
803         @TestApi
getTelecomCallId()804         public String getTelecomCallId() {
805             return mTelecomCallId;
806         }
807 
808         /**
809          * @return The handle (e.g., phone number) to which the {@code Call} is currently
810          * connected.
811          */
getHandle()812         public Uri getHandle() {
813             return mHandle;
814         }
815 
816         /**
817          * @return The presentation requirements for the handle. See
818          * {@link TelecomManager} for valid values.
819          */
getHandlePresentation()820         public int getHandlePresentation() {
821             return mHandlePresentation;
822         }
823 
824         /**
825          * The display name for the caller.
826          * <p>
827          * This is the name as reported by the {@link ConnectionService} associated with this call.
828          *
829          * @return The display name for the caller.
830          */
getCallerDisplayName()831         public String getCallerDisplayName() {
832             return mCallerDisplayName;
833         }
834 
835         /**
836          * @return The presentation requirements for the caller display name. See
837          * {@link TelecomManager} for valid values.
838          */
getCallerDisplayNamePresentation()839         public int getCallerDisplayNamePresentation() {
840             return mCallerDisplayNamePresentation;
841         }
842 
843         /**
844          * @return The {@code PhoneAccountHandle} whereby the {@code Call} is currently being
845          * routed.
846          */
getAccountHandle()847         public PhoneAccountHandle getAccountHandle() {
848             return mAccountHandle;
849         }
850 
851         /**
852          * @return A bitmask of the capabilities of the {@code Call}, as defined by the various
853          *         {@code CAPABILITY_*} constants in this class.
854          */
getCallCapabilities()855         public int getCallCapabilities() {
856             return mCallCapabilities;
857         }
858 
859         /**
860          * @return A bitmask of the properties of the {@code Call}, as defined by the various
861          *         {@code PROPERTY_*} constants in this class.
862          */
getCallProperties()863         public int getCallProperties() {
864             return mCallProperties;
865         }
866 
867         /**
868          * @return a bitmask of the audio routes available for the call.
869          *
870          * @hide
871          */
getSupportedAudioRoutes()872         public int getSupportedAudioRoutes() {
873             return mSupportedAudioRoutes;
874         }
875 
876         /**
877          * @return For a {@link #STATE_DISCONNECTED} {@code Call}, the disconnect cause expressed
878          * by {@link android.telecom.DisconnectCause}.
879          */
getDisconnectCause()880         public DisconnectCause getDisconnectCause() {
881             return mDisconnectCause;
882         }
883 
884         /**
885          * Returns the time the {@link Call} connected (i.e. became active).  This information is
886          * updated periodically, but user interfaces should not rely on this to display the "call
887          * time clock".  For the time when the call was first added to Telecom, see
888          * {@link #getCreationTimeMillis()}.
889          *
890          * @return The time the {@link Call} connected in milliseconds since the epoch.
891          */
getConnectTimeMillis()892         public final long getConnectTimeMillis() {
893             return mConnectTimeMillis;
894         }
895 
896         /**
897          * @return Information about any calling gateway the {@code Call} may be using.
898          */
getGatewayInfo()899         public GatewayInfo getGatewayInfo() {
900             return mGatewayInfo;
901         }
902 
903         /**
904          * @return The video state of the {@code Call}.
905          */
getVideoState()906         public int getVideoState() {
907             return mVideoState;
908         }
909 
910         /**
911          * @return The current {@link android.telecom.StatusHints}, or {@code null} if none
912          * have been set.
913          */
getStatusHints()914         public StatusHints getStatusHints() {
915             return mStatusHints;
916         }
917 
918         /**
919          * @return The extras associated with this call.
920          */
getExtras()921         public Bundle getExtras() {
922             return mExtras;
923         }
924 
925         /**
926          * @return The extras used with the original intent to place this call.
927          */
getIntentExtras()928         public Bundle getIntentExtras() {
929             return mIntentExtras;
930         }
931 
932         /**
933          * Returns the time when the call was first created and added to Telecom.  This is the same
934          * time that is logged as the start time in the Call Log (see
935          * {@link android.provider.CallLog.Calls#DATE}).  To determine when the call was connected
936          * (became active), see {@link #getConnectTimeMillis()}.
937          *
938          * @return The creation time of the call, in millis since the epoch.
939          */
getCreationTimeMillis()940         public long getCreationTimeMillis() {
941             return mCreationTimeMillis;
942         }
943 
944         /**
945          * Returns the name of the caller on the remote end, as derived from a
946          * {@link android.provider.ContactsContract} lookup of the call's handle.
947          * @return The name of the caller, or {@code null} if the lookup is not yet complete, if
948          *         there's no contacts entry for the caller, or if the {@link InCallService} does
949          *         not hold the {@link android.Manifest.permission#READ_CONTACTS} permission.
950          */
getContactDisplayName()951         public @Nullable String getContactDisplayName() {
952             return mContactDisplayName;
953         }
954 
955         /**
956          * Indicates whether the call is an incoming or outgoing call.
957          * @return The call's direction.
958          */
getCallDirection()959         public @CallDirection int getCallDirection() {
960             return mCallDirection;
961         }
962 
963         /**
964          * Gets the verification status for the phone number of an incoming call as identified in
965          * ATIS-1000082.
966          * @return the verification status.
967          */
getCallerNumberVerificationStatus()968         public @Connection.VerificationStatus int getCallerNumberVerificationStatus() {
969             return mCallerNumberVerificationStatus;
970         }
971 
972         @Override
equals(Object o)973         public boolean equals(Object o) {
974             if (o instanceof Details) {
975                 Details d = (Details) o;
976                 return
977                         Objects.equals(mHandle, d.mHandle) &&
978                         Objects.equals(mHandlePresentation, d.mHandlePresentation) &&
979                         Objects.equals(mCallerDisplayName, d.mCallerDisplayName) &&
980                         Objects.equals(mCallerDisplayNamePresentation,
981                                 d.mCallerDisplayNamePresentation) &&
982                         Objects.equals(mAccountHandle, d.mAccountHandle) &&
983                         Objects.equals(mCallCapabilities, d.mCallCapabilities) &&
984                         Objects.equals(mCallProperties, d.mCallProperties) &&
985                         Objects.equals(mDisconnectCause, d.mDisconnectCause) &&
986                         Objects.equals(mConnectTimeMillis, d.mConnectTimeMillis) &&
987                         Objects.equals(mGatewayInfo, d.mGatewayInfo) &&
988                         Objects.equals(mVideoState, d.mVideoState) &&
989                         Objects.equals(mStatusHints, d.mStatusHints) &&
990                         areBundlesEqual(mExtras, d.mExtras) &&
991                         areBundlesEqual(mIntentExtras, d.mIntentExtras) &&
992                         Objects.equals(mCreationTimeMillis, d.mCreationTimeMillis) &&
993                         Objects.equals(mContactDisplayName, d.mContactDisplayName) &&
994                         Objects.equals(mCallDirection, d.mCallDirection) &&
995                         Objects.equals(mCallerNumberVerificationStatus,
996                                 d.mCallerNumberVerificationStatus);
997             }
998             return false;
999         }
1000 
1001         @Override
hashCode()1002         public int hashCode() {
1003             return Objects.hash(mHandle,
1004                             mHandlePresentation,
1005                             mCallerDisplayName,
1006                             mCallerDisplayNamePresentation,
1007                             mAccountHandle,
1008                             mCallCapabilities,
1009                             mCallProperties,
1010                             mDisconnectCause,
1011                             mConnectTimeMillis,
1012                             mGatewayInfo,
1013                             mVideoState,
1014                             mStatusHints,
1015                             mExtras,
1016                             mIntentExtras,
1017                             mCreationTimeMillis,
1018                             mContactDisplayName,
1019                             mCallDirection,
1020                             mCallerNumberVerificationStatus);
1021         }
1022 
1023         /** {@hide} */
Details( String telecomCallId, Uri handle, int handlePresentation, String callerDisplayName, int callerDisplayNamePresentation, PhoneAccountHandle accountHandle, int capabilities, int properties, DisconnectCause disconnectCause, long connectTimeMillis, GatewayInfo gatewayInfo, int videoState, StatusHints statusHints, Bundle extras, Bundle intentExtras, long creationTimeMillis, String contactDisplayName, int callDirection, int callerNumberVerificationStatus)1024         public Details(
1025                 String telecomCallId,
1026                 Uri handle,
1027                 int handlePresentation,
1028                 String callerDisplayName,
1029                 int callerDisplayNamePresentation,
1030                 PhoneAccountHandle accountHandle,
1031                 int capabilities,
1032                 int properties,
1033                 DisconnectCause disconnectCause,
1034                 long connectTimeMillis,
1035                 GatewayInfo gatewayInfo,
1036                 int videoState,
1037                 StatusHints statusHints,
1038                 Bundle extras,
1039                 Bundle intentExtras,
1040                 long creationTimeMillis,
1041                 String contactDisplayName,
1042                 int callDirection,
1043                 int callerNumberVerificationStatus) {
1044             mTelecomCallId = telecomCallId;
1045             mHandle = handle;
1046             mHandlePresentation = handlePresentation;
1047             mCallerDisplayName = callerDisplayName;
1048             mCallerDisplayNamePresentation = callerDisplayNamePresentation;
1049             mAccountHandle = accountHandle;
1050             mCallCapabilities = capabilities;
1051             mCallProperties = properties;
1052             mDisconnectCause = disconnectCause;
1053             mConnectTimeMillis = connectTimeMillis;
1054             mGatewayInfo = gatewayInfo;
1055             mVideoState = videoState;
1056             mStatusHints = statusHints;
1057             mExtras = extras;
1058             mIntentExtras = intentExtras;
1059             mCreationTimeMillis = creationTimeMillis;
1060             mContactDisplayName = contactDisplayName;
1061             mCallDirection = callDirection;
1062             mCallerNumberVerificationStatus = callerNumberVerificationStatus;
1063         }
1064 
1065         /** {@hide} */
createFromParcelableCall(ParcelableCall parcelableCall)1066         public static Details createFromParcelableCall(ParcelableCall parcelableCall) {
1067             return new Details(
1068                     parcelableCall.getId(),
1069                     parcelableCall.getHandle(),
1070                     parcelableCall.getHandlePresentation(),
1071                     parcelableCall.getCallerDisplayName(),
1072                     parcelableCall.getCallerDisplayNamePresentation(),
1073                     parcelableCall.getAccountHandle(),
1074                     parcelableCall.getCapabilities(),
1075                     parcelableCall.getProperties(),
1076                     parcelableCall.getDisconnectCause(),
1077                     parcelableCall.getConnectTimeMillis(),
1078                     parcelableCall.getGatewayInfo(),
1079                     parcelableCall.getVideoState(),
1080                     parcelableCall.getStatusHints(),
1081                     parcelableCall.getExtras(),
1082                     parcelableCall.getIntentExtras(),
1083                     parcelableCall.getCreationTimeMillis(),
1084                     parcelableCall.getContactDisplayName(),
1085                     parcelableCall.getCallDirection(),
1086                     parcelableCall.getCallerNumberVerificationStatus());
1087         }
1088 
1089         @Override
toString()1090         public String toString() {
1091             StringBuilder sb = new StringBuilder();
1092             sb.append("[id: ");
1093             sb.append(mTelecomCallId);
1094             sb.append(", pa: ");
1095             sb.append(mAccountHandle);
1096             sb.append(", hdl: ");
1097             sb.append(Log.piiHandle(mHandle));
1098             sb.append(", hdlPres: ");
1099             sb.append(mHandlePresentation);
1100             sb.append(", videoState: ");
1101             sb.append(VideoProfile.videoStateToString(mVideoState));
1102             sb.append(", caps: ");
1103             sb.append(capabilitiesToString(mCallCapabilities));
1104             sb.append(", props: ");
1105             sb.append(propertiesToString(mCallProperties));
1106             sb.append("]");
1107             return sb.toString();
1108         }
1109     }
1110 
1111     /**
1112      * Defines callbacks which inform the {@link InCallService} of changes to a {@link Call}.
1113      * These callbacks can originate from the Telecom framework, or a {@link ConnectionService}
1114      * implementation.
1115      * <p>
1116      * You can handle these callbacks by extending the {@link Callback} class and overriding the
1117      * callbacks that your {@link InCallService} is interested in.  The callback methods include the
1118      * {@link Call} for which the callback applies, allowing reuse of a single instance of your
1119      * {@link Callback} implementation, if desired.
1120      * <p>
1121      * Use {@link Call#registerCallback(Callback)} to register your callback(s).  Ensure
1122      * {@link Call#unregisterCallback(Callback)} is called when you no longer require callbacks
1123      * (typically in {@link InCallService#onCallRemoved(Call)}).
1124      * Note: Callbacks which occur before you call {@link Call#registerCallback(Callback)} will not
1125      * reach your implementation of {@link Callback}, so it is important to register your callback
1126      * as soon as your {@link InCallService} is notified of a new call via
1127      * {@link InCallService#onCallAdded(Call)}.
1128      */
1129     public static abstract class Callback {
1130         /**
1131          * @hide
1132          */
1133         @IntDef(prefix = { "HANDOVER_" },
1134                 value = {HANDOVER_FAILURE_DEST_APP_REJECTED, HANDOVER_FAILURE_NOT_SUPPORTED,
1135                 HANDOVER_FAILURE_USER_REJECTED, HANDOVER_FAILURE_ONGOING_EMERGENCY_CALL,
1136                 HANDOVER_FAILURE_UNKNOWN})
1137         @Retention(RetentionPolicy.SOURCE)
1138         public @interface HandoverFailureErrors {}
1139 
1140         /**
1141          * Handover failure reason returned via {@link #onHandoverFailed(Call, int)} when the app
1142          * to handover the call to rejects the handover request.
1143          * <p>
1144          * Will be returned when {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} is called
1145          * and the destination {@link PhoneAccountHandle}'s {@link ConnectionService} returns a
1146          * {@code null} {@link Connection} from
1147          * {@link ConnectionService#onCreateOutgoingHandoverConnection(PhoneAccountHandle,
1148          * ConnectionRequest)}.
1149          * <p>
1150          * For more information on call handovers, see
1151          * {@link #handoverTo(PhoneAccountHandle, int, Bundle)}.
1152          */
1153         public static final int HANDOVER_FAILURE_DEST_APP_REJECTED = 1;
1154 
1155         /**
1156          * Handover failure reason returned via {@link #onHandoverFailed(Call, int)} when a handover
1157          * is initiated but the source or destination app does not support handover.
1158          * <p>
1159          * Will be returned when a handover is requested via
1160          * {@link #handoverTo(PhoneAccountHandle, int, Bundle)} and the destination
1161          * {@link PhoneAccountHandle} does not declare
1162          * {@link PhoneAccount#EXTRA_SUPPORTS_HANDOVER_TO}.  May also be returned when a handover is
1163          * requested at the {@link PhoneAccountHandle} for the current call (i.e. the source call's
1164          * {@link Details#getAccountHandle()}) does not declare
1165          * {@link PhoneAccount#EXTRA_SUPPORTS_HANDOVER_FROM}.
1166          * <p>
1167          * For more information on call handovers, see
1168          * {@link #handoverTo(PhoneAccountHandle, int, Bundle)}.
1169          */
1170         public static final int HANDOVER_FAILURE_NOT_SUPPORTED = 2;
1171 
1172         /**
1173          * Handover failure reason returned via {@link #onHandoverFailed(Call, int)} when the remote
1174          * user rejects the handover request.
1175          * <p>
1176          * For more information on call handovers, see
1177          * {@link #handoverTo(PhoneAccountHandle, int, Bundle)}.
1178          */
1179         public static final int HANDOVER_FAILURE_USER_REJECTED = 3;
1180 
1181         /**
1182          * Handover failure reason returned via {@link #onHandoverFailed(Call, int)} when there
1183          * is ongoing emergency call.
1184          * <p>
1185          * This error code is returned when {@link #handoverTo(PhoneAccountHandle, int, Bundle)} is
1186          * called on an emergency call, or if any other call is an emergency call.
1187          * <p>
1188          * Handovers are not permitted while there are ongoing emergency calls.
1189          * <p>
1190          * For more information on call handovers, see
1191          * {@link #handoverTo(PhoneAccountHandle, int, Bundle)}.
1192          */
1193         public static final int HANDOVER_FAILURE_ONGOING_EMERGENCY_CALL = 4;
1194 
1195         /**
1196          * Handover failure reason returned via {@link #onHandoverFailed(Call, int)} when a handover
1197          * fails for an unknown reason.
1198          * <p>
1199          * For more information on call handovers, see
1200          * {@link #handoverTo(PhoneAccountHandle, int, Bundle)}.
1201          */
1202         public static final int HANDOVER_FAILURE_UNKNOWN = 5;
1203 
1204         /**
1205          * Invoked when the state of this {@code Call} has changed. See {@link #getState()}.
1206          *
1207          * @param call The {@code Call} invoking this method.
1208          * @param state The new state of the {@code Call}.
1209          */
onStateChanged(Call call, int state)1210         public void onStateChanged(Call call, int state) {}
1211 
1212         /**
1213          * Invoked when the parent of this {@code Call} has changed. See {@link #getParent()}.
1214          *
1215          * @param call The {@code Call} invoking this method.
1216          * @param parent The new parent of the {@code Call}.
1217          */
onParentChanged(Call call, Call parent)1218         public void onParentChanged(Call call, Call parent) {}
1219 
1220         /**
1221          * Invoked when the children of this {@code Call} have changed. See {@link #getChildren()}.
1222          *
1223          * @param call The {@code Call} invoking this method.
1224          * @param children The new children of the {@code Call}.
1225          */
onChildrenChanged(Call call, List<Call> children)1226         public void onChildrenChanged(Call call, List<Call> children) {}
1227 
1228         /**
1229          * Invoked when the details of this {@code Call} have changed. See {@link #getDetails()}.
1230          *
1231          * @param call The {@code Call} invoking this method.
1232          * @param details A {@code Details} object describing the {@code Call}.
1233          */
onDetailsChanged(Call call, Details details)1234         public void onDetailsChanged(Call call, Details details) {}
1235 
1236         /**
1237          * Invoked when the text messages that can be used as responses to the incoming
1238          * {@code Call} are loaded from the relevant database.
1239          * See {@link #getCannedTextResponses()}.
1240          *
1241          * @param call The {@code Call} invoking this method.
1242          * @param cannedTextResponses The text messages useable as responses.
1243          */
onCannedTextResponsesLoaded(Call call, List<String> cannedTextResponses)1244         public void onCannedTextResponsesLoaded(Call call, List<String> cannedTextResponses) {}
1245 
1246         /**
1247          * Invoked when the post-dial sequence in the outgoing {@code Call} has reached a pause
1248          * character. This causes the post-dial signals to stop pending user confirmation. An
1249          * implementation should present this choice to the user and invoke
1250          * {@link #postDialContinue(boolean)} when the user makes the choice.
1251          *
1252          * @param call The {@code Call} invoking this method.
1253          * @param remainingPostDialSequence The post-dial characters that remain to be sent.
1254          */
onPostDialWait(Call call, String remainingPostDialSequence)1255         public void onPostDialWait(Call call, String remainingPostDialSequence) {}
1256 
1257         /**
1258          * Invoked when the {@code Call.VideoCall} of the {@code Call} has changed.
1259          *
1260          * @param call The {@code Call} invoking this method.
1261          * @param videoCall The {@code Call.VideoCall} associated with the {@code Call}.
1262          */
onVideoCallChanged(Call call, InCallService.VideoCall videoCall)1263         public void onVideoCallChanged(Call call, InCallService.VideoCall videoCall) {}
1264 
1265         /**
1266          * Invoked when the {@code Call} is destroyed. Clients should refrain from cleaning
1267          * up their UI for the {@code Call} in response to state transitions. Specifically,
1268          * clients should not assume that a {@link #onStateChanged(Call, int)} with a state of
1269          * {@link #STATE_DISCONNECTED} is the final notification the {@code Call} will send. Rather,
1270          * clients should wait for this method to be invoked.
1271          *
1272          * @param call The {@code Call} being destroyed.
1273          */
onCallDestroyed(Call call)1274         public void onCallDestroyed(Call call) {}
1275 
1276         /**
1277          * Invoked upon changes to the set of {@code Call}s with which this {@code Call} can be
1278          * conferenced.
1279          *
1280          * @param call The {@code Call} being updated.
1281          * @param conferenceableCalls The {@code Call}s with which this {@code Call} can be
1282          *          conferenced.
1283          */
onConferenceableCallsChanged(Call call, List<Call> conferenceableCalls)1284         public void onConferenceableCallsChanged(Call call, List<Call> conferenceableCalls) {}
1285 
1286         /**
1287          * Invoked when a {@link Call} receives an event from its associated {@link Connection} or
1288          * {@link Conference}.
1289          * <p>
1290          * Where possible, the Call should make an attempt to handle {@link Connection} events which
1291          * are part of the {@code android.telecom.*} namespace.  The Call should ignore any events
1292          * it does not wish to handle.  Unexpected events should be handled gracefully, as it is
1293          * possible that a {@link ConnectionService} has defined its own Connection events which a
1294          * Call is not aware of.
1295          * <p>
1296          * See {@link Connection#sendConnectionEvent(String, Bundle)},
1297          * {@link Conference#sendConferenceEvent(String, Bundle)}.
1298          *
1299          * @param call The {@code Call} receiving the event.
1300          * @param event The event.
1301          * @param extras Extras associated with the connection event.
1302          */
onConnectionEvent(Call call, String event, Bundle extras)1303         public void onConnectionEvent(Call call, String event, Bundle extras) {}
1304 
1305         /**
1306          * Invoked when the RTT mode changes for this call.
1307          * @param call The call whose RTT mode has changed.
1308          * @param mode the new RTT mode, one of
1309          * {@link RttCall#RTT_MODE_FULL}, {@link RttCall#RTT_MODE_HCO},
1310          *             or {@link RttCall#RTT_MODE_VCO}
1311          */
onRttModeChanged(Call call, int mode)1312         public void onRttModeChanged(Call call, int mode) {}
1313 
1314         /**
1315          * Invoked when the call's RTT status changes, either from off to on or from on to off.
1316          * @param call The call whose RTT status has changed.
1317          * @param enabled whether RTT is now enabled or disabled
1318          * @param rttCall the {@link RttCall} object to use for reading and writing if RTT is now
1319          *                on, null otherwise.
1320          */
onRttStatusChanged(Call call, boolean enabled, RttCall rttCall)1321         public void onRttStatusChanged(Call call, boolean enabled, RttCall rttCall) {}
1322 
1323         /**
1324          * Invoked when the remote end of the connection has requested that an RTT communication
1325          * channel be opened. A response to this should be sent via {@link #respondToRttRequest}
1326          * with the same ID that this method is invoked with.
1327          * @param call The call which the RTT request was placed on
1328          * @param id The ID of the request.
1329          */
onRttRequest(Call call, int id)1330         public void onRttRequest(Call call, int id) {}
1331 
1332         /**
1333          * Invoked when the RTT session failed to initiate for some reason, including rejection
1334          * by the remote party.
1335          * @param call The call which the RTT initiation failure occurred on.
1336          * @param reason One of the status codes defined in
1337          *               {@link android.telecom.Connection.RttModifyStatus}, with the exception of
1338          *               {@link android.telecom.Connection.RttModifyStatus#SESSION_MODIFY_REQUEST_SUCCESS}.
1339          */
onRttInitiationFailure(Call call, int reason)1340         public void onRttInitiationFailure(Call call, int reason) {}
1341 
1342         /**
1343          * Invoked when Call handover from one {@link PhoneAccount} to other {@link PhoneAccount}
1344          * has completed successfully.
1345          * <p>
1346          * For a full discussion of the handover process and the APIs involved, see
1347          * {@link android.telecom.Call#handoverTo(PhoneAccountHandle, int, Bundle)}.
1348          *
1349          * @param call The call which had initiated handover.
1350          */
onHandoverComplete(Call call)1351         public void onHandoverComplete(Call call) {}
1352 
1353         /**
1354          * Invoked when Call handover from one {@link PhoneAccount} to other {@link PhoneAccount}
1355          * has failed.
1356          * <p>
1357          * For a full discussion of the handover process and the APIs involved, see
1358          * {@link android.telecom.Call#handoverTo(PhoneAccountHandle, int, Bundle)}.
1359          *
1360          * @param call The call which had initiated handover.
1361          * @param failureReason Error reason for failure.
1362          */
onHandoverFailed(Call call, @HandoverFailureErrors int failureReason)1363         public void onHandoverFailed(Call call, @HandoverFailureErrors int failureReason) {}
1364     }
1365 
1366     /**
1367      * A class that holds the state that describes the state of the RTT channel to the remote
1368      * party, if it is active.
1369      */
1370     public static final class RttCall {
1371         /** @hide */
1372         @Retention(RetentionPolicy.SOURCE)
1373         @IntDef({RTT_MODE_INVALID, RTT_MODE_FULL, RTT_MODE_HCO, RTT_MODE_VCO})
1374         public @interface RttAudioMode {}
1375 
1376         /**
1377          * For metrics use. Default value in the proto.
1378          * @hide
1379          */
1380         public static final int RTT_MODE_INVALID = 0;
1381 
1382         /**
1383          * Indicates that there should be a bidirectional audio stream between the two parties
1384          * on the call.
1385          */
1386         public static final int RTT_MODE_FULL = 1;
1387 
1388         /**
1389          * Indicates that the local user should be able to hear the audio stream from the remote
1390          * user, but not vice versa. Equivalent to muting the microphone.
1391          */
1392         public static final int RTT_MODE_HCO = 2;
1393 
1394         /**
1395          * Indicates that the remote user should be able to hear the audio stream from the local
1396          * user, but not vice versa. Equivalent to setting the volume to zero.
1397          */
1398         public static final int RTT_MODE_VCO = 3;
1399 
1400         private static final int READ_BUFFER_SIZE = 1000;
1401 
1402         private InputStreamReader mReceiveStream;
1403         private OutputStreamWriter mTransmitStream;
1404         private int mRttMode;
1405         private final InCallAdapter mInCallAdapter;
1406         private final String mTelecomCallId;
1407         private char[] mReadBuffer = new char[READ_BUFFER_SIZE];
1408 
1409         /**
1410          * @hide
1411          */
RttCall(String telecomCallId, InputStreamReader receiveStream, OutputStreamWriter transmitStream, int mode, InCallAdapter inCallAdapter)1412         public RttCall(String telecomCallId, InputStreamReader receiveStream,
1413                 OutputStreamWriter transmitStream, int mode, InCallAdapter inCallAdapter) {
1414             mTelecomCallId = telecomCallId;
1415             mReceiveStream = receiveStream;
1416             mTransmitStream = transmitStream;
1417             mRttMode = mode;
1418             mInCallAdapter = inCallAdapter;
1419         }
1420 
1421         /**
1422          * Returns the current RTT audio mode.
1423          * @return Current RTT audio mode. One of {@link #RTT_MODE_FULL}, {@link #RTT_MODE_VCO}, or
1424          * {@link #RTT_MODE_HCO}.
1425          */
getRttAudioMode()1426         public int getRttAudioMode() {
1427             return mRttMode;
1428         }
1429 
1430         /**
1431          * Sets the RTT audio mode. The requested mode change will be communicated through
1432          * {@link Callback#onRttModeChanged(Call, int)}.
1433          * @param mode The desired RTT audio mode, one of {@link #RTT_MODE_FULL},
1434          * {@link #RTT_MODE_VCO}, or {@link #RTT_MODE_HCO}.
1435          */
setRttMode(@ttAudioMode int mode)1436         public void setRttMode(@RttAudioMode int mode) {
1437             mInCallAdapter.setRttMode(mTelecomCallId, mode);
1438         }
1439 
1440         /**
1441          * Writes the string {@param input} into the outgoing text stream for this RTT call. Since
1442          * RTT transmits text in real-time, this method should be called once for each character
1443          * the user enters into the device.
1444          *
1445          * This method is not thread-safe -- calling it from multiple threads simultaneously may
1446          * lead to interleaved text.
1447          * @param input The message to send to the remote user.
1448          */
write(String input)1449         public void write(String input) throws IOException {
1450             mTransmitStream.write(input);
1451             mTransmitStream.flush();
1452         }
1453 
1454         /**
1455          * Reads a string from the remote user, blocking if there is no data available. Returns
1456          * {@code null} if the RTT conversation has been terminated and there is no further data
1457          * to read.
1458          *
1459          * This method is not thread-safe -- calling it from multiple threads simultaneously may
1460          * lead to interleaved text.
1461          * @return A string containing text sent by the remote user, or {@code null} if the
1462          * conversation has been terminated or if there was an error while reading.
1463          */
read()1464         public String read() {
1465             try {
1466                 int numRead = mReceiveStream.read(mReadBuffer, 0, READ_BUFFER_SIZE);
1467                 if (numRead < 0) {
1468                     return null;
1469                 }
1470                 return new String(mReadBuffer, 0, numRead);
1471             } catch (IOException e) {
1472                 Log.w(this, "Exception encountered when reading from InputStreamReader: %s", e);
1473                 return null;
1474             }
1475         }
1476 
1477         /**
1478          * Non-blocking version of {@link #read()}. Returns {@code null} if there is nothing to
1479          * be read.
1480          * @return A string containing text entered by the user, or {@code null} if the user has
1481          * not entered any new text yet.
1482          */
readImmediately()1483         public String readImmediately() throws IOException {
1484             if (mReceiveStream.ready()) {
1485                 int numRead = mReceiveStream.read(mReadBuffer, 0, READ_BUFFER_SIZE);
1486                 if (numRead < 0) {
1487                     return null;
1488                 }
1489                 return new String(mReadBuffer, 0, numRead);
1490             } else {
1491                 return null;
1492             }
1493         }
1494 
1495         /**
1496          * Closes the underlying file descriptors
1497          * @hide
1498          */
close()1499         public void close() {
1500             try {
1501                 mReceiveStream.close();
1502             } catch (IOException e) {
1503                 // ignore
1504             }
1505             try {
1506                 mTransmitStream.close();
1507             } catch (IOException e) {
1508                 // ignore
1509             }
1510         }
1511     }
1512 
1513     /**
1514      * @deprecated Use {@code Call.Callback} instead.
1515      * @hide
1516      */
1517     @Deprecated
1518     @SystemApi
1519     public static abstract class Listener extends Callback { }
1520 
1521     private final Phone mPhone;
1522     private final String mTelecomCallId;
1523     private final InCallAdapter mInCallAdapter;
1524     private final List<String> mChildrenIds = new ArrayList<>();
1525     private final List<Call> mChildren = new ArrayList<>();
1526     private final List<Call> mUnmodifiableChildren = Collections.unmodifiableList(mChildren);
1527     private final List<CallbackRecord<Callback>> mCallbackRecords = new CopyOnWriteArrayList<>();
1528     private final List<Call> mConferenceableCalls = new ArrayList<>();
1529     private final List<Call> mUnmodifiableConferenceableCalls =
1530             Collections.unmodifiableList(mConferenceableCalls);
1531 
1532     private boolean mChildrenCached;
1533     private String mParentId = null;
1534     private String mActiveGenericConferenceChild = null;
1535     private int mState;
1536     private List<String> mCannedTextResponses = null;
1537     private String mCallingPackage;
1538     private int mTargetSdkVersion;
1539     private String mRemainingPostDialSequence;
1540     private VideoCallImpl mVideoCallImpl;
1541     private RttCall mRttCall;
1542     private Details mDetails;
1543     private Bundle mExtras;
1544 
1545     /**
1546      * Obtains the post-dial sequence remaining to be emitted by this {@code Call}, if any.
1547      *
1548      * @return The remaining post-dial sequence, or {@code null} if there is no post-dial sequence
1549      * remaining or this {@code Call} is not in a post-dial state.
1550      */
getRemainingPostDialSequence()1551     public String getRemainingPostDialSequence() {
1552         return mRemainingPostDialSequence;
1553     }
1554 
1555     /**
1556      * Instructs this {@link #STATE_RINGING} {@code Call} to answer.
1557      * @param videoState The video state in which to answer the call.
1558      */
answer(@ideoProfile.VideoState int videoState)1559     public void answer(@VideoProfile.VideoState int videoState) {
1560         mInCallAdapter.answerCall(mTelecomCallId, videoState);
1561     }
1562 
1563     /**
1564      * Instructs this {@link #STATE_RINGING} {@code Call} to deflect.
1565      *
1566      * @param address The address to which the call will be deflected.
1567      */
deflect(Uri address)1568     public void deflect(Uri address) {
1569         mInCallAdapter.deflectCall(mTelecomCallId, address);
1570     }
1571 
1572     /**
1573      * Instructs this {@link #STATE_RINGING} {@code Call} to reject.
1574      *
1575      * @param rejectWithMessage Whether to reject with a text message.
1576      * @param textMessage An optional text message with which to respond.
1577      */
reject(boolean rejectWithMessage, String textMessage)1578     public void reject(boolean rejectWithMessage, String textMessage) {
1579         mInCallAdapter.rejectCall(mTelecomCallId, rejectWithMessage, textMessage);
1580     }
1581 
1582     /**
1583      * Instructs the {@link ConnectionService} providing this {@link #STATE_RINGING} call that the
1584      * user has chosen to reject the call and has indicated a reason why the call is being rejected.
1585      *
1586      * @param rejectReason the reason the call is being rejected.
1587      */
reject(@ejectReason int rejectReason)1588     public void reject(@RejectReason int rejectReason) {
1589         mInCallAdapter.rejectCall(mTelecomCallId, rejectReason);
1590     }
1591 
1592     /**
1593      * Instructs this {@code Call} to be transferred to another number.
1594      *
1595      * @param targetNumber The address to which the call will be transferred.
1596      * @param isConfirmationRequired if {@code true} it will initiate ASSURED transfer,
1597      * if {@code false}, it will initiate BLIND transfer.
1598      *
1599      * @hide
1600      */
transfer(@onNull Uri targetNumber, boolean isConfirmationRequired)1601     public void transfer(@NonNull Uri targetNumber, boolean isConfirmationRequired) {
1602         mInCallAdapter.transferCall(mTelecomCallId, targetNumber, isConfirmationRequired);
1603     }
1604 
1605     /**
1606      * Instructs this {@code Call} to be transferred to another ongoing call.
1607      * This will initiate CONSULTATIVE transfer.
1608      * @param toCall The other ongoing {@code Call} to which this call will be transferred.
1609      *
1610      * @hide
1611      */
transfer(@onNull android.telecom.Call toCall)1612     public void transfer(@NonNull android.telecom.Call toCall) {
1613         mInCallAdapter.transferCall(mTelecomCallId, toCall.mTelecomCallId);
1614     }
1615 
1616     /**
1617      * Instructs this {@code Call} to disconnect.
1618      */
disconnect()1619     public void disconnect() {
1620         mInCallAdapter.disconnectCall(mTelecomCallId);
1621     }
1622 
1623     /**
1624      * Instructs this {@code Call} to go on hold.
1625      */
hold()1626     public void hold() {
1627         mInCallAdapter.holdCall(mTelecomCallId);
1628     }
1629 
1630     /**
1631      * Instructs this {@link #STATE_HOLDING} call to release from hold.
1632      */
unhold()1633     public void unhold() {
1634         mInCallAdapter.unholdCall(mTelecomCallId);
1635     }
1636 
1637     /**
1638      * Instructs Telecom to put the call into the background audio processing state.
1639      * <p>
1640      * This method can be called either when the call is in {@link #STATE_RINGING} or
1641      * {@link #STATE_ACTIVE}. After Telecom acknowledges the request by setting the call's state to
1642      * {@link #STATE_AUDIO_PROCESSING}, your app may setup the audio paths with the audio stack in
1643      * order to capture and play audio on the call stream.
1644      * <p>
1645      * This method can only be called by the default dialer app.
1646      * <p>
1647      * Apps built with SDK version {@link android.os.Build.VERSION_CODES#R} or later which are using
1648      * the microphone as part of audio processing should specify the foreground service type using
1649      * the attribute {@link android.R.attr#foregroundServiceType} in the {@link InCallService}
1650      * service element of the app's manifest file.
1651      * The {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_MICROPHONE} attribute should be specified.
1652      * @see <a href="https://developer.android.com/preview/privacy/foreground-service-types">
1653      * the Android Developer Site</a> for more information.
1654      * @hide
1655      */
1656     @SystemApi
1657     @TestApi
enterBackgroundAudioProcessing()1658     public void enterBackgroundAudioProcessing() {
1659         if (mState != STATE_ACTIVE && mState != STATE_RINGING) {
1660             throw new IllegalStateException("Call must be active or ringing");
1661         }
1662         mInCallAdapter.enterBackgroundAudioProcessing(mTelecomCallId);
1663     }
1664 
1665     /**
1666      * Instructs Telecom to come out of the background audio processing state requested by
1667      * {@link #enterBackgroundAudioProcessing()} or from the call screening service.
1668      *
1669      * This method can only be called when the call is in {@link #STATE_AUDIO_PROCESSING}.
1670      *
1671      * @param shouldRing If true, Telecom will put the call into the
1672      *                   {@link #STATE_SIMULATED_RINGING} state and notify other apps that there is
1673      *                   a ringing call. Otherwise, the call will go into {@link #STATE_ACTIVE}
1674      *                   immediately.
1675      * @hide
1676      */
1677     @SystemApi
1678     @TestApi
exitBackgroundAudioProcessing(boolean shouldRing)1679     public void exitBackgroundAudioProcessing(boolean shouldRing) {
1680         if (mState != STATE_AUDIO_PROCESSING) {
1681             throw new IllegalStateException("Call must in the audio processing state");
1682         }
1683         mInCallAdapter.exitBackgroundAudioProcessing(mTelecomCallId, shouldRing);
1684     }
1685 
1686     /**
1687      * Instructs this {@code Call} to play a dual-tone multi-frequency signaling (DTMF) tone.
1688      *
1689      * Any other currently playing DTMF tone in the specified call is immediately stopped.
1690      *
1691      * @param digit A character representing the DTMF digit for which to play the tone. This
1692      *         value must be one of {@code '0'} through {@code '9'}, {@code '*'} or {@code '#'}.
1693      */
playDtmfTone(char digit)1694     public void playDtmfTone(char digit) {
1695         mInCallAdapter.playDtmfTone(mTelecomCallId, digit);
1696     }
1697 
1698     /**
1699      * Instructs this {@code Call} to stop any dual-tone multi-frequency signaling (DTMF) tone
1700      * currently playing.
1701      *
1702      * DTMF tones are played by calling {@link #playDtmfTone(char)}. If no DTMF tone is
1703      * currently playing, this method will do nothing.
1704      */
stopDtmfTone()1705     public void stopDtmfTone() {
1706         mInCallAdapter.stopDtmfTone(mTelecomCallId);
1707     }
1708 
1709     /**
1710      * Instructs this {@code Call} to continue playing a post-dial DTMF string.
1711      *
1712      * A post-dial DTMF string is a string of digits entered after a phone number, when dialed,
1713      * that are immediately sent as DTMF tones to the recipient as soon as the connection is made.
1714      *
1715      * If the DTMF string contains a {@link TelecomManager#DTMF_CHARACTER_PAUSE} symbol, this
1716      * {@code Call} will temporarily pause playing the tones for a pre-defined period of time.
1717      *
1718      * If the DTMF string contains a {@link TelecomManager#DTMF_CHARACTER_WAIT} symbol, this
1719      * {@code Call} will pause playing the tones and notify callbacks via
1720      * {@link Callback#onPostDialWait(Call, String)}. At this point, the in-call app
1721      * should display to the user an indication of this state and an affordance to continue
1722      * the postdial sequence. When the user decides to continue the postdial sequence, the in-call
1723      * app should invoke the {@link #postDialContinue(boolean)} method.
1724      *
1725      * @param proceed Whether or not to continue with the post-dial sequence.
1726      */
postDialContinue(boolean proceed)1727     public void postDialContinue(boolean proceed) {
1728         mInCallAdapter.postDialContinue(mTelecomCallId, proceed);
1729     }
1730 
1731     /**
1732      * Notifies this {@code Call} that an account has been selected and to proceed with placing
1733      * an outgoing call. Optionally sets this account as the default account.
1734      */
phoneAccountSelected(PhoneAccountHandle accountHandle, boolean setDefault)1735     public void phoneAccountSelected(PhoneAccountHandle accountHandle, boolean setDefault) {
1736         mInCallAdapter.phoneAccountSelected(mTelecomCallId, accountHandle, setDefault);
1737 
1738     }
1739 
1740     /**
1741      * Instructs this {@code Call} to enter a conference.
1742      *
1743      * @param callToConferenceWith The other call with which to conference.
1744      */
conference(Call callToConferenceWith)1745     public void conference(Call callToConferenceWith) {
1746         if (callToConferenceWith != null) {
1747             mInCallAdapter.conference(mTelecomCallId, callToConferenceWith.mTelecomCallId);
1748         }
1749     }
1750 
1751     /**
1752      * Instructs this {@code Call} to split from any conference call with which it may be
1753      * connected.
1754      */
splitFromConference()1755     public void splitFromConference() {
1756         mInCallAdapter.splitFromConference(mTelecomCallId);
1757     }
1758 
1759     /**
1760      * Merges the calls within this conference. See {@link Details#CAPABILITY_MERGE_CONFERENCE}.
1761      */
mergeConference()1762     public void mergeConference() {
1763         mInCallAdapter.mergeConference(mTelecomCallId);
1764     }
1765 
1766     /**
1767      * Swaps the calls within this conference. See {@link Details#CAPABILITY_SWAP_CONFERENCE}.
1768      */
swapConference()1769     public void swapConference() {
1770         mInCallAdapter.swapConference(mTelecomCallId);
1771     }
1772 
1773     /**
1774      * Pulls participants to existing call by forming a conference call.
1775      * See {@link Details#CAPABILITY_ADD_PARTICIPANT}.
1776      *
1777      * @param participants participants to be pulled to existing call.
1778      * @hide
1779      */
addConferenceParticipants(@onNull List<Uri> participants)1780     public void addConferenceParticipants(@NonNull List<Uri> participants) {
1781         mInCallAdapter.addConferenceParticipants(mTelecomCallId, participants);
1782     }
1783 
1784     /**
1785      * Initiates a request to the {@link ConnectionService} to pull an external call to the local
1786      * device.
1787      * <p>
1788      * Calls to this method are ignored if the call does not have the
1789      * {@link Call.Details#PROPERTY_IS_EXTERNAL_CALL} property set.
1790      * <p>
1791      * An {@link InCallService} will only see calls which support this method if it has the
1792      * {@link TelecomManager#METADATA_INCLUDE_EXTERNAL_CALLS} metadata set to {@code true}
1793      * in its manifest.
1794      */
pullExternalCall()1795     public void pullExternalCall() {
1796         // If this isn't an external call, ignore the request.
1797         if (!mDetails.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)) {
1798             return;
1799         }
1800 
1801         mInCallAdapter.pullExternalCall(mTelecomCallId);
1802     }
1803 
1804     /**
1805      * Sends a {@code Call} event from this {@code Call} to the associated {@link Connection} in
1806      * the {@link ConnectionService}.
1807      * <p>
1808      * Call events are used to communicate point in time information from an {@link InCallService}
1809      * to a {@link ConnectionService}.  A {@link ConnectionService} implementation could define
1810      * events which enable the {@link InCallService}, for example, toggle a unique feature of the
1811      * {@link ConnectionService}.
1812      * <p>
1813      * A {@link ConnectionService} can communicate to the {@link InCallService} using
1814      * {@link Connection#sendConnectionEvent(String, Bundle)}.
1815      * <p>
1816      * Events are exposed to {@link ConnectionService} implementations via
1817      * {@link android.telecom.Connection#onCallEvent(String, Bundle)}.
1818      * <p>
1819      * No assumptions should be made as to how a {@link ConnectionService} will handle these events.
1820      * The {@link InCallService} must assume that the {@link ConnectionService} could chose to
1821      * ignore some events altogether.
1822      * <p>
1823      * Events should be fully qualified (e.g., {@code com.example.event.MY_EVENT}) to avoid
1824      * conflicts between {@link InCallService} implementations.  Further, {@link InCallService}
1825      * implementations shall not re-purpose events in the {@code android.*} namespace, nor shall
1826      * they define their own event types in this namespace.  When defining a custom event type,
1827      * ensure the contents of the extras {@link Bundle} is clearly defined.  Extra keys for this
1828      * bundle should be named similar to the event type (e.g. {@code com.example.extra.MY_EXTRA}).
1829      * <p>
1830      * When defining events and the associated extras, it is important to keep their behavior
1831      * consistent when the associated {@link InCallService} is updated.  Support for deprecated
1832      * events/extras should me maintained to ensure backwards compatibility with older
1833      * {@link ConnectionService} implementations which were built to support the older behavior.
1834      *
1835      * @param event The connection event.
1836      * @param extras Bundle containing extra information associated with the event.
1837      */
sendCallEvent(String event, Bundle extras)1838     public void sendCallEvent(String event, Bundle extras) {
1839         mInCallAdapter.sendCallEvent(mTelecomCallId, event, mTargetSdkVersion, extras);
1840     }
1841 
1842     /**
1843      * Sends an RTT upgrade request to the remote end of the connection. Success is not
1844      * guaranteed, and notification of success will be via the
1845      * {@link Callback#onRttStatusChanged(Call, boolean, RttCall)} callback.
1846      */
sendRttRequest()1847     public void sendRttRequest() {
1848         mInCallAdapter.sendRttRequest(mTelecomCallId);
1849     }
1850 
1851     /**
1852      * Responds to an RTT request received via the {@link Callback#onRttRequest(Call, int)} )}
1853      * callback.
1854      * The ID used here should be the same as the ID that was received via the callback.
1855      * @param id The request ID received via {@link Callback#onRttRequest(Call, int)}
1856      * @param accept {@code true} if the RTT request should be accepted, {@code false} otherwise.
1857      */
respondToRttRequest(int id, boolean accept)1858     public void respondToRttRequest(int id, boolean accept) {
1859         mInCallAdapter.respondToRttRequest(mTelecomCallId, id, accept);
1860     }
1861 
1862     /**
1863      * Initiates a handover of this {@link Call} to the {@link ConnectionService} identified
1864      * by {@code toHandle}.  The videoState specified indicates the desired video state after the
1865      * handover.
1866      * <p>
1867      * A call handover is the process where an ongoing call is transferred from one app (i.e.
1868      * {@link ConnectionService} to another app.  The user could, for example, choose to continue a
1869      * mobile network call in a video calling app.  The mobile network call via the Telephony stack
1870      * is referred to as the source of the handover, and the video calling app is referred to as the
1871      * destination.
1872      * <p>
1873      * When considering a handover scenario the device this method is called on is considered the
1874      * <em>initiating</em> device (since the user initiates the handover from this device), and the
1875      * other device is considered the <em>receiving</em> device.
1876      * <p>
1877      * When this method is called on the <em>initiating</em> device, the Telecom framework will bind
1878      * to the {@link ConnectionService} defined by the {@code toHandle} {@link PhoneAccountHandle}
1879      * and invoke
1880      * {@link ConnectionService#onCreateOutgoingHandoverConnection(PhoneAccountHandle,
1881      * ConnectionRequest)} to inform the destination app that a request has been made to handover a
1882      * call to it.  The app returns an instance of {@link Connection} to represent the handover call
1883      * At this point the app should display UI to indicate to the user that a call
1884      * handover is in process.
1885      * <p>
1886      * The destination app is responsible for communicating the handover request from the
1887      * <em>initiating</em> device to the <em>receiving</em> device.
1888      * <p>
1889      * When the app on the <em>receiving</em> device receives the handover request, it calls
1890      * {@link TelecomManager#acceptHandover(Uri, int, PhoneAccountHandle)} to continue the handover
1891      * process from the <em>initiating</em> device to the <em>receiving</em> device.  At this point
1892      * the destination app on the <em>receiving</em> device should show UI to allow the user to
1893      * choose whether they want to continue their call in the destination app.
1894      * <p>
1895      * When the destination app on the <em>receiving</em> device calls
1896      * {@link TelecomManager#acceptHandover(Uri, int, PhoneAccountHandle)}, Telecom will bind to its
1897      * {@link ConnectionService} and call
1898      * {@link ConnectionService#onCreateIncomingHandoverConnection(PhoneAccountHandle,
1899      * ConnectionRequest)} to inform it of the handover request.  The app returns an instance of
1900      * {@link Connection} to represent the handover call.
1901      * <p>
1902      * If the user of the <em>receiving</em> device accepts the handover, the app calls
1903      * {@link Connection#setActive()} to complete the handover process; Telecom will disconnect the
1904      * original call.  If the user rejects the handover, the app calls
1905      * {@link Connection#setDisconnected(DisconnectCause)} and specifies a {@link DisconnectCause}
1906      * of {@link DisconnectCause#CANCELED} to indicate that the handover has been cancelled.
1907      * <p>
1908      * Telecom will only allow handovers from {@link PhoneAccount}s which declare
1909      * {@link PhoneAccount#EXTRA_SUPPORTS_HANDOVER_FROM}.  Similarly, the {@link PhoneAccount}
1910      * specified by {@code toHandle} must declare {@link PhoneAccount#EXTRA_SUPPORTS_HANDOVER_TO}.
1911      * <p>
1912      * Errors in the handover process are reported to the {@link InCallService} via
1913      * {@link Callback#onHandoverFailed(Call, int)}.  Errors in the handover process are reported to
1914      * the involved {@link ConnectionService}s via
1915      * {@link ConnectionService#onHandoverFailed(ConnectionRequest, int)}.
1916      *
1917      * @param toHandle {@link PhoneAccountHandle} of the {@link ConnectionService} to handover
1918      *                 this call to.
1919      * @param videoState Indicates the video state desired after the handover (see the
1920      *               {@code STATE_*} constants defined in {@link VideoProfile}).
1921      * @param extras Bundle containing extra information to be passed to the
1922      *               {@link ConnectionService}
1923      */
handoverTo(PhoneAccountHandle toHandle, @VideoProfile.VideoState int videoState, Bundle extras)1924     public void handoverTo(PhoneAccountHandle toHandle, @VideoProfile.VideoState int videoState,
1925             Bundle extras) {
1926         mInCallAdapter.handoverTo(mTelecomCallId, toHandle, videoState, extras);
1927     }
1928 
1929     /**
1930      * Terminate the RTT session on this call. The resulting state change will be notified via
1931      * the {@link Callback#onRttStatusChanged(Call, boolean, RttCall)} callback.
1932      */
stopRtt()1933     public void stopRtt() {
1934         mInCallAdapter.stopRtt(mTelecomCallId);
1935     }
1936 
1937     /**
1938      * Adds some extras to this {@link Call}.  Existing keys are replaced and new ones are
1939      * added.
1940      * <p>
1941      * No assumptions should be made as to how an In-Call UI or service will handle these
1942      * extras.  Keys should be fully qualified (e.g., com.example.MY_EXTRA) to avoid conflicts.
1943      *
1944      * @param extras The extras to add.
1945      */
putExtras(Bundle extras)1946     public final void putExtras(Bundle extras) {
1947         if (extras == null) {
1948             return;
1949         }
1950 
1951         if (mExtras == null) {
1952             mExtras = new Bundle();
1953         }
1954         mExtras.putAll(extras);
1955         mInCallAdapter.putExtras(mTelecomCallId, extras);
1956     }
1957 
1958     /**
1959      * Adds a boolean extra to this {@link Call}.
1960      *
1961      * @param key The extra key.
1962      * @param value The value.
1963      * @hide
1964      */
putExtra(String key, boolean value)1965     public final void putExtra(String key, boolean value) {
1966         if (mExtras == null) {
1967             mExtras = new Bundle();
1968         }
1969         mExtras.putBoolean(key, value);
1970         mInCallAdapter.putExtra(mTelecomCallId, key, value);
1971     }
1972 
1973     /**
1974      * Adds an integer extra to this {@link Call}.
1975      *
1976      * @param key The extra key.
1977      * @param value The value.
1978      * @hide
1979      */
putExtra(String key, int value)1980     public final void putExtra(String key, int value) {
1981         if (mExtras == null) {
1982             mExtras = new Bundle();
1983         }
1984         mExtras.putInt(key, value);
1985         mInCallAdapter.putExtra(mTelecomCallId, key, value);
1986     }
1987 
1988     /**
1989      * Adds a string extra to this {@link Call}.
1990      *
1991      * @param key The extra key.
1992      * @param value The value.
1993      * @hide
1994      */
putExtra(String key, String value)1995     public final void putExtra(String key, String value) {
1996         if (mExtras == null) {
1997             mExtras = new Bundle();
1998         }
1999         mExtras.putString(key, value);
2000         mInCallAdapter.putExtra(mTelecomCallId, key, value);
2001     }
2002 
2003     /**
2004      * Removes extras from this {@link Call}.
2005      *
2006      * @param keys The keys of the extras to remove.
2007      */
removeExtras(List<String> keys)2008     public final void removeExtras(List<String> keys) {
2009         if (mExtras != null) {
2010             for (String key : keys) {
2011                 mExtras.remove(key);
2012             }
2013             if (mExtras.size() == 0) {
2014                 mExtras = null;
2015             }
2016         }
2017         mInCallAdapter.removeExtras(mTelecomCallId, keys);
2018     }
2019 
2020     /**
2021      * Removes extras from this {@link Call}.
2022      *
2023      * @param keys The keys of the extras to remove.
2024      */
removeExtras(String .... keys)2025     public final void removeExtras(String ... keys) {
2026         removeExtras(Arrays.asList(keys));
2027     }
2028 
2029     /**
2030      * Obtains the parent of this {@code Call} in a conference, if any.
2031      *
2032      * @return The parent {@code Call}, or {@code null} if this {@code Call} is not a
2033      * child of any conference {@code Call}s.
2034      */
getParent()2035     public Call getParent() {
2036         if (mParentId != null) {
2037             return mPhone.internalGetCallByTelecomId(mParentId);
2038         }
2039         return null;
2040     }
2041 
2042     /**
2043      * Obtains the children of this conference {@code Call}, if any.
2044      *
2045      * @return The children of this {@code Call} if this {@code Call} is a conference, or an empty
2046      * {@code List} otherwise.
2047      */
getChildren()2048     public List<Call> getChildren() {
2049         if (!mChildrenCached) {
2050             mChildrenCached = true;
2051             mChildren.clear();
2052 
2053             for(String id : mChildrenIds) {
2054                 Call call = mPhone.internalGetCallByTelecomId(id);
2055                 if (call == null) {
2056                     // At least one child was still not found, so do not save true for "cached"
2057                     mChildrenCached = false;
2058                 } else {
2059                     mChildren.add(call);
2060                 }
2061             }
2062         }
2063 
2064         return mUnmodifiableChildren;
2065     }
2066 
2067     /**
2068      * Returns the list of {@code Call}s with which this {@code Call} is allowed to conference.
2069      *
2070      * @return The list of conferenceable {@code Call}s.
2071      */
getConferenceableCalls()2072     public List<Call> getConferenceableCalls() {
2073         return mUnmodifiableConferenceableCalls;
2074     }
2075 
2076     /**
2077      * Obtains the state of this {@code Call}.
2078      *
2079      * @return A state value, chosen from the {@code STATE_*} constants.
2080      */
getState()2081     public int getState() {
2082         return mState;
2083     }
2084 
2085     /**
2086      * Returns the child {@link Call} in a generic conference that is currently active.
2087      *
2088      * A "generic conference" is the mechanism used to support two simultaneous calls on a device
2089      * in CDMA networks. It is effectively equivalent to having one call active and one call on hold
2090      * in GSM or IMS calls. This method returns the currently active call.
2091      *
2092      * In a generic conference, the network exposes the conference to us as a single call, and we
2093      * switch between talking to the two participants using a CDMA flash command. Since the network
2094      * exposes no additional information about the call, the only way we know which caller we're
2095      * currently talking to is by keeping track of the flash commands that we've sent to the
2096      * network.
2097      *
2098      * For calls that are not generic conferences, or when the generic conference has more than
2099      * 2 children, returns {@code null}.
2100      * @see Details#PROPERTY_GENERIC_CONFERENCE
2101      * @return The active child call.
2102      */
getGenericConferenceActiveChildCall()2103     public @Nullable Call getGenericConferenceActiveChildCall() {
2104         if (mActiveGenericConferenceChild != null) {
2105             return mPhone.internalGetCallByTelecomId(mActiveGenericConferenceChild);
2106         }
2107         return null;
2108     }
2109 
2110     /**
2111      * Obtains a list of canned, pre-configured message responses to present to the user as
2112      * ways of rejecting this {@code Call} using via a text message.
2113      *
2114      * @see #reject(boolean, String)
2115      *
2116      * @return A list of canned text message responses.
2117      */
getCannedTextResponses()2118     public List<String> getCannedTextResponses() {
2119         return mCannedTextResponses;
2120     }
2121 
2122     /**
2123      * Obtains an object that can be used to display video from this {@code Call}.
2124      *
2125      * @return An {@code Call.VideoCall}.
2126      */
getVideoCall()2127     public InCallService.VideoCall getVideoCall() {
2128         return mVideoCallImpl;
2129     }
2130 
2131     /**
2132      * Obtains an object containing call details.
2133      *
2134      * @return A {@link Details} object. Depending on the state of the {@code Call}, the
2135      * result may be {@code null}.
2136      */
getDetails()2137     public Details getDetails() {
2138         return mDetails;
2139     }
2140 
2141     /**
2142      * Returns this call's RttCall object. The {@link RttCall} instance is used to send and
2143      * receive RTT text data, as well as to change the RTT mode.
2144      * @return A {@link Call.RttCall}. {@code null} if there is no active RTT connection.
2145      */
getRttCall()2146     public @Nullable RttCall getRttCall() {
2147         return mRttCall;
2148     }
2149 
2150     /**
2151      * Returns whether this call has an active RTT connection.
2152      * @return true if there is a connection, false otherwise.
2153      */
isRttActive()2154     public boolean isRttActive() {
2155         return mRttCall != null && mDetails.hasProperty(Details.PROPERTY_RTT);
2156     }
2157 
2158     /**
2159      * Registers a callback to this {@code Call}.
2160      *
2161      * @param callback A {@code Callback}.
2162      */
registerCallback(Callback callback)2163     public void registerCallback(Callback callback) {
2164         registerCallback(callback, new Handler());
2165     }
2166 
2167     /**
2168      * Registers a callback to this {@code Call}.
2169      *
2170      * @param callback A {@code Callback}.
2171      * @param handler A handler which command and status changes will be delivered to.
2172      */
registerCallback(Callback callback, Handler handler)2173     public void registerCallback(Callback callback, Handler handler) {
2174         unregisterCallback(callback);
2175         // Don't allow new callback registration if the call is already being destroyed.
2176         if (callback != null && handler != null && mState != STATE_DISCONNECTED) {
2177             mCallbackRecords.add(new CallbackRecord<Callback>(callback, handler));
2178         }
2179     }
2180 
2181     /**
2182      * Unregisters a callback from this {@code Call}.
2183      *
2184      * @param callback A {@code Callback}.
2185      */
unregisterCallback(Callback callback)2186     public void unregisterCallback(Callback callback) {
2187         // Don't allow callback deregistration if the call is already being destroyed.
2188         if (callback != null && mState != STATE_DISCONNECTED) {
2189             for (CallbackRecord<Callback> record : mCallbackRecords) {
2190                 if (record.getCallback() == callback) {
2191                     mCallbackRecords.remove(record);
2192                     break;
2193                 }
2194             }
2195         }
2196     }
2197 
2198     @Override
toString()2199     public String toString() {
2200         return new StringBuilder().
2201                 append("Call [id: ").
2202                 append(mTelecomCallId).
2203                 append(", state: ").
2204                 append(stateToString(mState)).
2205                 append(", details: ").
2206                 append(mDetails).
2207                 append("]").toString();
2208     }
2209 
2210     /**
2211      * @param state An integer value of a {@code STATE_*} constant.
2212      * @return A string representation of the value.
2213      */
stateToString(int state)2214     private static String stateToString(int state) {
2215         switch (state) {
2216             case STATE_NEW:
2217                 return "NEW";
2218             case STATE_RINGING:
2219                 return "RINGING";
2220             case STATE_DIALING:
2221                 return "DIALING";
2222             case STATE_ACTIVE:
2223                 return "ACTIVE";
2224             case STATE_HOLDING:
2225                 return "HOLDING";
2226             case STATE_DISCONNECTED:
2227                 return "DISCONNECTED";
2228             case STATE_CONNECTING:
2229                 return "CONNECTING";
2230             case STATE_DISCONNECTING:
2231                 return "DISCONNECTING";
2232             case STATE_SELECT_PHONE_ACCOUNT:
2233                 return "SELECT_PHONE_ACCOUNT";
2234             case STATE_SIMULATED_RINGING:
2235                 return "SIMULATED_RINGING";
2236             case STATE_AUDIO_PROCESSING:
2237                 return "AUDIO_PROCESSING";
2238             default:
2239                 Log.w(Call.class, "Unknown state %d", state);
2240                 return "UNKNOWN";
2241         }
2242     }
2243 
2244     /**
2245      * Adds a listener to this {@code Call}.
2246      *
2247      * @param listener A {@code Listener}.
2248      * @deprecated Use {@link #registerCallback} instead.
2249      * @hide
2250      */
2251     @Deprecated
2252     @SystemApi
addListener(Listener listener)2253     public void addListener(Listener listener) {
2254         registerCallback(listener);
2255     }
2256 
2257     /**
2258      * Removes a listener from this {@code Call}.
2259      *
2260      * @param listener A {@code Listener}.
2261      * @deprecated Use {@link #unregisterCallback} instead.
2262      * @hide
2263      */
2264     @Deprecated
2265     @SystemApi
removeListener(Listener listener)2266     public void removeListener(Listener listener) {
2267         unregisterCallback(listener);
2268     }
2269 
2270     /** {@hide} */
Call(Phone phone, String telecomCallId, InCallAdapter inCallAdapter, String callingPackage, int targetSdkVersion)2271     Call(Phone phone, String telecomCallId, InCallAdapter inCallAdapter, String callingPackage,
2272          int targetSdkVersion) {
2273         mPhone = phone;
2274         mTelecomCallId = telecomCallId;
2275         mInCallAdapter = inCallAdapter;
2276         mState = STATE_NEW;
2277         mCallingPackage = callingPackage;
2278         mTargetSdkVersion = targetSdkVersion;
2279     }
2280 
2281     /** {@hide} */
Call(Phone phone, String telecomCallId, InCallAdapter inCallAdapter, int state, String callingPackage, int targetSdkVersion)2282     Call(Phone phone, String telecomCallId, InCallAdapter inCallAdapter, int state,
2283             String callingPackage, int targetSdkVersion) {
2284         mPhone = phone;
2285         mTelecomCallId = telecomCallId;
2286         mInCallAdapter = inCallAdapter;
2287         mState = state;
2288         mCallingPackage = callingPackage;
2289         mTargetSdkVersion = targetSdkVersion;
2290     }
2291 
2292     /** {@hide} */
internalGetCallId()2293     final String internalGetCallId() {
2294         return mTelecomCallId;
2295     }
2296 
2297     /** {@hide} */
internalUpdate(ParcelableCall parcelableCall, Map<String, Call> callIdMap)2298     final void internalUpdate(ParcelableCall parcelableCall, Map<String, Call> callIdMap) {
2299 
2300         // First, we update the internal state as far as possible before firing any updates.
2301         Details details = Details.createFromParcelableCall(parcelableCall);
2302         boolean detailsChanged = !Objects.equals(mDetails, details);
2303         if (detailsChanged) {
2304             mDetails = details;
2305         }
2306 
2307         boolean cannedTextResponsesChanged = false;
2308         if (mCannedTextResponses == null && parcelableCall.getCannedSmsResponses() != null
2309                 && !parcelableCall.getCannedSmsResponses().isEmpty()) {
2310             mCannedTextResponses =
2311                     Collections.unmodifiableList(parcelableCall.getCannedSmsResponses());
2312             cannedTextResponsesChanged = true;
2313         }
2314 
2315         IVideoProvider previousVideoProvider = mVideoCallImpl == null ? null :
2316                 mVideoCallImpl.getVideoProvider();
2317         IVideoProvider newVideoProvider = parcelableCall.getVideoProvider();
2318 
2319         // parcelableCall.isVideoCallProviderChanged is only true when we have a video provider
2320         // specified; so we should check if the actual IVideoProvider changes as well.
2321         boolean videoCallChanged = parcelableCall.isVideoCallProviderChanged()
2322                 && !Objects.equals(previousVideoProvider, newVideoProvider);
2323         if (videoCallChanged) {
2324             if (mVideoCallImpl != null) {
2325                 mVideoCallImpl.destroy();
2326             }
2327             mVideoCallImpl = parcelableCall.isVideoCallProviderChanged() ?
2328                     parcelableCall.getVideoCallImpl(mCallingPackage, mTargetSdkVersion) : null;
2329         }
2330 
2331         if (mVideoCallImpl != null) {
2332             mVideoCallImpl.setVideoState(getDetails().getVideoState());
2333         }
2334 
2335         int state = parcelableCall.getState();
2336         if (mTargetSdkVersion < Phone.SDK_VERSION_R && state == Call.STATE_SIMULATED_RINGING) {
2337             state = Call.STATE_RINGING;
2338         }
2339         boolean stateChanged = mState != state;
2340         if (stateChanged) {
2341             mState = state;
2342         }
2343 
2344         String parentId = parcelableCall.getParentCallId();
2345         boolean parentChanged = !Objects.equals(mParentId, parentId);
2346         if (parentChanged) {
2347             mParentId = parentId;
2348         }
2349 
2350         List<String> childCallIds = parcelableCall.getChildCallIds();
2351         boolean childrenChanged = !Objects.equals(childCallIds, mChildrenIds);
2352         if (childrenChanged) {
2353             mChildrenIds.clear();
2354             mChildrenIds.addAll(parcelableCall.getChildCallIds());
2355             mChildrenCached = false;
2356         }
2357 
2358         String activeChildCallId = parcelableCall.getActiveChildCallId();
2359         boolean activeChildChanged = !Objects.equals(activeChildCallId,
2360                 mActiveGenericConferenceChild);
2361         if (activeChildChanged) {
2362             mActiveGenericConferenceChild = activeChildCallId;
2363         }
2364 
2365         List<String> conferenceableCallIds = parcelableCall.getConferenceableCallIds();
2366         List<Call> conferenceableCalls = new ArrayList<Call>(conferenceableCallIds.size());
2367         for (String otherId : conferenceableCallIds) {
2368             if (callIdMap.containsKey(otherId)) {
2369                 conferenceableCalls.add(callIdMap.get(otherId));
2370             }
2371         }
2372 
2373         if (!Objects.equals(mConferenceableCalls, conferenceableCalls)) {
2374             mConferenceableCalls.clear();
2375             mConferenceableCalls.addAll(conferenceableCalls);
2376             fireConferenceableCallsChanged();
2377         }
2378 
2379         boolean isRttChanged = false;
2380         boolean rttModeChanged = false;
2381         if (parcelableCall.getIsRttCallChanged()
2382                 && mDetails.hasProperty(Details.PROPERTY_RTT)) {
2383             ParcelableRttCall parcelableRttCall = parcelableCall.getParcelableRttCall();
2384             InputStreamReader receiveStream = new InputStreamReader(
2385                     new ParcelFileDescriptor.AutoCloseInputStream(
2386                             parcelableRttCall.getReceiveStream()),
2387                     StandardCharsets.UTF_8);
2388             OutputStreamWriter transmitStream = new OutputStreamWriter(
2389                     new ParcelFileDescriptor.AutoCloseOutputStream(
2390                             parcelableRttCall.getTransmitStream()),
2391                     StandardCharsets.UTF_8);
2392             RttCall newRttCall = new Call.RttCall(mTelecomCallId,
2393                     receiveStream, transmitStream, parcelableRttCall.getRttMode(), mInCallAdapter);
2394             if (mRttCall == null) {
2395                 isRttChanged = true;
2396             } else if (mRttCall.getRttAudioMode() != newRttCall.getRttAudioMode()) {
2397                 rttModeChanged = true;
2398             }
2399             mRttCall = newRttCall;
2400         } else if (mRttCall != null && parcelableCall.getParcelableRttCall() == null
2401                 && parcelableCall.getIsRttCallChanged()) {
2402             isRttChanged = true;
2403             mRttCall = null;
2404         }
2405 
2406         // Now we fire updates, ensuring that any client who listens to any of these notifications
2407         // gets the most up-to-date state.
2408 
2409         if (stateChanged) {
2410             fireStateChanged(mState);
2411         }
2412         if (detailsChanged) {
2413             fireDetailsChanged(mDetails);
2414         }
2415         if (cannedTextResponsesChanged) {
2416             fireCannedTextResponsesLoaded(mCannedTextResponses);
2417         }
2418         if (videoCallChanged) {
2419             fireVideoCallChanged(mVideoCallImpl);
2420         }
2421         if (parentChanged) {
2422             fireParentChanged(getParent());
2423         }
2424         if (childrenChanged || activeChildChanged) {
2425             fireChildrenChanged(getChildren());
2426         }
2427         if (isRttChanged) {
2428             fireOnIsRttChanged(mRttCall != null, mRttCall);
2429         }
2430         if (rttModeChanged) {
2431             fireOnRttModeChanged(mRttCall.getRttAudioMode());
2432         }
2433 
2434         // If we have transitioned to DISCONNECTED, that means we need to notify clients and
2435         // remove ourselves from the Phone. Note that we do this after completing all state updates
2436         // so a client can cleanly transition all their UI to the state appropriate for a
2437         // DISCONNECTED Call while still relying on the existence of that Call in the Phone's list.
2438         if (mState == STATE_DISCONNECTED) {
2439             fireCallDestroyed();
2440         }
2441     }
2442 
2443     /** {@hide} */
internalSetPostDialWait(String remaining)2444     final void internalSetPostDialWait(String remaining) {
2445         mRemainingPostDialSequence = remaining;
2446         firePostDialWait(mRemainingPostDialSequence);
2447     }
2448 
2449     /** {@hide} */
internalSetDisconnected()2450     final void internalSetDisconnected() {
2451         if (mState != Call.STATE_DISCONNECTED) {
2452             mState = Call.STATE_DISCONNECTED;
2453             fireStateChanged(mState);
2454             fireCallDestroyed();
2455         }
2456     }
2457 
2458     /** {@hide} */
internalOnConnectionEvent(String event, Bundle extras)2459     final void internalOnConnectionEvent(String event, Bundle extras) {
2460         fireOnConnectionEvent(event, extras);
2461     }
2462 
2463     /** {@hide} */
internalOnRttUpgradeRequest(final int requestId)2464     final void internalOnRttUpgradeRequest(final int requestId) {
2465         for (CallbackRecord<Callback> record : mCallbackRecords) {
2466             final Call call = this;
2467             final Callback callback = record.getCallback();
2468             record.getHandler().post(() -> callback.onRttRequest(call, requestId));
2469         }
2470     }
2471 
2472     /** @hide */
internalOnRttInitiationFailure(int reason)2473     final void internalOnRttInitiationFailure(int reason) {
2474         for (CallbackRecord<Callback> record : mCallbackRecords) {
2475             final Call call = this;
2476             final Callback callback = record.getCallback();
2477             record.getHandler().post(() -> callback.onRttInitiationFailure(call, reason));
2478         }
2479     }
2480 
2481     /** {@hide} */
internalOnHandoverFailed(int error)2482     final void internalOnHandoverFailed(int error) {
2483         for (CallbackRecord<Callback> record : mCallbackRecords) {
2484             final Call call = this;
2485             final Callback callback = record.getCallback();
2486             record.getHandler().post(() -> callback.onHandoverFailed(call, error));
2487         }
2488     }
2489 
2490     /** {@hide} */
internalOnHandoverComplete()2491     final void internalOnHandoverComplete() {
2492         for (CallbackRecord<Callback> record : mCallbackRecords) {
2493             final Call call = this;
2494             final Callback callback = record.getCallback();
2495             record.getHandler().post(() -> callback.onHandoverComplete(call));
2496         }
2497     }
2498 
fireStateChanged(final int newState)2499     private void fireStateChanged(final int newState) {
2500         for (CallbackRecord<Callback> record : mCallbackRecords) {
2501             final Call call = this;
2502             final Callback callback = record.getCallback();
2503             record.getHandler().post(new Runnable() {
2504                 @Override
2505                 public void run() {
2506                     callback.onStateChanged(call, newState);
2507                 }
2508             });
2509         }
2510     }
2511 
fireParentChanged(final Call newParent)2512     private void fireParentChanged(final Call newParent) {
2513         for (CallbackRecord<Callback> record : mCallbackRecords) {
2514             final Call call = this;
2515             final Callback callback = record.getCallback();
2516             record.getHandler().post(new Runnable() {
2517                 @Override
2518                 public void run() {
2519                     callback.onParentChanged(call, newParent);
2520                 }
2521             });
2522         }
2523     }
2524 
fireChildrenChanged(final List<Call> children)2525     private void fireChildrenChanged(final List<Call> children) {
2526         for (CallbackRecord<Callback> record : mCallbackRecords) {
2527             final Call call = this;
2528             final Callback callback = record.getCallback();
2529             record.getHandler().post(new Runnable() {
2530                 @Override
2531                 public void run() {
2532                     callback.onChildrenChanged(call, children);
2533                 }
2534             });
2535         }
2536     }
2537 
fireDetailsChanged(final Details details)2538     private void fireDetailsChanged(final Details details) {
2539         for (CallbackRecord<Callback> record : mCallbackRecords) {
2540             final Call call = this;
2541             final Callback callback = record.getCallback();
2542             record.getHandler().post(new Runnable() {
2543                 @Override
2544                 public void run() {
2545                     callback.onDetailsChanged(call, details);
2546                 }
2547             });
2548         }
2549     }
2550 
fireCannedTextResponsesLoaded(final List<String> cannedTextResponses)2551     private void fireCannedTextResponsesLoaded(final List<String> cannedTextResponses) {
2552         for (CallbackRecord<Callback> record : mCallbackRecords) {
2553             final Call call = this;
2554             final Callback callback = record.getCallback();
2555             record.getHandler().post(new Runnable() {
2556                 @Override
2557                 public void run() {
2558                     callback.onCannedTextResponsesLoaded(call, cannedTextResponses);
2559                 }
2560             });
2561         }
2562     }
2563 
fireVideoCallChanged(final InCallService.VideoCall videoCall)2564     private void fireVideoCallChanged(final InCallService.VideoCall videoCall) {
2565         for (CallbackRecord<Callback> record : mCallbackRecords) {
2566             final Call call = this;
2567             final Callback callback = record.getCallback();
2568             record.getHandler().post(new Runnable() {
2569                 @Override
2570                 public void run() {
2571                     callback.onVideoCallChanged(call, videoCall);
2572                 }
2573             });
2574         }
2575     }
2576 
firePostDialWait(final String remainingPostDialSequence)2577     private void firePostDialWait(final String remainingPostDialSequence) {
2578         for (CallbackRecord<Callback> record : mCallbackRecords) {
2579             final Call call = this;
2580             final Callback callback = record.getCallback();
2581             record.getHandler().post(new Runnable() {
2582                 @Override
2583                 public void run() {
2584                     callback.onPostDialWait(call, remainingPostDialSequence);
2585                 }
2586             });
2587         }
2588     }
2589 
fireCallDestroyed()2590     private void fireCallDestroyed() {
2591         /**
2592          * To preserve the ordering of the Call's onCallDestroyed callback and Phone's
2593          * onCallRemoved callback, we remove this call from the Phone's record
2594          * only once all of the registered onCallDestroyed callbacks are executed.
2595          * All the callbacks get removed from our records as a part of this operation
2596          * since onCallDestroyed is the final callback.
2597          */
2598         final Call call = this;
2599         if (mCallbackRecords.isEmpty()) {
2600             // No callbacks registered, remove the call from Phone's record.
2601             mPhone.internalRemoveCall(call);
2602         }
2603         for (final CallbackRecord<Callback> record : mCallbackRecords) {
2604             final Callback callback = record.getCallback();
2605             record.getHandler().post(new Runnable() {
2606                 @Override
2607                 public void run() {
2608                     boolean isFinalRemoval = false;
2609                     RuntimeException toThrow = null;
2610                     try {
2611                         callback.onCallDestroyed(call);
2612                     } catch (RuntimeException e) {
2613                             toThrow = e;
2614                     }
2615                     synchronized(Call.this) {
2616                         mCallbackRecords.remove(record);
2617                         if (mCallbackRecords.isEmpty()) {
2618                             isFinalRemoval = true;
2619                         }
2620                     }
2621                     if (isFinalRemoval) {
2622                         mPhone.internalRemoveCall(call);
2623                     }
2624                     if (toThrow != null) {
2625                         throw toThrow;
2626                     }
2627                 }
2628             });
2629         }
2630     }
2631 
fireConferenceableCallsChanged()2632     private void fireConferenceableCallsChanged() {
2633         for (CallbackRecord<Callback> record : mCallbackRecords) {
2634             final Call call = this;
2635             final Callback callback = record.getCallback();
2636             record.getHandler().post(new Runnable() {
2637                 @Override
2638                 public void run() {
2639                     callback.onConferenceableCallsChanged(call, mUnmodifiableConferenceableCalls);
2640                 }
2641             });
2642         }
2643     }
2644 
2645     /**
2646      * Notifies listeners of an incoming connection event.
2647      * <p>
2648      * Connection events are issued via {@link Connection#sendConnectionEvent(String, Bundle)}.
2649      *
2650      * @param event
2651      * @param extras
2652      */
fireOnConnectionEvent(final String event, final Bundle extras)2653     private void fireOnConnectionEvent(final String event, final Bundle extras) {
2654         for (CallbackRecord<Callback> record : mCallbackRecords) {
2655             final Call call = this;
2656             final Callback callback = record.getCallback();
2657             record.getHandler().post(new Runnable() {
2658                 @Override
2659                 public void run() {
2660                     callback.onConnectionEvent(call, event, extras);
2661                 }
2662             });
2663         }
2664     }
2665 
2666     /**
2667      * Notifies listeners of an RTT on/off change
2668      *
2669      * @param enabled True if RTT is now enabled, false otherwise
2670      */
fireOnIsRttChanged(final boolean enabled, final RttCall rttCall)2671     private void fireOnIsRttChanged(final boolean enabled, final RttCall rttCall) {
2672         for (CallbackRecord<Callback> record : mCallbackRecords) {
2673             final Call call = this;
2674             final Callback callback = record.getCallback();
2675             record.getHandler().post(() -> callback.onRttStatusChanged(call, enabled, rttCall));
2676         }
2677     }
2678 
2679     /**
2680      * Notifies listeners of a RTT mode change
2681      *
2682      * @param mode The new RTT mode
2683      */
fireOnRttModeChanged(final int mode)2684     private void fireOnRttModeChanged(final int mode) {
2685         for (CallbackRecord<Callback> record : mCallbackRecords) {
2686             final Call call = this;
2687             final Callback callback = record.getCallback();
2688             record.getHandler().post(() -> callback.onRttModeChanged(call, mode));
2689         }
2690     }
2691 
2692     /**
2693      * Determines if two bundles are equal.
2694      *
2695      * @param bundle The original bundle.
2696      * @param newBundle The bundle to compare with.
2697      * @retrun {@code true} if the bundles are equal, {@code false} otherwise.
2698      */
areBundlesEqual(Bundle bundle, Bundle newBundle)2699     private static boolean areBundlesEqual(Bundle bundle, Bundle newBundle) {
2700         if (bundle == null || newBundle == null) {
2701             return bundle == newBundle;
2702         }
2703 
2704         if (bundle.size() != newBundle.size()) {
2705             return false;
2706         }
2707 
2708         for(String key : bundle.keySet()) {
2709             if (key != null) {
2710                 final Object value = bundle.get(key);
2711                 final Object newValue = newBundle.get(key);
2712                 if (!Objects.equals(value, newValue)) {
2713                     return false;
2714                 }
2715             }
2716         }
2717         return true;
2718     }
2719 }
2720