• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package android.telecom;
16 
17 import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
18 import static android.content.Intent.LOCAL_FLAG_FROM_SYSTEM;
19 
20 import android.Manifest;
21 import android.annotation.CallbackExecutor;
22 import android.annotation.FlaggedApi;
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.RequiresFeature;
27 import android.annotation.RequiresPermission;
28 import android.annotation.SuppressAutoDoc;
29 import android.annotation.SuppressLint;
30 import android.annotation.SystemApi;
31 import android.annotation.SystemService;
32 import android.annotation.TestApi;
33 import android.compat.annotation.ChangeId;
34 import android.compat.annotation.EnabledSince;
35 import android.compat.annotation.UnsupportedAppUsage;
36 import android.content.ComponentName;
37 import android.content.Context;
38 import android.content.Intent;
39 import android.content.pm.PackageManager;
40 import android.net.Uri;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.os.IBinder;
44 import android.os.OutcomeReceiver;
45 import android.os.Process;
46 import android.os.RemoteException;
47 import android.os.ServiceManager;
48 import android.os.UserHandle;
49 import android.telephony.Annotation.CallState;
50 import android.telephony.SubscriptionManager;
51 import android.telephony.TelephonyManager;
52 import android.text.TextUtils;
53 import android.util.Log;
54 
55 import com.android.internal.annotations.GuardedBy;
56 import com.android.internal.telecom.ClientTransactionalServiceRepository;
57 import com.android.internal.telecom.ClientTransactionalServiceWrapper;
58 import com.android.internal.telecom.ITelecomService;
59 import com.android.server.telecom.flags.Flags;
60 
61 import java.lang.annotation.Retention;
62 import java.lang.annotation.RetentionPolicy;
63 import java.util.ArrayList;
64 import java.util.Collections;
65 import java.util.List;
66 import java.util.Objects;
67 import java.util.concurrent.Executor;
68 
69 /**
70  * Provides access to information about active calls and registration/call-management functionality.
71  * Apps can use methods in this class to determine the current call state.
72  * <p>
73  * Apps do not instantiate this class directly; instead, they retrieve a reference to an instance
74  * through {@link Context#getSystemService Context.getSystemService(Context.TELECOM_SERVICE)}.
75  * <p>
76  * Note that access to some telecom information is permission-protected. Your app cannot access the
77  * protected information or gain access to protected functionality unless it has the appropriate
78  * permissions declared in its manifest file. Where permissions apply, they are noted in the method
79  * descriptions.
80  */
81 @SuppressAutoDoc
82 @SystemService(Context.TELECOM_SERVICE)
83 @RequiresFeature(PackageManager.FEATURE_TELECOM)
84 public class TelecomManager {
85 
86     /**
87      * Activity action: Starts the UI for handing an incoming call. This intent starts the in-call
88      * UI by notifying the Telecom system that an incoming call exists for a specific call service
89      * (see {@link android.telecom.ConnectionService}). Telecom reads the Intent extras to find
90      * and bind to the appropriate {@link android.telecom.ConnectionService} which Telecom will
91      * ultimately use to control and get information about the call.
92      * <p>
93      * Input: get*Extra field {@link #EXTRA_PHONE_ACCOUNT_HANDLE} contains the component name of the
94      * {@link android.telecom.ConnectionService} that Telecom should bind to. Telecom will then
95      * ask the connection service for more information about the call prior to showing any UI.
96      *
97      * @deprecated Use {@link #addNewIncomingCall} instead.
98      */
99     public static final String ACTION_INCOMING_CALL = "android.telecom.action.INCOMING_CALL";
100 
101     /**
102      * Similar to {@link #ACTION_INCOMING_CALL}, but is used only by Telephony to add a new
103      * sim-initiated MO call for carrier testing.
104      * @deprecated Use {@link #addNewUnknownCall} instead.
105      * @hide
106      */
107     public static final String ACTION_NEW_UNKNOWN_CALL = "android.telecom.action.NEW_UNKNOWN_CALL";
108 
109     /**
110      * An {@link android.content.Intent} action sent by the telecom framework to start a
111      * configuration dialog for a registered {@link PhoneAccount}. There is no default dialog
112      * and each app that registers a {@link PhoneAccount} should provide one if desired.
113      * <p>
114      * A user can access the list of enabled {@link android.telecom.PhoneAccount}s through the Phone
115      * app's settings menu. For each entry, the settings app will add a click action. When
116      * triggered, the click-action will start this intent along with the extra
117      * {@link #EXTRA_PHONE_ACCOUNT_HANDLE} to indicate the {@link PhoneAccount} to configure. If the
118      * {@link PhoneAccount} package does not register an {@link android.app.Activity} for this
119      * intent, then it will not be sent.
120      */
121     public static final String ACTION_CONFIGURE_PHONE_ACCOUNT =
122             "android.telecom.action.CONFIGURE_PHONE_ACCOUNT";
123 
124     /**
125      * The {@link android.content.Intent} action used to show the call accessibility settings page.
126      */
127     public static final String ACTION_SHOW_CALL_ACCESSIBILITY_SETTINGS =
128             "android.telecom.action.SHOW_CALL_ACCESSIBILITY_SETTINGS";
129 
130     /**
131      * The {@link android.content.Intent} action used to show the call settings page.
132      */
133     public static final String ACTION_SHOW_CALL_SETTINGS =
134             "android.telecom.action.SHOW_CALL_SETTINGS";
135 
136     /**
137      * The {@link android.content.Intent} action used to show the respond via SMS settings page.
138      */
139     public static final String ACTION_SHOW_RESPOND_VIA_SMS_SETTINGS =
140             "android.telecom.action.SHOW_RESPOND_VIA_SMS_SETTINGS";
141 
142     /**
143      * The {@link android.content.Intent} action used to show the settings page used to configure
144      * {@link PhoneAccount} preferences.
145      */
146     public static final String ACTION_CHANGE_PHONE_ACCOUNTS =
147             "android.telecom.action.CHANGE_PHONE_ACCOUNTS";
148 
149     /**
150      * {@link android.content.Intent} action used indicate that a new phone account was just
151      * registered.
152      * <p>
153      * The Intent {@link Intent#getExtras() extras} will contain {@link #EXTRA_PHONE_ACCOUNT_HANDLE}
154      * to indicate which {@link PhoneAccount} was registered.
155      * <p>
156      * Will only be sent to the default dialer app (see {@link #getDefaultDialerPackage()}).
157      */
158     public static final String ACTION_PHONE_ACCOUNT_REGISTERED =
159             "android.telecom.action.PHONE_ACCOUNT_REGISTERED";
160 
161     /**
162      * {@link android.content.Intent} action used indicate that a phone account was just
163      * unregistered.
164      * <p>
165      * The Intent {@link Intent#getExtras() extras} will contain {@link #EXTRA_PHONE_ACCOUNT_HANDLE}
166      * to indicate which {@link PhoneAccount} was unregistered.
167      * <p>
168      * Will only be sent to the default dialer app (see {@link #getDefaultDialerPackage()}).
169      */
170     public static final String ACTION_PHONE_ACCOUNT_UNREGISTERED =
171             "android.telecom.action.PHONE_ACCOUNT_UNREGISTERED";
172 
173     /**
174      * Activity action: Shows a dialog asking the user whether or not they want to replace the
175      * current default Dialer with the one specified in
176      * {@link #EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME}.
177      *
178      * Usage example:
179      * <pre>
180      * Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
181      * intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
182      *         getActivity().getPackageName());
183      * startActivity(intent);
184      * </pre>
185      * <p>
186      * This is no longer supported since Q, please use
187      * {@link android.app.role.RoleManager#createRequestRoleIntent(String)} with
188      * {@link android.app.role.RoleManager#ROLE_DIALER} instead.
189      */
190     public static final String ACTION_CHANGE_DEFAULT_DIALER =
191             "android.telecom.action.CHANGE_DEFAULT_DIALER";
192 
193     /**
194      * Broadcast intent action indicating that the current default dialer has changed.
195      * The string extra {@link #EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME} will contain the
196      * name of the package that the default dialer was changed to.
197      *
198      * @see #EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME
199      */
200     public static final String ACTION_DEFAULT_DIALER_CHANGED =
201             "android.telecom.action.DEFAULT_DIALER_CHANGED";
202 
203     /**
204      * Extra value used to provide the package name for {@link #ACTION_CHANGE_DEFAULT_DIALER}.
205      */
206     public static final String EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME =
207             "android.telecom.extra.CHANGE_DEFAULT_DIALER_PACKAGE_NAME";
208 
209     /**
210      * Broadcast intent action indicating that the current default call screening app has changed.
211      * <p>
212      * Note: This intent is NEVER actually broadcast and will be deprecated in the future.
213      * <p>
214      * An app that want to know if it holds the
215      * {@link android.app.role.RoleManager#ROLE_CALL_SCREENING} role can use
216      * {@link android.app.role.RoleManager#isRoleHeld(String)} to confirm if it holds the role or
217      * not.
218      */
219     public static final String ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED =
220         "android.telecom.action.DEFAULT_CALL_SCREENING_APP_CHANGED";
221 
222     /**
223      * Extra value used with {@link #ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED} broadcast to
224      * indicate the ComponentName of the call screening app which has changed.
225      * <p>
226      * Note: This extra is NOT used and will be deprecated in the future.
227      */
228     public static final String EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME =
229             "android.telecom.extra.DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME";
230 
231     /**
232      * Optional extra to indicate a call should not be added to the call log.
233      *
234      * @hide
235      */
236     public static final String EXTRA_DO_NOT_LOG_CALL =
237             "android.telecom.extra.DO_NOT_LOG_CALL";
238 
239     /**
240      * Extra value used with {@link #ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED} broadcast to
241      * indicate whether an app is the default call screening app.
242      * <p>
243      * Note: This extra is NOT used and will be deprecated in the future.
244      */
245     public static final String EXTRA_IS_DEFAULT_CALL_SCREENING_APP =
246             "android.telecom.extra.IS_DEFAULT_CALL_SCREENING_APP";
247 
248     /**
249      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing a boolean that
250      * determines whether the speakerphone should be automatically turned on for an outgoing call.
251      */
252     public static final String EXTRA_START_CALL_WITH_SPEAKERPHONE =
253             "android.telecom.extra.START_CALL_WITH_SPEAKERPHONE";
254 
255     /**
256      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing an integer that
257      * determines the desired video state for an outgoing call.
258      * Valid options:
259      * {@link VideoProfile#STATE_AUDIO_ONLY},
260      * {@link VideoProfile#STATE_BIDIRECTIONAL},
261      * {@link VideoProfile#STATE_RX_ENABLED},
262      * {@link VideoProfile#STATE_TX_ENABLED}.
263      */
264     public static final String EXTRA_START_CALL_WITH_VIDEO_STATE =
265             "android.telecom.extra.START_CALL_WITH_VIDEO_STATE";
266 
267     /**
268      * Optional extra for {@link #addNewIncomingCall(PhoneAccountHandle, Bundle)} containing an
269      * integer that determines the requested video state for an incoming call.
270      * Valid options:
271      * {@link VideoProfile#STATE_AUDIO_ONLY},
272      * {@link VideoProfile#STATE_BIDIRECTIONAL},
273      * {@link VideoProfile#STATE_RX_ENABLED},
274      * {@link VideoProfile#STATE_TX_ENABLED}.
275      */
276     public static final String EXTRA_INCOMING_VIDEO_STATE =
277             "android.telecom.extra.INCOMING_VIDEO_STATE";
278 
279     /**
280      * The extra used with an {@link android.content.Intent#ACTION_CALL} and
281      * {@link android.content.Intent#ACTION_DIAL} {@code Intent} to specify a
282      * {@link PhoneAccountHandle} to use when making the call.
283      * <p class="note">
284      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
285      */
286     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
287             "android.telecom.extra.PHONE_ACCOUNT_HANDLE";
288 
289     /**
290      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing a string call
291      * subject which will be associated with an outgoing call.  Should only be specified if the
292      * {@link PhoneAccount} supports the capability {@link PhoneAccount#CAPABILITY_CALL_SUBJECT}
293      * or {@link PhoneAccount#CAPABILITY_CALL_COMPOSER}.
294      */
295     public static final String EXTRA_CALL_SUBJECT = "android.telecom.extra.CALL_SUBJECT";
296 
297     // Values for EXTRA_PRIORITY
298     /**
299      * Indicates the call composer call priority is normal.
300      *
301      * Reference: RCC.20 Section 2.4.4.2
302      */
303     public static final int PRIORITY_NORMAL = 0;
304 
305     /**
306      * Indicates the call composer call priority is urgent.
307      *
308      * Reference: RCC.20 Section 2.4.4.2
309      */
310     public static final int PRIORITY_URGENT = 1;
311 
312     /**
313      * Extra for the call composer call priority, either {@link #PRIORITY_NORMAL} or
314      * {@link #PRIORITY_URGENT}.
315      *
316      * Reference: RCC.20 Section 2.4.4.2
317      */
318     public static final String EXTRA_PRIORITY = "android.telecom.extra.PRIORITY";
319 
320     /**
321      * Extra for the call composer call location, an {@link android.location.Location} parcelable
322      * class to represent the geolocation as a latitude and longitude pair.
323      *
324      * Reference: RCC.20 Section 2.4.3.2
325      */
326     public static final String EXTRA_LOCATION = "android.telecom.extra.LOCATION";
327 
328     /**
329      * A boolean extra set on incoming calls to indicate that the call has a picture specified.
330      * Given that image download could take a (short) time, the EXTRA is set immediately upon
331      * adding the call to the Dialer app, this allows the Dialer app to reserve space for an image
332      * if one is expected. The EXTRA may be unset if the image download ends up failing for some
333      * reason.
334      */
335     public static final String EXTRA_HAS_PICTURE = "android.telecom.extra.HAS_PICTURE";
336 
337     /**
338      * A {@link Uri} representing the picture that was downloaded when a call is received or
339      * uploaded when a call is placed.
340      *
341      * This is a content URI within the call log provider which can be used to open a file
342      * descriptor. This could be set a short time after a call is added to the Dialer app if the
343      * download/upload is delayed for some reason. The Dialer app will receive a callback via
344      * {@link Call.Callback#onDetailsChanged} when this value has changed.
345      *
346      * Reference: RCC.20 Section 2.4.3.2
347      */
348     public static final String EXTRA_PICTURE_URI = "android.telecom.extra.PICTURE_URI";
349 
350     /**
351      * A ParcelUuid used as a token to represent a picture that was uploaded prior to the call
352      * being placed. The value of this extra should be set using the {@link android.os.ParcelUuid}
353      * obtained from the callback in {@link TelephonyManager#uploadCallComposerPicture}.
354      */
355     public static final String EXTRA_OUTGOING_PICTURE = "android.telecom.extra.OUTGOING_PICTURE";
356 
357     /**
358      * The extra used by a {@link ConnectionService} to provide the handle of the caller that
359      * has initiated a new incoming call.
360      */
361     public static final String EXTRA_INCOMING_CALL_ADDRESS =
362             "android.telecom.extra.INCOMING_CALL_ADDRESS";
363 
364     /**
365      * Optional extra for {@link #ACTION_INCOMING_CALL} containing a {@link Bundle} which contains
366      * metadata about the call. This {@link Bundle} will be returned to the
367      * {@link ConnectionService}.
368      */
369     public static final String EXTRA_INCOMING_CALL_EXTRAS =
370             "android.telecom.extra.INCOMING_CALL_EXTRAS";
371 
372     /**
373      * Optional extra for {@link #addNewIncomingCall(PhoneAccountHandle, Bundle)} used to indicate
374      * that a call has an in-band ringtone associated with it.  This is used when the device is
375      * acting as an HFP headset and the Bluetooth stack has received an in-band ringtone from the
376      * the HFP host which must be played instead of any local ringtone the device would otherwise
377      * have generated.
378      *
379      * @hide
380      */
381     @SystemApi
382     public static final String EXTRA_CALL_HAS_IN_BAND_RINGTONE =
383             "android.telecom.extra.CALL_HAS_IN_BAND_RINGTONE";
384 
385     /**
386      * Optional extra for {@link android.content.Intent#ACTION_CALL} and
387      * {@link android.content.Intent#ACTION_DIAL} {@code Intent} containing a {@link Bundle}
388      * which contains metadata about the call. This {@link Bundle} will be saved into
389      * {@code Call.Details} and passed to the {@link ConnectionService} when placing the call.
390      */
391     public static final String EXTRA_OUTGOING_CALL_EXTRAS =
392             "android.telecom.extra.OUTGOING_CALL_EXTRAS";
393 
394     /**
395      * An optional boolean extra on {@link android.content.Intent#ACTION_CALL_EMERGENCY} to tell
396      * whether the user's dial intent is emergency; this is required to specify when the dialed
397      * number is ambiguous, identified as both emergency number and any other non-emergency number;
398      * e.g. in some situation, 611 could be both an emergency number in a country and a
399      * non-emergency number of a carrier's customer service hotline.
400      *
401      * @hide
402      */
403     @SystemApi
404     public static final String EXTRA_IS_USER_INTENT_EMERGENCY_CALL =
405             "android.telecom.extra.IS_USER_INTENT_EMERGENCY_CALL";
406 
407     /**
408      * A mandatory extra containing a {@link Uri} to be passed in when calling
409      * {@link #addNewUnknownCall(PhoneAccountHandle, Bundle)}. The {@link Uri} value indicates
410      * the remote handle of the new call.
411      * @hide
412      */
413     @SystemApi
414     public static final String EXTRA_UNKNOWN_CALL_HANDLE =
415             "android.telecom.extra.UNKNOWN_CALL_HANDLE";
416 
417     /**
418      * Optional extra for incoming and outgoing calls containing a long which specifies the time the
419      * call was created. This value is in milliseconds since boot.
420      * @hide
421      */
422     public static final String EXTRA_CALL_CREATED_TIME_MILLIS =
423             "android.telecom.extra.CALL_CREATED_TIME_MILLIS";
424 
425     /**
426      * Extra URI that is used by a dialer to query the {@link android.provider.CallLog} content
427      * provider and associate a missed call notification with a call log entry.
428      */
429     @FlaggedApi(Flags.FLAG_ADD_CALL_URI_FOR_MISSED_CALLS)
430     public static final String EXTRA_CALL_LOG_URI =
431             "android.telecom.extra.CALL_LOG_URI";
432 
433     /**
434      * Optional extra for incoming containing a long which specifies the time the
435      * call was answered by user. This value is in milliseconds.
436      * @hide
437      */
438     public static final String EXTRA_CALL_ANSWERED_TIME_MILLIS =
439             "android.telecom.extra.CALL_ANSWERED_TIME_MILLIS";
440 
441 
442     /**
443      * Optional extra for incoming and outgoing calls containing a long which specifies the Epoch
444      * time the call was created.
445      * @hide
446      */
447     public static final String EXTRA_CALL_CREATED_EPOCH_TIME_MILLIS =
448             "android.telecom.extra.CALL_CREATED_EPOCH_TIME_MILLIS";
449 
450     /**
451      * Optional extra for incoming and outgoing calls containing a long which specifies the time
452      * telecom began routing the call. This value is in milliseconds since boot.
453      * @hide
454      */
455     public static final String EXTRA_CALL_TELECOM_ROUTING_START_TIME_MILLIS =
456             "android.telecom.extra.CALL_TELECOM_ROUTING_START_TIME_MILLIS";
457 
458     /**
459      * Optional extra for incoming and outgoing calls containing a long which specifies the time
460      * telecom finished routing the call. This value is in milliseconds since boot.
461      * @hide
462      */
463     public static final String EXTRA_CALL_TELECOM_ROUTING_END_TIME_MILLIS =
464             "android.telecom.extra.CALL_TELECOM_ROUTING_END_TIME_MILLIS";
465 
466     /**
467      * Optional extra for {@link android.telephony.TelephonyManager#ACTION_PHONE_STATE_CHANGED}
468      * containing the disconnect code.
469      */
470     public static final String EXTRA_CALL_DISCONNECT_CAUSE =
471             "android.telecom.extra.CALL_DISCONNECT_CAUSE";
472 
473     /**
474      * Optional extra for {@link android.telephony.TelephonyManager#ACTION_PHONE_STATE_CHANGED}
475      * containing the disconnect message.
476      */
477     public static final String EXTRA_CALL_DISCONNECT_MESSAGE =
478             "android.telecom.extra.CALL_DISCONNECT_MESSAGE";
479 
480     /**
481      * A string value for {@link #EXTRA_CALL_DISCONNECT_MESSAGE}, indicates the call was dropped by
482      * lower layers
483      * @hide
484      */
485     public static final String CALL_AUTO_DISCONNECT_MESSAGE_STRING =
486             "Call dropped by lower layers";
487 
488     /**
489      * Optional extra for {@link android.telephony.TelephonyManager#ACTION_PHONE_STATE_CHANGED}
490      * containing the component name of the associated connection service.
491      * @hide
492      */
493     @SystemApi
494     public static final String EXTRA_CONNECTION_SERVICE =
495             "android.telecom.extra.CONNECTION_SERVICE";
496 
497     /**
498      * Optional extra for communicating the call technology used by a {@link ConnectionService}
499      * to Telecom. Valid values are:
500      * <ul>
501      *     <li>{@link TelephonyManager#PHONE_TYPE_CDMA}</li>
502      *     <li>{@link TelephonyManager#PHONE_TYPE_GSM}</li>
503      *     <li>{@link TelephonyManager#PHONE_TYPE_IMS}</li>
504      *     <li>{@link TelephonyManager#PHONE_TYPE_THIRD_PARTY}</li>
505      *     <li>{@link TelephonyManager#PHONE_TYPE_SIP}</li>
506      * </ul>
507      * @hide
508      */
509     @SystemApi
510     public static final String EXTRA_CALL_TECHNOLOGY_TYPE =
511             "android.telecom.extra.CALL_TECHNOLOGY_TYPE";
512 
513     /**
514      * Optional extra for communicating the call network technology used by a
515      * {@link android.telecom.Connection} to Telecom and InCallUI.
516      *
517      * {@code NETWORK_TYPE_*} in {@link android.telephony.TelephonyManager}.
518      */
519     public static final String EXTRA_CALL_NETWORK_TYPE =
520             "android.telecom.extra.CALL_NETWORK_TYPE";
521 
522     /**
523      * An optional {@link android.content.Intent#ACTION_CALL} intent extra denoting the
524      * package name of the app specifying an alternative gateway for the call.
525      * The value is a string.
526      *
527      * (The following comment corresponds to the all GATEWAY_* extras)
528      * An app which sends the {@link android.content.Intent#ACTION_CALL} intent can specify an
529      * alternative address to dial which is different from the one specified and displayed to
530      * the user. This alternative address is referred to as the gateway address.
531      */
532     public static final String GATEWAY_PROVIDER_PACKAGE =
533             "android.telecom.extra.GATEWAY_PROVIDER_PACKAGE";
534 
535     /**
536      * An optional {@link android.content.Intent#ACTION_CALL} intent extra corresponding to the
537      * original address to dial for the call. This is used when an alternative gateway address is
538      * provided to recall the original address.
539      * The value is a {@link android.net.Uri}.
540      *
541      * (See {@link #GATEWAY_PROVIDER_PACKAGE} for details)
542      */
543     public static final String GATEWAY_ORIGINAL_ADDRESS =
544             "android.telecom.extra.GATEWAY_ORIGINAL_ADDRESS";
545 
546     /**
547      * The number which the party on the other side of the line will see (and use to return the
548      * call).
549      * <p>
550      * {@link ConnectionService}s which interact with {@link RemoteConnection}s should only populate
551      * this if the {@link android.telephony.TelephonyManager#getLine1Number()} value, as that is the
552      * user's expected caller ID.
553      */
554     public static final String EXTRA_CALL_BACK_NUMBER = "android.telecom.extra.CALL_BACK_NUMBER";
555 
556     /**
557      * The number of milliseconds that Telecom should wait after disconnecting a call via the
558      * ACTION_NEW_OUTGOING_CALL broadcast, in order to wait for the app which cancelled the call
559      * to make a new one.
560      * @hide
561      */
562     public static final String EXTRA_NEW_OUTGOING_CALL_CANCEL_TIMEOUT =
563             "android.telecom.extra.NEW_OUTGOING_CALL_CANCEL_TIMEOUT";
564 
565     /**
566      * Boolean extra specified to indicate that the intention of adding a call is to handover an
567      * existing call from the user's device to a different {@link PhoneAccount}.
568      * <p>
569      * Used when calling {@link #addNewIncomingCall(PhoneAccountHandle, Bundle)}
570      * to indicate to Telecom that the purpose of adding a new incoming call is to handover an
571      * existing call from the user's device to a different {@link PhoneAccount}.  This occurs on
572      * the receiving side of a handover.
573      * <p>
574      * Used when Telecom calls
575      * {@link ConnectionService#onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}
576      * to indicate that the purpose of Telecom requesting a new outgoing connection it to request
577      * a handover to this {@link ConnectionService} from an ongoing call on the user's device.  This
578      * occurs on the initiating side of a handover.
579      * <p>
580      * The phone number of the call used by Telecom to determine which call should be handed over.
581      * @hide
582      * @deprecated Use the public handover APIs.  See
583      * {@link Call#handoverTo(PhoneAccountHandle, int, Bundle)} for more information.
584      */
585     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 119305590)
586     public static final String EXTRA_IS_HANDOVER = "android.telecom.extra.IS_HANDOVER";
587 
588     /**
589      * When {@code true} indicates that a request to create a new connection is for the purpose of
590      * a handover.  Note: This is used with the
591      * {@link android.telecom.Call#handoverTo(PhoneAccountHandle, int, Bundle)} API as part of the
592      * internal communication mechanism with the {@link android.telecom.ConnectionService}.  It is
593      * not the same as the legacy {@link #EXTRA_IS_HANDOVER} extra.
594      * @hide
595      */
596     public static final String EXTRA_IS_HANDOVER_CONNECTION =
597             "android.telecom.extra.IS_HANDOVER_CONNECTION";
598 
599     /**
600      * Parcelable extra used with {@link #EXTRA_IS_HANDOVER} to indicate the source
601      * {@link PhoneAccountHandle} when initiating a handover which {@link ConnectionService}
602      * the handover is from.
603      * @hide
604      */
605     public static final String EXTRA_HANDOVER_FROM_PHONE_ACCOUNT =
606             "android.telecom.extra.HANDOVER_FROM_PHONE_ACCOUNT";
607 
608     /**
609      * Extra key specified in the {@link ConnectionRequest#getExtras()} when Telecom calls
610      * {@link ConnectionService#onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}
611      * to inform the {@link ConnectionService} what the initial {@link CallAudioState} of the
612      * {@link Connection} will be.
613      * @hide
614      */
615     public static final String EXTRA_CALL_AUDIO_STATE = "android.telecom.extra.CALL_AUDIO_STATE";
616 
617     /**
618      * A boolean extra, which when set on the {@link Intent#ACTION_CALL} intent or on the bundle
619      * passed into {@link #placeCall(Uri, Bundle)}, indicates that the call should be initiated with
620      * an RTT session open. See {@link android.telecom.Call.RttCall} for more information on RTT.
621      */
622     public static final String EXTRA_START_CALL_WITH_RTT =
623             "android.telecom.extra.START_CALL_WITH_RTT";
624 
625     /**
626      * Start an activity indicating that the completion of an outgoing call or an incoming call
627      * which was not blocked by the {@link CallScreeningService}, and which was NOT terminated
628      * while the call was in {@link Call#STATE_AUDIO_PROCESSING}.
629      *
630      * The {@link Uri} extra {@link #EXTRA_HANDLE} will contain the uri handle(phone number) for the
631      * call which completed.
632      *
633      * The integer extra {@link #EXTRA_DISCONNECT_CAUSE} will indicate the reason for the call
634      * disconnection. See {@link #EXTRA_DISCONNECT_CAUSE} for more information.
635      *
636      * The integer extra {@link #EXTRA_CALL_DURATION} will indicate the duration of the call. See
637      * {@link #EXTRA_CALL_DURATION} for more information.
638      */
639     public static final String ACTION_POST_CALL = "android.telecom.action.POST_CALL";
640 
641     /**
642      * A {@link Uri} extra, which when set on the {@link #ACTION_POST_CALL} intent, indicates the
643      * uri handle(phone number) of the completed call.
644      */
645     public static final String EXTRA_HANDLE = "android.telecom.extra.HANDLE";
646 
647     /**
648      * A integer value provided for completed calls to indicate the reason for the call
649      * disconnection.
650      * <p>
651      * Allowed values:
652      * <ul>
653      * <li>{@link DisconnectCause#UNKNOWN}</li>
654      * <li>{@link DisconnectCause#LOCAL}</li>
655      * <li>{@link DisconnectCause#REMOTE}</li>
656      * <li>{@link DisconnectCause#REJECTED}</li>
657      * <li>{@link DisconnectCause#MISSED}</li>
658      * </ul>
659      * </p>
660      */
661     public static final String EXTRA_DISCONNECT_CAUSE = "android.telecom.extra.DISCONNECT_CAUSE";
662 
663     /**
664      * A integer value provided for completed calls to indicate the duration of the call.
665      * <p>
666      * Allowed values:
667      * <ul>
668      * <li>{@link #DURATION_VERY_SHORT}</li>
669      * <li>{@link #DURATION_SHORT}</li>
670      * <li>{@link #DURATION_MEDIUM}</li>
671      * <li>{@link #DURATION_LONG}</li>
672      * </ul>
673      * </p>
674      */
675     public static final String EXTRA_CALL_DURATION = "android.telecom.extra.CALL_DURATION";
676 
677     /**
678      * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
679      * call was < 3 seconds.
680      */
681     public static final int DURATION_VERY_SHORT = 0;
682 
683     /**
684      * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
685      * call was >= 3 seconds and < 60 seconds.
686      */
687     public static final int DURATION_SHORT = 1;
688 
689     /**
690      * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
691      * call was >= 60 seconds and < 120 seconds.
692      */
693     public static final int DURATION_MEDIUM = 2;
694 
695     /**
696      * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
697      * call was >= 120 seconds.
698      */
699     public static final int DURATION_LONG = 3;
700 
701     /**
702      * The threshold between {@link #DURATION_VERY_SHORT} calls and {@link #DURATION_SHORT} calls in
703      * milliseconds.
704      * @hide
705      */
706     public static final long VERY_SHORT_CALL_TIME_MS = 3000;
707 
708     /**
709      * The threshold between {@link #DURATION_SHORT} calls and {@link #DURATION_MEDIUM} calls in
710      * milliseconds.
711      * @hide
712      */
713     public static final long SHORT_CALL_TIME_MS = 60000;
714 
715     /**
716      * The threshold between {@link #DURATION_MEDIUM} calls and {@link #DURATION_LONG} calls in
717      * milliseconds.
718      * @hide
719      */
720     public static final long MEDIUM_CALL_TIME_MS = 120000;
721 
722     /**
723      * A boolean meta-data value indicating whether an {@link InCallService} implements an
724      * in-call user interface. Dialer implementations (see {@link #getDefaultDialerPackage()}) which
725      * would also like to replace the in-call interface should set this meta-data to {@code true} in
726      * the manifest registration of their {@link InCallService}.
727      */
728     public static final String METADATA_IN_CALL_SERVICE_UI = "android.telecom.IN_CALL_SERVICE_UI";
729 
730     /**
731      * A boolean meta-data value indicating whether an {@link InCallService} implements an
732      * in-call user interface to be used while the device is in car-mode (see
733      * {@link android.content.res.Configuration#UI_MODE_TYPE_CAR}).
734      */
735     public static final String METADATA_IN_CALL_SERVICE_CAR_MODE_UI =
736             "android.telecom.IN_CALL_SERVICE_CAR_MODE_UI";
737 
738     /**
739      * A boolean meta-data value indicating whether an {@link InCallService} implements ringing.
740      * Dialer implementations (see {@link #getDefaultDialerPackage()}) which would also like to
741      * override the system provided ringing should set this meta-data to {@code true} in the
742      * manifest registration of their {@link InCallService}.
743      * <p>
744      * When {@code true}, it is the {@link InCallService}'s responsibility to play a ringtone for
745      * all incoming calls.
746      */
747     public static final String METADATA_IN_CALL_SERVICE_RINGING =
748             "android.telecom.IN_CALL_SERVICE_RINGING";
749 
750     /**
751      * A boolean meta-data value indicating whether an {@link InCallService} wants to be informed of
752      * calls which have the {@link Call.Details#PROPERTY_IS_EXTERNAL_CALL} property.  An external
753      * call is one which a {@link ConnectionService} knows about, but is not connected to directly.
754      * Dialer implementations (see {@link #getDefaultDialerPackage()}) which would like to be
755      * informed of external calls should set this meta-data to {@code true} in the manifest
756      * registration of their {@link InCallService}.  By default, the {@link InCallService} will NOT
757      * be informed of external calls.
758      */
759     public static final String METADATA_INCLUDE_EXTERNAL_CALLS =
760             "android.telecom.INCLUDE_EXTERNAL_CALLS";
761 
762     /**
763      * A boolean meta-data value indicating whether an {@link InCallService} wants to be informed of
764      * calls which have the {@link Call.Details#PROPERTY_SELF_MANAGED} property.  A self-managed
765      * call is one which originates from a self-managed {@link ConnectionService} which has chosen
766      * to implement its own call user interface.  An {@link InCallService} implementation which
767      * would like to be informed of external calls should set this meta-data to {@code true} in the
768      * manifest registration of their {@link InCallService}.  By default, the {@link InCallService}
769      * will NOT be informed about self-managed calls.
770      * <p>
771      * An {@link InCallService} which receives self-managed calls is free to view and control the
772      * state of calls in the self-managed {@link ConnectionService}.  An example use-case is
773      * exposing these calls to an automotive device via its companion app.
774      * <p>
775      * See also {@link Connection#PROPERTY_SELF_MANAGED}.
776      */
777     public static final String METADATA_INCLUDE_SELF_MANAGED_CALLS =
778             "android.telecom.INCLUDE_SELF_MANAGED_CALLS";
779 
780     /**
781      * The dual tone multi-frequency signaling character sent to indicate the dialing system should
782      * pause for a predefined period.
783      */
784     public static final char DTMF_CHARACTER_PAUSE = ',';
785 
786     /**
787      * The dual-tone multi-frequency signaling character sent to indicate the dialing system should
788      * wait for user confirmation before proceeding.
789      */
790     public static final char DTMF_CHARACTER_WAIT = ';';
791 
792     /**
793      * @hide
794      */
795     @IntDef(prefix = { "TTY_MODE_" },
796             value = {TTY_MODE_OFF, TTY_MODE_FULL, TTY_MODE_HCO, TTY_MODE_VCO})
797     @Retention(RetentionPolicy.SOURCE)
798     public @interface TtyMode {}
799 
800     /**
801      * TTY (teletypewriter) mode is off.
802      *
803      * @hide
804      */
805     @SystemApi
806     public static final int TTY_MODE_OFF = 0;
807 
808     /**
809      * TTY (teletypewriter) mode is on. The speaker is off and the microphone is muted. The user
810      * will communicate with the remote party by sending and receiving text messages.
811      *
812      * @hide
813      */
814     @SystemApi
815     public static final int TTY_MODE_FULL = 1;
816 
817     /**
818      * TTY (teletypewriter) mode is in hearing carryover mode (HCO). The microphone is muted but the
819      * speaker is on. The user will communicate with the remote party by sending text messages and
820      * hearing an audible reply.
821      *
822      * @hide
823      */
824     @SystemApi
825     public static final int TTY_MODE_HCO = 2;
826 
827     /**
828      * TTY (teletypewriter) mode is in voice carryover mode (VCO). The speaker is off but the
829      * microphone is still on. User will communicate with the remote party by speaking and receiving
830      * text message replies.
831      *
832      * @hide
833      */
834     @SystemApi
835     public static final int TTY_MODE_VCO = 3;
836 
837     /**
838      * Broadcast intent action indicating that the current TTY mode has changed.
839      *
840      * This intent will contain {@link #EXTRA_CURRENT_TTY_MODE} as an intent extra, giving the new
841      * TTY mode.
842      * @hide
843      */
844     @SystemApi
845     public static final String ACTION_CURRENT_TTY_MODE_CHANGED =
846             "android.telecom.action.CURRENT_TTY_MODE_CHANGED";
847 
848     /**
849      * Integer extra key that indicates the current TTY mode.
850      *
851      * Used with {@link #ACTION_CURRENT_TTY_MODE_CHANGED}.
852      *
853      * Valid modes are:
854      * <ul>
855      *     <li>{@link #TTY_MODE_OFF}</li>
856      *     <li>{@link #TTY_MODE_FULL}</li>
857      *     <li>{@link #TTY_MODE_HCO}</li>
858      *     <li>{@link #TTY_MODE_VCO}</li>
859      * </ul>
860      *
861      * This TTY mode is distinct from the one sent via {@link #ACTION_TTY_PREFERRED_MODE_CHANGED},
862      * since the current TTY mode will always be {@link #TTY_MODE_OFF}unless a TTY terminal is
863      * plugged into the device.
864      * @hide
865      */
866     @SystemApi
867     public static final String EXTRA_CURRENT_TTY_MODE =
868             "android.telecom.extra.CURRENT_TTY_MODE";
869 
870     /**
871      * Broadcast intent action indicating that the TTY preferred operating mode has changed.
872      *
873      * This intent will contain {@link #EXTRA_TTY_PREFERRED_MODE} as an intent extra, giving the new
874      * preferred TTY mode.
875      * @hide
876      */
877     @SystemApi
878     public static final String ACTION_TTY_PREFERRED_MODE_CHANGED =
879             "android.telecom.action.TTY_PREFERRED_MODE_CHANGED";
880 
881     /**
882      * Integer extra key that indicates the preferred TTY mode.
883      *
884      * Used with {@link #ACTION_TTY_PREFERRED_MODE_CHANGED}.
885      *
886      * Valid modes are:
887      * <ul>
888      *     <li>{@link #TTY_MODE_OFF}</li>
889      *     <li>{@link #TTY_MODE_FULL}</li>
890      *     <li>{@link #TTY_MODE_HCO}</li>
891      *     <li>{@link #TTY_MODE_VCO}</li>
892      * </ul>
893      * @hide
894      */
895     @SystemApi
896     public static final String EXTRA_TTY_PREFERRED_MODE =
897             "android.telecom.extra.TTY_PREFERRED_MODE";
898 
899     /**
900      * Broadcast intent action for letting custom component know to show the missed call
901      * notification. If no custom component exists then this is sent to the default dialer which
902      * should post a missed-call notification.
903      */
904     public static final String ACTION_SHOW_MISSED_CALLS_NOTIFICATION =
905             "android.telecom.action.SHOW_MISSED_CALLS_NOTIFICATION";
906 
907     /**
908      * The number of calls associated with the notification. If the number is zero then the missed
909      * call notification should be dismissed.
910      */
911     public static final String EXTRA_NOTIFICATION_COUNT =
912             "android.telecom.extra.NOTIFICATION_COUNT";
913 
914     /**
915      * The number associated with the missed calls. This number is only relevant
916      * when EXTRA_NOTIFICATION_COUNT is 1.
917      */
918     public static final String EXTRA_NOTIFICATION_PHONE_NUMBER =
919             "android.telecom.extra.NOTIFICATION_PHONE_NUMBER";
920 
921     /**
922      * Included in the extras of the {@link #ACTION_SHOW_MISSED_CALLS_NOTIFICATION}, provides a
923      * pending intent which can be used to clear the missed calls notification and mark unread
924      * missed call log entries as read.
925      * @hide
926      * @deprecated Use {@link #cancelMissedCallsNotification()} instead.
927      */
928     @Deprecated
929     @SystemApi
930     public static final String EXTRA_CLEAR_MISSED_CALLS_INTENT =
931             "android.telecom.extra.CLEAR_MISSED_CALLS_INTENT";
932 
933     /**
934      * The intent to call back a missed call.
935      * @hide
936      */
937     @SystemApi
938     public static final String EXTRA_CALL_BACK_INTENT =
939             "android.telecom.extra.CALL_BACK_INTENT";
940 
941     /**
942      * The dialer activity responsible for placing emergency calls from, for example, a locked
943      * keyguard.
944      * @hide
945      */
946     public static final ComponentName EMERGENCY_DIALER_COMPONENT =
947             ComponentName.createRelative("com.android.phone", ".EmergencyDialer");
948 
949     /**
950      * The boolean indicated by this extra controls whether or not a call is eligible to undergo
951      * assisted dialing. This extra is stored under {@link #EXTRA_OUTGOING_CALL_EXTRAS}.
952      * <p>
953      * The call initiator can use this extra to indicate that a call used assisted dialing to help
954      * place the call.  This is most commonly used by a Dialer app which provides the ability to
955      * automatically add dialing prefixes when placing international calls.
956      * <p>
957      * Setting this extra on the outgoing call extras will cause the
958      * {@link Connection#PROPERTY_ASSISTED_DIALING} property and
959      * {@link Call.Details#PROPERTY_ASSISTED_DIALING} property to be set on the
960      * {@link Connection}/{@link Call} in question.  When the call is logged to the call log, the
961      * {@link android.provider.CallLog.Calls#FEATURES_ASSISTED_DIALING_USED} call feature is set to
962      * indicate that assisted dialing was used for the call.
963      */
964     public static final String EXTRA_USE_ASSISTED_DIALING =
965             "android.telecom.extra.USE_ASSISTED_DIALING";
966 
967     /**
968      * Optional extra for {@link #placeCall(Uri, Bundle)} containing an integer that specifies
969      * the source where user initiated this call. This data is used in metrics.
970      * Valid sources are:
971      * {@link TelecomManager#CALL_SOURCE_UNSPECIFIED},
972      * {@link TelecomManager#CALL_SOURCE_EMERGENCY_DIALPAD},
973      * {@link TelecomManager#CALL_SOURCE_EMERGENCY_SHORTCUT}.
974      *
975      * Intended for use with the platform emergency dialer only.
976      * @hide
977      */
978     @SystemApi
979     public static final String EXTRA_CALL_SOURCE = "android.telecom.extra.CALL_SOURCE";
980 
981     /**
982      * Intent action to trigger "switch to managed profile" dialog for call in SystemUI
983      *
984      * @hide
985      */
986     public static final String ACTION_SHOW_SWITCH_TO_WORK_PROFILE_FOR_CALL_DIALOG =
987             "android.telecom.action.SHOW_SWITCH_TO_WORK_PROFILE_FOR_CALL_DIALOG";
988 
989     /**
990      * Extra specifying the managed profile user id.
991      * This is used with {@link TelecomManager#ACTION_SHOW_SWITCH_TO_WORK_PROFILE_FOR_CALL_DIALOG}
992      *
993      * @hide
994      */
995     public static final String EXTRA_MANAGED_PROFILE_USER_ID =
996             "android.telecom.extra.MANAGED_PROFILE_USER_ID";
997 
998     /**
999      * Indicating the call is initiated via emergency dialer's shortcut button.
1000      *
1001      * @hide
1002      */
1003     @SystemApi
1004     public static final int CALL_SOURCE_EMERGENCY_SHORTCUT = 2;
1005 
1006     /**
1007      * Indicating the call is initiated via emergency dialer's dialpad.
1008      *
1009      * @hide
1010      */
1011     @SystemApi
1012     public static final int CALL_SOURCE_EMERGENCY_DIALPAD = 1;
1013 
1014     /**
1015      * Indicating the call source is not specified.
1016      *
1017      * @hide
1018      */
1019     @SystemApi
1020     public static final int CALL_SOURCE_UNSPECIFIED = 0;
1021 
1022     /**
1023      * The following 4 constants define how properties such as phone numbers and names are
1024      * displayed to the user.
1025      */
1026 
1027     /**
1028      * Indicates that the address or number of a call is allowed to be displayed for caller ID.
1029      */
1030     public static final int PRESENTATION_ALLOWED = 1;
1031 
1032     /**
1033      * Indicates that the address or number of a call is blocked by the other party.
1034      */
1035     public static final int PRESENTATION_RESTRICTED = 2;
1036 
1037     /**
1038      * Indicates that the address or number of a call is not specified or known by the carrier.
1039      */
1040     public static final int PRESENTATION_UNKNOWN = 3;
1041 
1042     /**
1043      * Indicates that the address or number of a call belongs to a pay phone.
1044      */
1045     public static final int PRESENTATION_PAYPHONE = 4;
1046 
1047     /**
1048      * Indicates that the address or number of a call is unavailable.
1049      */
1050     public static final int PRESENTATION_UNAVAILABLE = 5;
1051 
1052 
1053     /**
1054      * Controls audio route for video calls.
1055      * 0 - Use the default audio routing strategy.
1056      * 1 - Disable the speaker. Route the audio to Headset or Bluetooth
1057      *     or Earpiece, based on the default audio routing strategy.
1058      * @hide
1059      */
1060     public static final String PROPERTY_VIDEOCALL_AUDIO_OUTPUT = "persist.radio.call.audio.output";
1061 
1062     /*
1063      * Values for the adb property "persist.radio.call.audio.output"
1064      */
1065     /** @hide */
1066     public static final int AUDIO_OUTPUT_ENABLE_SPEAKER = 0;
1067     /** @hide */
1068     public static final int AUDIO_OUTPUT_DISABLE_SPEAKER = 1;
1069     /** @hide */
1070     public static final int AUDIO_OUTPUT_DEFAULT = AUDIO_OUTPUT_ENABLE_SPEAKER;
1071 
1072     /** @hide */
1073     @Retention(RetentionPolicy.SOURCE)
1074     @IntDef(
1075             prefix = { "PRESENTATION_" },
1076             value = {PRESENTATION_ALLOWED, PRESENTATION_RESTRICTED, PRESENTATION_UNKNOWN,
1077             PRESENTATION_PAYPHONE, PRESENTATION_UNAVAILABLE})
1078     public @interface Presentation {}
1079 
1080 
1081     /**
1082      * Enable READ_PHONE_STATE protection on APIs querying and notifying call state, such as
1083      * {@code TelecomManager#getCallState}, {@link TelephonyManager#getCallStateForSubscription()},
1084      * and {@link android.telephony.TelephonyCallback.CallStateListener}.
1085      * @hide
1086      */
1087     @ChangeId
1088     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
1089     // this magic number is a bug ID
1090     public static final long ENABLE_GET_CALL_STATE_PERMISSION_PROTECTION = 157233955L;
1091 
1092     /**
1093      * Enable READ_PHONE_NUMBERS or READ_PRIVILEGED_PHONE_STATE protections on
1094      * {@link TelecomManager#getPhoneAccount(PhoneAccountHandle)}.
1095      * @hide
1096      */
1097     @ChangeId
1098     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
1099     // bug ID
1100     public static final long ENABLE_GET_PHONE_ACCOUNT_PERMISSION_PROTECTION = 183407956L;
1101 
1102     private static final String TAG = "TelecomManager";
1103 
1104 
1105     /** Cached service handles, cleared by resetServiceCache() at death */
1106     private static final Object CACHE_LOCK = new Object();
1107 
1108     @GuardedBy("CACHE_LOCK")
1109     private static ITelecomService sTelecomService;
1110     @GuardedBy("CACHE_LOCK")
1111     private static final DeathRecipient SERVICE_DEATH = new DeathRecipient();
1112 
1113     private final Context mContext;
1114 
1115     private final ITelecomService mTelecomServiceOverride;
1116 
1117     /** @hide **/
1118     private final ClientTransactionalServiceRepository mTransactionalServiceRepository =
1119             new ClientTransactionalServiceRepository();
1120     /** @hide **/
1121     public static final int TELECOM_TRANSACTION_SUCCESS = 0;
1122     /** @hide **/
1123     public static final String TRANSACTION_CALL_ID_KEY = "TelecomCallId";
1124 
1125     /**
1126      * @hide
1127      */
1128     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)1129     public static TelecomManager from(Context context) {
1130         return (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
1131     }
1132 
1133     /**
1134      * @hide
1135      */
TelecomManager(Context context)1136     public TelecomManager(Context context) {
1137         this(context, null);
1138     }
1139 
1140     /**
1141      * @hide
1142      */
TelecomManager(Context context, ITelecomService telecomServiceImpl)1143     public TelecomManager(Context context, ITelecomService telecomServiceImpl) {
1144         Context appContext = context.getApplicationContext();
1145         if (appContext != null && Objects.equals(context.getAttributionTag(),
1146                 appContext.getAttributionTag())) {
1147             mContext = appContext;
1148         } else {
1149             mContext = context;
1150         }
1151         mTelecomServiceOverride = telecomServiceImpl;
1152     }
1153 
1154     /**
1155      * Return the {@link PhoneAccount} which will be used to place outgoing calls to addresses with
1156      * the specified {@code uriScheme}. This {@link PhoneAccount} will always be a member of the
1157      * list which is returned from invoking {@link #getCallCapablePhoneAccounts()}. The specific
1158      * account returned depends on the following priorities:
1159      * <ul>
1160      * <li> If the user-selected default {@link PhoneAccount} supports the specified scheme, it will
1161      * be returned.
1162      * </li>
1163      * <li> If there exists only one {@link PhoneAccount} that supports the specified scheme, it
1164      * will be returned.
1165      * </li>
1166      * </ul>
1167      * <p>
1168      * If no {@link PhoneAccount} fits the criteria above, this method will return {@code null}.
1169      *
1170      * @param uriScheme The URI scheme.
1171      * @return The {@link PhoneAccountHandle} corresponding to the account to be used.
1172      */
1173     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getDefaultOutgoingPhoneAccount(String uriScheme)1174     public PhoneAccountHandle getDefaultOutgoingPhoneAccount(String uriScheme) {
1175         ITelecomService service = getTelecomService();
1176         if (service != null) {
1177             try {
1178                 return service.getDefaultOutgoingPhoneAccount(uriScheme,
1179                         mContext.getOpPackageName(), mContext.getAttributionTag());
1180             } catch (RemoteException e) {
1181                 Log.e(TAG, "Error calling ITelecomService#getDefaultOutgoingPhoneAccount", e);
1182             }
1183         }
1184         return null;
1185     }
1186 
1187     /**
1188      * Return the {@link PhoneAccount} which is the user-chosen default for making outgoing phone
1189      * calls. This {@code PhoneAccount} will always be a member of the list which is returned from
1190      * calling {@link #getCallCapablePhoneAccounts()}
1191      * <p>
1192      * Apps must be prepared for this method to return {@code null}, indicating that there currently
1193      * exists no user-chosen default {@code PhoneAccount}.
1194      * <p>
1195      * The default dialer has access to use this method.
1196      *
1197      * @return The user outgoing phone account selected by the user, or {@code null} if there is no
1198      * user selected outgoing {@link PhoneAccountHandle}.
1199      */
1200     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getUserSelectedOutgoingPhoneAccount()1201     public @Nullable PhoneAccountHandle getUserSelectedOutgoingPhoneAccount() {
1202         ITelecomService service = getTelecomService();
1203         if (service != null) {
1204             try {
1205                 return service.getUserSelectedOutgoingPhoneAccount(
1206                         mContext.getOpPackageName());
1207             } catch (RemoteException e) {
1208                 Log.e(TAG, "Error calling ITelecomService#getUserSelectedOutgoingPhoneAccount", e);
1209             }
1210         }
1211         return null;
1212     }
1213 
1214     /**
1215      * Sets the user-chosen default {@link PhoneAccountHandle} for making outgoing phone calls.
1216      *
1217      * @param accountHandle The {@link PhoneAccountHandle} which will be used by default for making
1218      *                      outgoing voice calls, or {@code null} if no default is specified (the
1219      *                      user will be asked each time a call is placed in this case).
1220      * @hide
1221      */
1222     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
1223     @SystemApi
setUserSelectedOutgoingPhoneAccount(@ullable PhoneAccountHandle accountHandle)1224     public void setUserSelectedOutgoingPhoneAccount(@Nullable PhoneAccountHandle accountHandle) {
1225         ITelecomService service = getTelecomService();
1226         if (service != null) {
1227             try {
1228                 service.setUserSelectedOutgoingPhoneAccount(accountHandle);
1229             } catch (RemoteException e) {
1230                 Log.e(TAG, "Error calling ITelecomService#setUserSelectedOutgoingPhoneAccount");
1231             }
1232         }
1233     }
1234 
1235     /**
1236      * Returns the current SIM call manager. Apps must be prepared for this method to return
1237      * {@code null}, indicating that there currently exists no SIM call manager {@link PhoneAccount}
1238      * for the default voice subscription.
1239      *
1240      * @return The phone account handle of the current sim call manager for the default voice
1241      * subscription.
1242      * @see SubscriptionManager#getDefaultVoiceSubscriptionId()
1243      */
getSimCallManager()1244     public PhoneAccountHandle getSimCallManager() {
1245         ITelecomService service = getTelecomService();
1246         if (service != null) {
1247             try {
1248                 return service.getSimCallManager(
1249                         SubscriptionManager.getDefaultSubscriptionId(), mContext.getPackageName());
1250             } catch (RemoteException e) {
1251                 Log.e(TAG, "Error calling ITelecomService#getSimCallManager");
1252             }
1253         }
1254         return null;
1255     }
1256 
1257     /**
1258      * Returns current SIM call manager for the Telephony Subscription ID specified. Apps must be
1259      * prepared for this method to return {@code null}, indicating that there currently exists no
1260      * SIM call manager {@link PhoneAccount} for the subscription specified.
1261      *
1262      * @param subscriptionId The Telephony Subscription ID that the SIM call manager should be
1263      *                       queried for.
1264      * @return The phone account handle of the current sim call manager.
1265      * @see SubscriptionManager#getActiveSubscriptionInfoList()
1266      */
getSimCallManagerForSubscription(int subscriptionId)1267     public @Nullable PhoneAccountHandle getSimCallManagerForSubscription(int subscriptionId) {
1268         ITelecomService service = getTelecomService();
1269         if (service != null) {
1270             try {
1271                 return service.getSimCallManager(subscriptionId, mContext.getPackageName());
1272             } catch (RemoteException e) {
1273                 Log.e(TAG, "Error calling ITelecomService#getSimCallManager");
1274             }
1275         }
1276         return null;
1277     }
1278 
1279     /**
1280      * Returns the current SIM call manager for the user-chosen default Telephony Subscription ID
1281      * (see {@link SubscriptionManager#getDefaultSubscriptionId()}) and the specified user. Apps
1282      * must be prepared for this method to return {@code null}, indicating that there currently
1283      * exists no SIM call manager {@link PhoneAccount} for the default voice subscription.
1284      *
1285      * @return The phone account handle of the current sim call manager.
1286      *
1287      * @hide
1288      * @deprecated Use {@link #getSimCallManager()}.
1289      */
1290     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 119305590)
getSimCallManager(int userId)1291     public PhoneAccountHandle getSimCallManager(int userId) {
1292         ITelecomService service = getTelecomService();
1293         if (service != null) {
1294             try {
1295                 return service.getSimCallManagerForUser(userId, mContext.getPackageName());
1296             } catch (RemoteException e) {
1297                 Log.e(TAG, "Error calling ITelecomService#getSimCallManagerForUser");
1298             }
1299         }
1300         return null;
1301     }
1302 
1303     /**
1304      * Returns the current connection manager. Apps must be prepared for this method to return
1305      * {@code null}, indicating that there currently exists no Connection Manager
1306      * {@link PhoneAccount} for the default voice subscription.
1307      *
1308      * @return The phone account handle of the current connection manager.
1309      * @hide
1310      */
1311     @SystemApi
getConnectionManager()1312     public PhoneAccountHandle getConnectionManager() {
1313         return getSimCallManager();
1314     }
1315 
1316     /**
1317      * Returns a list of the {@link PhoneAccountHandle}s which can be used to make and receive phone
1318      * calls which support the specified URI scheme.
1319      * <P>
1320      * For example, invoking with {@code "tel"} will find all {@link PhoneAccountHandle}s which
1321      * support telephone calls (e.g. URIs such as {@code tel:555-555-1212}).  Invoking with
1322      * {@code "sip"} will find all {@link PhoneAccountHandle}s which support SIP calls (e.g. URIs
1323      * such as {@code sip:example@sipexample.com}).
1324      *
1325      * @param uriScheme The URI scheme.
1326      * @return A list of {@code PhoneAccountHandle} objects supporting the URI scheme.
1327      * @hide
1328      */
1329     @SystemApi
1330     @RequiresPermission(anyOf = {
1331             READ_PRIVILEGED_PHONE_STATE,
1332             android.Manifest.permission.READ_PHONE_STATE
1333     })
getPhoneAccountsSupportingScheme(String uriScheme)1334     public List<PhoneAccountHandle> getPhoneAccountsSupportingScheme(String uriScheme) {
1335         ITelecomService service = getTelecomService();
1336         if (service != null) {
1337             try {
1338                 return service.getPhoneAccountsSupportingScheme(uriScheme,
1339                         mContext.getOpPackageName()).getList();
1340             } catch (RemoteException e) {
1341                 Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsSupportingScheme", e);
1342             }
1343         }
1344         return new ArrayList<>();
1345     }
1346 
1347 
1348     /**
1349      * Returns a list of {@link PhoneAccountHandle}s which can be used to make and receive phone
1350      * calls. The returned list includes only those accounts which have been explicitly enabled
1351      * by the user.
1352      *
1353      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
1354      * @return A list of {@code PhoneAccountHandle} objects.
1355      */
1356     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCallCapablePhoneAccounts()1357     public List<PhoneAccountHandle> getCallCapablePhoneAccounts() {
1358         return getCallCapablePhoneAccounts(false);
1359     }
1360 
1361     /**
1362      * Returns a list of {@link PhoneAccountHandle}s which can be used to make and receive phone
1363      * calls. The returned list includes those accounts which have been explicitly enabled.
1364      * In contrast to {@link #getCallCapablePhoneAccounts}, this also includes accounts from
1365      * the calling user's {@link android.os.UserManager#getUserProfiles} profile group.
1366      *
1367      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
1368      * @return A list of {@code PhoneAccountHandle} objects.
1369      *
1370      * @throws IllegalStateException if telecom service is null.
1371      */
1372     @FlaggedApi(com.android.internal.telephony.flags.Flags.FLAG_WORK_PROFILE_API_SPLIT)
1373     @RequiresPermission(allOf = {android.Manifest.permission.READ_PHONE_STATE,
1374             android.Manifest.permission.INTERACT_ACROSS_PROFILES})
getCallCapablePhoneAccountsAcrossProfiles()1375     public @NonNull List<PhoneAccountHandle> getCallCapablePhoneAccountsAcrossProfiles() {
1376         return getCallCapablePhoneAccountsAcrossProfiles(false);
1377     }
1378 
1379 
1380     /**
1381      * Returns a list of {@link PhoneAccountHandle}s for all self-managed
1382      * {@link ConnectionService}s owned by the calling {@link UserHandle}.
1383      * <p>
1384      * Self-Managed {@link ConnectionService}s have a {@link PhoneAccount} with
1385      * {@link PhoneAccount#CAPABILITY_SELF_MANAGED}.
1386      * <p>
1387      * Requires permission {@link android.Manifest.permission#READ_PHONE_STATE}, or that the caller
1388      * is the default dialer app.
1389      * <p>
1390      * A {@link SecurityException} will be thrown if a called is not the default dialer, or lacks
1391      * the {@link android.Manifest.permission#READ_PHONE_STATE} permission.
1392      *
1393      * @return A list of {@code PhoneAccountHandle} objects.
1394      */
1395     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getSelfManagedPhoneAccounts()1396     public @NonNull List<PhoneAccountHandle> getSelfManagedPhoneAccounts() {
1397         ITelecomService service = getTelecomService();
1398         if (service != null) {
1399             try {
1400                 return service.getSelfManagedPhoneAccounts(mContext.getOpPackageName(),
1401                         mContext.getAttributionTag()).getList();
1402             } catch (RemoteException e) {
1403                 Log.e(TAG, "Error calling ITelecomService#getSelfManagedPhoneAccounts()", e);
1404             }
1405         }
1406         return new ArrayList<>();
1407     }
1408 
1409     /**
1410      * Returns a list of {@link PhoneAccountHandle}s owned by the calling self-managed
1411      * {@link ConnectionService}.
1412      * <p>
1413      * Self-Managed {@link ConnectionService}s have a {@link PhoneAccount} with
1414      * {@link PhoneAccount#CAPABILITY_SELF_MANAGED}.
1415      * <p>
1416      * Requires permission {@link android.Manifest.permission#MANAGE_OWN_CALLS}
1417      * <p>
1418      * A {@link SecurityException} will be thrown if a caller lacks the
1419      * {@link android.Manifest.permission#MANAGE_OWN_CALLS} permission.
1420      *
1421      * @return A list of {@code PhoneAccountHandle} objects.
1422      */
1423     @RequiresPermission(Manifest.permission.MANAGE_OWN_CALLS)
getOwnSelfManagedPhoneAccounts()1424     public @NonNull List<PhoneAccountHandle> getOwnSelfManagedPhoneAccounts() {
1425         ITelecomService service = getTelecomService();
1426         if (service != null) {
1427             try {
1428                 return service.getOwnSelfManagedPhoneAccounts(mContext.getOpPackageName(),
1429                         mContext.getAttributionTag()).getList();
1430             } catch (RemoteException e) {
1431                 throw e.rethrowFromSystemServer();
1432             }
1433         }
1434         throw new IllegalStateException("Telecom is not available");
1435     }
1436 
1437     /**
1438      * This API will return all {@link PhoneAccount}s the caller registered via
1439      * {@link TelecomManager#registerPhoneAccount(PhoneAccount)}.  If a {@link PhoneAccount} appears
1440      * to be missing from the list, Telecom has either unregistered the {@link PhoneAccount} (for
1441      * cleanup purposes) or the caller registered the {@link PhoneAccount} under a different user
1442      * and does not have the  {@link android.Manifest.permission#INTERACT_ACROSS_USERS} permission.
1443      * <b>Note:</b> This API will only return {@link PhoneAccount}s registered by the same app.  For
1444      * system Dialers that need all the {@link PhoneAccount}s registered by every application, see
1445      * {@link TelecomManager#getAllPhoneAccounts()}.
1446      *
1447      * @return all the {@link PhoneAccount}s registered by the caller.
1448      */
1449     @SuppressLint("RequiresPermission")
1450     @FlaggedApi(Flags.FLAG_GET_REGISTERED_PHONE_ACCOUNTS)
getRegisteredPhoneAccounts()1451     public @NonNull List<PhoneAccount> getRegisteredPhoneAccounts() {
1452         ITelecomService service = getTelecomService();
1453         if (service != null) {
1454             try {
1455                 return service.getRegisteredPhoneAccounts(
1456                         mContext.getOpPackageName(),
1457                         mContext.getAttributionTag()).getList();
1458             } catch (RemoteException e) {
1459                 throw e.rethrowFromSystemServer();
1460             }
1461         }
1462         throw new IllegalStateException("Telecom is not available");
1463     }
1464 
1465     /**
1466      * Returns a list of {@link PhoneAccountHandle}s including those which have not been enabled
1467      * by the user.
1468      *
1469      * @param includeDisabledAccounts When {@code true}, disabled phone accounts will be included,
1470      *                                when {@code false}, only enabled phone accounts will be
1471      *                                included.
1472      * @return A list of {@code PhoneAccountHandle} objects.
1473      * @hide
1474      */
1475     @SystemApi
1476     @RequiresPermission(READ_PRIVILEGED_PHONE_STATE)
getCallCapablePhoneAccounts( boolean includeDisabledAccounts)1477     public @NonNull List<PhoneAccountHandle> getCallCapablePhoneAccounts(
1478             boolean includeDisabledAccounts) {
1479         ITelecomService service = getTelecomService();
1480         if (service != null) {
1481             try {
1482                 return service.getCallCapablePhoneAccounts(includeDisabledAccounts,
1483                         mContext.getOpPackageName(), mContext.getAttributionTag(), false).getList();
1484             } catch (RemoteException e) {
1485                 Log.e(TAG, "Error calling ITelecomService#getCallCapablePhoneAccounts("
1486                         + includeDisabledAccounts + ")", e);
1487             }
1488         }
1489         return new ArrayList<>();
1490     }
1491 
1492     /**
1493      * Returns a list of {@link PhoneAccountHandle}s visible to current user including those which
1494      * have not been enabled by the user.
1495      *
1496      * @param includeDisabledAccounts When {@code true}, disabled phone accounts will be included,
1497      *                                when {@code false}, only enabled phone accounts will be
1498      *                                included.
1499      * @return A list of {@code PhoneAccountHandle} objects.
1500      *
1501      * @throws IllegalStateException if telecom service is null.
1502      * @hide
1503      */
1504     @SystemApi
1505     @FlaggedApi(com.android.internal.telephony.flags.Flags.FLAG_WORK_PROFILE_API_SPLIT)
1506     @RequiresPermission(allOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1507             android.Manifest.permission.INTERACT_ACROSS_PROFILES})
getCallCapablePhoneAccountsAcrossProfiles( boolean includeDisabledAccounts)1508     public @NonNull List<PhoneAccountHandle> getCallCapablePhoneAccountsAcrossProfiles(
1509             boolean includeDisabledAccounts) {
1510         ITelecomService service = getTelecomService();
1511         if (service == null) {
1512             throw new IllegalStateException("telecom service is null.");
1513         }
1514 
1515         try {
1516             return service.getCallCapablePhoneAccounts(includeDisabledAccounts,
1517                     mContext.getOpPackageName(), mContext.getAttributionTag(), true).getList();
1518         } catch (RemoteException e) {
1519             throw e.rethrowFromSystemServer();
1520         }
1521     }
1522 
1523     /**
1524      *  Returns a list of all {@link PhoneAccount}s registered for the calling package.
1525      *
1526      * @deprecated Use {@link #getSelfManagedPhoneAccounts()} instead to get only self-managed
1527      * {@link PhoneAccountHandle} for the calling package.
1528      * @return A list of {@code PhoneAccountHandle} objects.
1529      * @hide
1530      */
1531     @SystemApi
1532     @SuppressLint("RequiresPermission")
1533     @Deprecated
getPhoneAccountsForPackage()1534     public List<PhoneAccountHandle> getPhoneAccountsForPackage() {
1535         ITelecomService service = getTelecomService();
1536         if (service != null) {
1537             try {
1538                 return service.getPhoneAccountsForPackage(mContext.getPackageName()).getList();
1539             } catch (RemoteException e) {
1540                 Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsForPackage", e);
1541             }
1542         }
1543         return null;
1544     }
1545 
1546     /**
1547      * Return the {@link PhoneAccount} for a specified {@link PhoneAccountHandle}. Object includes
1548      * resources which can be used in a user interface.
1549      *
1550      * Requires Permission:
1551      * {@link android.Manifest.permission#READ_PHONE_NUMBERS} for applications targeting API
1552      * level 31+.
1553      * @param account The {@link PhoneAccountHandle}.
1554      * @return The {@link PhoneAccount} object.
1555      */
getPhoneAccount(PhoneAccountHandle account)1556     public PhoneAccount getPhoneAccount(PhoneAccountHandle account) {
1557         ITelecomService service = getTelecomService();
1558         if (service != null) {
1559             try {
1560                 return service.getPhoneAccount(account, mContext.getPackageName());
1561             } catch (RemoteException e) {
1562                 Log.e(TAG, "Error calling ITelecomService#getPhoneAccount", e);
1563             }
1564         }
1565         return null;
1566     }
1567 
1568     /**
1569      * Returns a count of all {@link PhoneAccount}s.
1570      *
1571      * @return The count of {@link PhoneAccount}s.
1572      * @hide
1573      */
1574     @SystemApi
getAllPhoneAccountsCount()1575     public int getAllPhoneAccountsCount() {
1576         ITelecomService service = getTelecomService();
1577         if (service != null) {
1578             try {
1579                 return service.getAllPhoneAccountsCount();
1580             } catch (RemoteException e) {
1581                 Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccountsCount", e);
1582             }
1583         }
1584         return 0;
1585     }
1586 
1587     /**
1588      * Returns a list of all {@link PhoneAccount}s.
1589      *
1590      * @return All {@link PhoneAccount}s.
1591      * @hide
1592      */
1593     @SystemApi
getAllPhoneAccounts()1594     public List<PhoneAccount> getAllPhoneAccounts() {
1595         ITelecomService service = getTelecomService();
1596         if (service != null) {
1597             try {
1598                 return service.getAllPhoneAccounts().getList();
1599             } catch (RemoteException e) {
1600                 Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccounts", e);
1601             }
1602         }
1603         return Collections.EMPTY_LIST;
1604     }
1605 
1606     /**
1607      * Returns a list of all {@link PhoneAccountHandle}s.
1608      *
1609      * @return All {@link PhoneAccountHandle}s.
1610      * @hide
1611      */
1612     @SystemApi
getAllPhoneAccountHandles()1613     public List<PhoneAccountHandle> getAllPhoneAccountHandles() {
1614         ITelecomService service = getTelecomService();
1615         if (service != null) {
1616             try {
1617                 return service.getAllPhoneAccountHandles().getList();
1618             } catch (RemoteException e) {
1619                 Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccountHandles", e);
1620             }
1621         }
1622         return Collections.EMPTY_LIST;
1623     }
1624 
1625     /**
1626      * Register a {@link PhoneAccount} for use by the system that will be stored in Device Encrypted
1627      * storage. When registering {@link PhoneAccount}s, existing registrations will be overwritten
1628      * if the {@link PhoneAccountHandle} matches that of a {@link PhoneAccount} which is already
1629      * registered. Once registered, the {@link PhoneAccount} is listed to the user as an option
1630      * when placing calls. The user may still need to enable the {@link PhoneAccount} within
1631      * the phone app settings before the account is usable.
1632      * <p>
1633      * Note: Each package is limited to 10 {@link PhoneAccount} registrations.
1634      * <p>
1635      * A {@link SecurityException} will be thrown if an app tries to register a
1636      * {@link PhoneAccountHandle} where the package name specified within
1637      * {@link PhoneAccountHandle#getComponentName()} does not match the package name of the app.
1638      * <p>
1639      * A {@link IllegalArgumentException} will be thrown if an app tries to register a
1640      * {@link PhoneAccount} when the upper bound limit, 10, has already been reached.
1641      *
1642      * @param account The complete {@link PhoneAccount}.
1643      * @throws UnsupportedOperationException if the caller cannot modify phone state and the device
1644      * does not have the Telecom feature.
1645      * @throws SecurityException if:
1646      * <ol>
1647      *     <li>the caller cannot modify phone state and the phone account doesn't belong to the
1648      *     calling user.</li>
1649      *     <li>the caller is registering a self-managed phone and either they are not allowed to
1650      *     manage their own calls or if the account is call capable, a connection manager, or a
1651      *     sim account.</li>
1652      *     <li>the caller is registering a sim account without the ability to do so.</li>
1653      *     <li>the caller is registering a multi-user phone account but isn't a system app.</li>
1654      *     <li>the account can make SIM-based voice calls but the caller cannot register sim
1655      *     accounts or isn't a sim call manager.</li>
1656      *     <li>the account defines the EXTRA_SKIP_CALL_FILTERING extra but the caller isn't
1657      *     able to modify the phone state.</li>
1658      *     <li>the caller is registering an account for a different user but isn't able to
1659      *     interact across users.</li>
1660      *     <li>if simultaneous calling is available and the phone account package name doesn't
1661      *     correspond to the simultaneous calling accounts associated with this phone account.</li>
1662      * </ol>
1663      */
registerPhoneAccount(PhoneAccount account)1664     public void registerPhoneAccount(PhoneAccount account) {
1665         ITelecomService service = getTelecomService();
1666         if (service != null) {
1667             try {
1668                 service.registerPhoneAccount(account, mContext.getPackageName());
1669             } catch (RemoteException e) {
1670                 Log.e(TAG, "Error calling ITelecomService#registerPhoneAccount", e);
1671             }
1672         }
1673     }
1674 
1675     /**
1676      * Remove a {@link PhoneAccount} registration from the system.
1677      *
1678      * @param accountHandle A {@link PhoneAccountHandle} for the {@link PhoneAccount} to unregister.
1679      */
unregisterPhoneAccount(PhoneAccountHandle accountHandle)1680     public void unregisterPhoneAccount(PhoneAccountHandle accountHandle) {
1681         ITelecomService service = getTelecomService();
1682         if (service != null) {
1683             try {
1684                 service.unregisterPhoneAccount(accountHandle, mContext.getPackageName());
1685             } catch (RemoteException e) {
1686                 Log.e(TAG, "Error calling ITelecomService#unregisterPhoneAccount", e);
1687             }
1688         }
1689     }
1690 
1691     /**
1692      * Remove all Accounts that belong to the calling package from the system.
1693      * @hide
1694      */
1695     @SystemApi
1696     @SuppressLint("RequiresPermission")
clearPhoneAccounts()1697     public void clearPhoneAccounts() {
1698         clearAccounts();
1699     }
1700     /**
1701      * Remove all Accounts that belong to the calling package from the system.
1702      * @deprecated Use {@link #clearPhoneAccounts()} instead.
1703      * @hide
1704      */
1705     @SystemApi
1706     @SuppressLint("RequiresPermission")
clearAccounts()1707     public void clearAccounts() {
1708         ITelecomService service = getTelecomService();
1709         if (service != null) {
1710             try {
1711                 service.clearAccounts(mContext.getPackageName());
1712             } catch (RemoteException e) {
1713                 Log.e(TAG, "Error calling ITelecomService#clearAccounts", e);
1714             }
1715         }
1716     }
1717 
1718     /**
1719      * Remove all Accounts that belong to the specified package from the system.
1720      * @hide
1721      */
clearAccountsForPackage(String packageName)1722     public void clearAccountsForPackage(String packageName) {
1723         ITelecomService service = getTelecomService();
1724         if (service != null) {
1725             try {
1726                 if (!TextUtils.isEmpty(packageName)) {
1727                     service.clearAccounts(packageName);
1728                 }
1729             } catch (RemoteException e) {
1730                 Log.e(TAG, "Error calling ITelecomService#clearAccountsForPackage", e);
1731             }
1732         }
1733     }
1734 
1735 
1736     /**
1737      * @deprecated - Use {@link TelecomManager#getDefaultDialerPackage} to directly access
1738      *         the default dialer's package name instead.
1739      * @hide
1740      */
1741     @SystemApi
1742     @SuppressLint("RequiresPermission")
getDefaultPhoneApp()1743     public ComponentName getDefaultPhoneApp() {
1744         ITelecomService service = getTelecomService();
1745         if (service != null) {
1746             try {
1747                 return service.getDefaultPhoneApp();
1748             } catch (RemoteException e) {
1749                 Log.e(TAG, "RemoteException attempting to get the default phone app.", e);
1750             }
1751         }
1752         return null;
1753     }
1754 
1755     /**
1756      * Used to determine the currently selected default dialer package.
1757      *
1758      * @return package name for the default dialer package or null if no package has been
1759      *         selected as the default dialer.
1760      */
getDefaultDialerPackage()1761     public String getDefaultDialerPackage() {
1762         ITelecomService service = getTelecomService();
1763         if (service != null) {
1764             try {
1765                 return service.getDefaultDialerPackage(mContext.getPackageName());
1766             } catch (RemoteException e) {
1767                 Log.e(TAG, "RemoteException attempting to get the default dialer package name.", e);
1768             }
1769         }
1770         return null;
1771     }
1772 
1773     /**
1774      * Used to determine the currently selected default dialer package for a specific user.
1775      *
1776      * @param userHandle the user id to query the default dialer package for.
1777      * @return package name for the default dialer package or null if no package has been
1778      *         selected as the default dialer.
1779      * @hide
1780      */
1781     @SystemApi
1782     @RequiresPermission(READ_PRIVILEGED_PHONE_STATE)
getDefaultDialerPackage(@onNull UserHandle userHandle)1783     public @Nullable String getDefaultDialerPackage(@NonNull UserHandle userHandle) {
1784         ITelecomService service = getTelecomService();
1785         if (service != null) {
1786             try {
1787                 return service.getDefaultDialerPackageForUser(
1788                         userHandle.getIdentifier());
1789             } catch (RemoteException e) {
1790                 Log.e(TAG, "RemoteException attempting to get the default dialer package name.", e);
1791             }
1792         }
1793         return null;
1794     }
1795 
1796     /**
1797      * Used to set the default dialer package.
1798      *
1799      * @param packageName to set the default dialer to, or {@code null} if the system provided
1800      *                    dialer should be used instead.
1801      *
1802      * @result {@code true} if the default dialer was successfully changed, {@code false} if
1803      *         the specified package does not correspond to an installed dialer, or is already
1804      *         the default dialer.
1805      *
1806      * @hide
1807      * @deprecated Use
1808      * {@link android.app.role.RoleManager#addRoleHolderAsUser(String, String, int, UserHandle,
1809      * Executor, java.util.function.Consumer)} instead.
1810      * @removed
1811      */
1812     @SystemApi
1813     @Deprecated
1814     @RequiresPermission(allOf = {
1815             android.Manifest.permission.MODIFY_PHONE_STATE,
1816             android.Manifest.permission.WRITE_SECURE_SETTINGS})
setDefaultDialer(@ullable String packageName)1817     public boolean setDefaultDialer(@Nullable String packageName) {
1818         ITelecomService service = getTelecomService();
1819         if (service != null) {
1820             try {
1821                 return service.setDefaultDialer(packageName);
1822             } catch (RemoteException e) {
1823                 Log.e(TAG, "RemoteException attempting to set the default dialer.", e);
1824             }
1825         }
1826         return false;
1827     }
1828 
1829     /**
1830      * Determines the package name of the system-provided default phone app.
1831      *
1832      * @return package name for the system dialer package or {@code null} if no system dialer is
1833      *         preloaded.
1834      */
getSystemDialerPackage()1835     public @Nullable String getSystemDialerPackage() {
1836         ITelecomService service = getTelecomService();
1837         if (service != null) {
1838             try {
1839                 return service.getSystemDialerPackage(mContext.getPackageName());
1840             } catch (RemoteException e) {
1841                 Log.e(TAG, "RemoteException attempting to get the system dialer package name.", e);
1842             }
1843         }
1844         return null;
1845     }
1846 
1847     /**
1848      * Return whether a given phone number is the configured voicemail number for a
1849      * particular phone account.
1850      *
1851      * @param accountHandle The handle for the account to check the voicemail number against
1852      * @param number The number to look up.
1853      */
1854     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isVoiceMailNumber(PhoneAccountHandle accountHandle, String number)1855     public boolean isVoiceMailNumber(PhoneAccountHandle accountHandle, String number) {
1856         ITelecomService service = getTelecomService();
1857         if (service != null) {
1858             try {
1859                 return service.isVoiceMailNumber(accountHandle, number,
1860                         mContext.getOpPackageName(), mContext.getAttributionTag());
1861             } catch (RemoteException e) {
1862                 Log.e(TAG, "RemoteException calling ITelecomService#isVoiceMailNumber.", e);
1863             }
1864         }
1865         return false;
1866     }
1867 
1868     /**
1869      * Return the voicemail number for a given phone account.
1870      *
1871      * @param accountHandle The handle for the phone account.
1872      * @return The voicemail number for the phone account, and {@code null} if one has not been
1873      *         configured.
1874      */
1875     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailNumber(PhoneAccountHandle accountHandle)1876     public String getVoiceMailNumber(PhoneAccountHandle accountHandle) {
1877         ITelecomService service = getTelecomService();
1878         if (service != null) {
1879             try {
1880                 return service.getVoiceMailNumber(accountHandle,
1881                         mContext.getOpPackageName(), mContext.getAttributionTag());
1882             } catch (RemoteException e) {
1883                 Log.e(TAG, "RemoteException calling ITelecomService#hasVoiceMailNumber.", e);
1884             }
1885         }
1886         return null;
1887     }
1888 
1889     /**
1890      * This test API determines the foreground service delegation state for a VoIP app that adds
1891      * calls via {@link TelecomManager#addCall(CallAttributes, Executor, OutcomeReceiver,
1892      * CallControlCallback, CallEventCallback)}.  Foreground Service Delegation allows applications
1893      * to operate in the background  starting in Android 14 and is granted by Telecom via a request
1894      * to the ActivityManager.
1895      *
1896      * @param handle of the voip app that is being checked
1897      * @return true if the app has foreground service delegation. Otherwise, false.
1898      *
1899      * @hide
1900      */
1901     @FlaggedApi(Flags.FLAG_VOIP_CALL_MONITOR_REFACTOR)
1902     @TestApi
hasForegroundServiceDelegation(@ullable PhoneAccountHandle handle)1903     public boolean hasForegroundServiceDelegation(@Nullable PhoneAccountHandle handle) {
1904         ITelecomService service = getTelecomService();
1905         if (service != null) {
1906             try {
1907                 return service.hasForegroundServiceDelegation(handle, mContext.getOpPackageName());
1908             } catch (RemoteException e) {
1909                 Log.e(TAG,
1910                         "RemoteException calling ITelecomService#hasForegroundServiceDelegation.",
1911                         e);
1912             }
1913         }
1914         return false;
1915     }
1916 
1917     /**
1918      * Return the line 1 phone number for given phone account.
1919      *
1920      * <p>Requires Permission:
1921      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
1922      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
1923      *     or that the caller is the default SMS app for any API level.
1924      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
1925      *     for apps targeting SDK API level 29 and below.
1926      *
1927      * @param accountHandle The handle for the account retrieve a number for.
1928      * @return A string representation of the line 1 phone number.
1929      * @deprecated use {@link SubscriptionManager#getPhoneNumber(int)} instead, which takes a
1930      *             Telephony Subscription ID that can be retrieved with the {@code accountHandle}
1931      *             from {@link TelephonyManager#getSubscriptionId(PhoneAccountHandle)}.
1932      */
1933     @Deprecated
1934     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
1935     @RequiresPermission(anyOf = {
1936             android.Manifest.permission.READ_PHONE_STATE,
1937             android.Manifest.permission.READ_SMS,
1938             android.Manifest.permission.READ_PHONE_NUMBERS
1939             }, conditional = true)
getLine1Number(PhoneAccountHandle accountHandle)1940     public String getLine1Number(PhoneAccountHandle accountHandle) {
1941         ITelecomService service = getTelecomService();
1942         if (service != null) {
1943             try {
1944                 return service.getLine1Number(accountHandle,
1945                         mContext.getOpPackageName(), mContext.getAttributionTag());
1946             } catch (RemoteException e) {
1947                 Log.e(TAG, "RemoteException calling ITelecomService#getLine1Number.", e);
1948             }
1949         }
1950         return null;
1951     }
1952 
1953     /**
1954      * Returns whether there is an ongoing phone call (can be in dialing, ringing, active or holding
1955      * states) originating from either a manager or self-managed {@link ConnectionService}.
1956      *
1957      * @return {@code true} if there is an ongoing call in either a managed or self-managed
1958      *      {@link ConnectionService}, {@code false} otherwise.
1959      */
1960     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isInCall()1961     public boolean isInCall() {
1962         ITelecomService service = getTelecomService();
1963         if (service != null) {
1964             try {
1965                 return service.isInCall(mContext.getOpPackageName(),
1966                         mContext.getAttributionTag());
1967             } catch (RemoteException e) {
1968                 Log.e(TAG, "RemoteException calling isInCall().", e);
1969             }
1970         }
1971         return false;
1972     }
1973 
1974     /**
1975      * Returns whether the caller has {@link android.Manifest.permission#MANAGE_ONGOING_CALLS}
1976      * permission. The permission can be obtained by associating with a physical wearable device
1977      * via the {@link android.companion.CompanionDeviceManager} API as a companion app. If the
1978      * caller app has the permission, it has {@link InCallService} access to manage ongoing calls.
1979      *
1980      * @return {@code true} if the caller has {@link InCallService} access for
1981      *      companion app; {@code false} otherwise.
1982      */
hasManageOngoingCallsPermission()1983     public boolean hasManageOngoingCallsPermission() {
1984         ITelecomService service = getTelecomService();
1985         if (service != null) {
1986             try {
1987                 return service.hasManageOngoingCallsPermission(
1988                         mContext.getOpPackageName());
1989             } catch (RemoteException e) {
1990                 Log.e(TAG, "RemoteException calling hasManageOngoingCallsPermission().", e);
1991                 if (!isSystemProcess()) {
1992                     e.rethrowAsRuntimeException();
1993                 }
1994             }
1995         }
1996         return false;
1997     }
1998 
1999     /**
2000      * Returns whether there is an ongoing call originating from a managed
2001      * {@link ConnectionService}.  An ongoing call can be in dialing, ringing, active or holding
2002      * states.
2003      * <p>
2004      * If you also need to know if there are ongoing self-managed calls, use {@link #isInCall()}
2005      * instead.
2006      *
2007      * @return {@code true} if there is an ongoing call in a managed {@link ConnectionService},
2008      *      {@code false} otherwise.
2009      */
2010     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isInManagedCall()2011     public boolean isInManagedCall() {
2012         ITelecomService service = getTelecomService();
2013         if (service != null) {
2014             try {
2015                 return service.isInManagedCall(mContext.getOpPackageName(),
2016                         mContext.getAttributionTag());
2017             } catch (RemoteException e) {
2018                 Log.e(TAG, "RemoteException calling isInManagedCall().", e);
2019             }
2020         }
2021         return false;
2022     }
2023 
2024     /**
2025      * Returns one of the following constants that represents the current state of Telecom:
2026      *
2027      * {@link TelephonyManager#CALL_STATE_RINGING}
2028      * {@link TelephonyManager#CALL_STATE_OFFHOOK}
2029      * {@link TelephonyManager#CALL_STATE_IDLE}
2030      *
2031      * Takes into consideration both managed and self-managed calls.
2032      * <p>
2033      * Requires Permission:
2034      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
2035      * targeting API level 31+.
2036      *
2037      * @hide
2038      */
2039     @RequiresPermission(anyOf = {READ_PRIVILEGED_PHONE_STATE,
2040             android.Manifest.permission.READ_PHONE_STATE}, conditional = true)
2041     @SystemApi
getCallState()2042     public @CallState int getCallState() {
2043         ITelecomService service = getTelecomService();
2044         if (service != null) {
2045             try {
2046                 return service.getCallStateUsingPackage(mContext.getOpPackageName(),
2047                         mContext.getAttributionTag());
2048             } catch (RemoteException e) {
2049                 Log.d(TAG, "RemoteException calling getCallState().", e);
2050             }
2051         }
2052         return TelephonyManager.CALL_STATE_IDLE;
2053     }
2054 
2055     /**
2056      * Returns whether there currently exists is a ringing incoming-call.
2057      *
2058      * @return {@code true} if there is a managed or self-managed ringing call.
2059      * @hide
2060      */
2061     @SystemApi
2062     @RequiresPermission(anyOf = {
2063             READ_PRIVILEGED_PHONE_STATE,
2064             android.Manifest.permission.READ_PHONE_STATE
2065     })
isRinging()2066     public boolean isRinging() {
2067         ITelecomService service = getTelecomService();
2068         if (service != null) {
2069             try {
2070                 return service.isRinging(mContext.getOpPackageName());
2071             } catch (RemoteException e) {
2072                 Log.e(TAG, "RemoteException attempting to get ringing state of phone app.", e);
2073             }
2074         }
2075         return false;
2076     }
2077 
2078     /**
2079      * Ends the foreground call on the device.
2080      * <p>
2081      * If there is a ringing call, calling this method rejects the ringing call. Otherwise, the
2082      * foreground call is ended.
2083      * <p>
2084      * Note: this method CANNOT be used to end ongoing emergency calls and will return {@code false}
2085      * if an attempt is made to end an emergency call.
2086      * <p>
2087      * Note: If the foreground call on this device is self-managed, this method will only end
2088      * the call if the caller of this method is privileged (i.e. system, shell, or root) or system
2089      * UI.
2090      *
2091      * @return {@code true} if there is a call which will be rejected or terminated, {@code false}
2092      * otherwise.
2093      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
2094      * instead.  Apps performing call screening should use the {@link CallScreeningService} API
2095      * instead.
2096      */
2097     @RequiresPermission(Manifest.permission.ANSWER_PHONE_CALLS)
2098     @Deprecated
endCall()2099     public boolean endCall() {
2100         ITelecomService service = getTelecomService();
2101         if (service != null) {
2102             try {
2103                 return service.endCall(mContext.getPackageName());
2104             } catch (RemoteException e) {
2105                 Log.e(TAG, "Error calling ITelecomService#endCall", e);
2106             }
2107         }
2108         return false;
2109     }
2110 
2111     /**
2112      * If there is a ringing incoming call, this method accepts the call on behalf of the user.
2113      *
2114      * If the incoming call is a video call, the call will be answered with the same video state as
2115      * the incoming call requests.  This means, for example, that an incoming call requesting
2116      * {@link VideoProfile#STATE_BIDIRECTIONAL} will be answered, accepting that state.
2117      *
2118      * If the ringing incoming call is self-managed, this method will only accept the call if the
2119      * caller of this method is privileged (i.e. system, shell, or root) or system UI.
2120      *
2121      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
2122      * instead.
2123      */
2124     //TODO: L-release - need to convert all invocation of ITelecmmService#answerRingingCall to use
2125     // this method (clockwork & gearhead).
2126     @RequiresPermission(anyOf =
2127             {Manifest.permission.ANSWER_PHONE_CALLS, Manifest.permission.MODIFY_PHONE_STATE})
2128     @Deprecated
acceptRingingCall()2129     public void acceptRingingCall() {
2130         ITelecomService service = getTelecomService();
2131         if (service != null) {
2132             try {
2133                 service.acceptRingingCall(mContext.getPackageName());
2134             } catch (RemoteException e) {
2135                 Log.e(TAG, "Error calling ITelecomService#acceptRingingCall", e);
2136             }
2137         }
2138     }
2139 
2140     /**
2141      * If there is a ringing incoming call, this method accepts the call on behalf of the user,
2142      * with the specified video state.
2143      *
2144      * @param videoState The desired video state to answer the call with.
2145      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
2146      * instead.
2147      */
2148     @RequiresPermission(anyOf =
2149             {Manifest.permission.ANSWER_PHONE_CALLS, Manifest.permission.MODIFY_PHONE_STATE})
2150     @Deprecated
acceptRingingCall(int videoState)2151     public void acceptRingingCall(int videoState) {
2152         ITelecomService service = getTelecomService();
2153         if (service != null) {
2154             try {
2155                 service.acceptRingingCallWithVideoState(
2156                         mContext.getPackageName(), videoState);
2157             } catch (RemoteException e) {
2158                 Log.e(TAG, "Error calling ITelecomService#acceptRingingCallWithVideoState", e);
2159             }
2160         }
2161     }
2162 
2163     /**
2164      * Silences the ringer if a ringing call exists.
2165      * <p>
2166      * This method can only be relied upon to stop the ringtone for a call if the ringtone has
2167      * already started playing.  It is intended to handle use-cases such as silencing a ringing call
2168      * when the user presses the volume button during ringing.
2169      * <p>
2170      * If this method is called prior to when the ringtone begins playing, the ringtone will not be
2171      * silenced.  As such it is not intended as a means to avoid playing of a ringtone.
2172      * <p>
2173      * A dialer app which wants to have more control over ringtone playing should declare
2174      * {@link TelecomManager#METADATA_IN_CALL_SERVICE_RINGING} in the manifest entry for their
2175      * {@link InCallService} implementation to indicate that the app wants to be responsible for
2176      * playing the ringtone for all incoming calls.
2177      * <p>
2178      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the
2179      * app fills the dialer role (see {@link #getDefaultDialerPackage()}).
2180      */
2181     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
silenceRinger()2182     public void silenceRinger() {
2183         ITelecomService service = getTelecomService();
2184         if (service != null) {
2185             try {
2186                 service.silenceRinger(mContext.getOpPackageName());
2187             } catch (RemoteException e) {
2188                 Log.e(TAG, "Error calling ITelecomService#silenceRinger", e);
2189             }
2190         }
2191     }
2192 
2193     /**
2194      * Returns whether TTY is supported on this device.
2195      */
2196     @RequiresPermission(anyOf = {
2197             READ_PRIVILEGED_PHONE_STATE,
2198             android.Manifest.permission.READ_PHONE_STATE
2199     })
isTtySupported()2200     public boolean isTtySupported() {
2201         ITelecomService service = getTelecomService();
2202         if (service != null) {
2203             try {
2204                 return service.isTtySupported(mContext.getOpPackageName(),
2205                         mContext.getAttributionTag());
2206             } catch (RemoteException e) {
2207                 Log.e(TAG, "RemoteException attempting to get TTY supported state.", e);
2208             }
2209         }
2210         return false;
2211     }
2212 
2213     /**
2214      * Returns the current TTY mode of the device. For TTY to be on the user must enable it in
2215      * settings and have a wired headset plugged in.
2216      * Valid modes are:
2217      * - {@link TelecomManager#TTY_MODE_OFF}
2218      * - {@link TelecomManager#TTY_MODE_FULL}
2219      * - {@link TelecomManager#TTY_MODE_HCO}
2220      * - {@link TelecomManager#TTY_MODE_VCO}
2221      * @hide
2222      */
2223     @SystemApi
2224     @RequiresPermission(READ_PRIVILEGED_PHONE_STATE)
getCurrentTtyMode()2225     public @TtyMode int getCurrentTtyMode() {
2226         ITelecomService service = getTelecomService();
2227         if (service != null) {
2228             try {
2229                 return service.getCurrentTtyMode(mContext.getOpPackageName(),
2230                         mContext.getAttributionTag());
2231             } catch (RemoteException e) {
2232                 Log.e(TAG, "RemoteException attempting to get the current TTY mode.", e);
2233             }
2234         }
2235         return TTY_MODE_OFF;
2236     }
2237 
2238     /**
2239      * Registers a new incoming call. A {@link ConnectionService} should invoke this method when it
2240      * has an incoming call. For managed {@link ConnectionService}s, the specified
2241      * {@link PhoneAccountHandle} must have been registered with {@link #registerPhoneAccount} and
2242      * the user must have enabled the corresponding {@link PhoneAccount}.  This can be checked using
2243      * {@link #getPhoneAccount}. Self-managed {@link ConnectionService}s must have
2244      * {@link android.Manifest.permission#MANAGE_OWN_CALLS} to add a new incoming call.
2245      * <p>
2246      * Specify the address associated with the incoming call using
2247      * {@link #EXTRA_INCOMING_CALL_ADDRESS}.  If an incoming call is from an anonymous source, omit
2248      * this extra and ensure you specify a valid number presentation via
2249      * {@link Connection#setAddress(Uri, int)} on the {@link Connection} instance you return in
2250      * your
2251      * {@link ConnectionService#onCreateIncomingConnection(PhoneAccountHandle, ConnectionRequest)}
2252      * implementation.
2253      * <p>
2254      * The incoming call you are adding is assumed to have a video state of
2255      * {@link VideoProfile#STATE_AUDIO_ONLY}, unless the extra value
2256      * {@link #EXTRA_INCOMING_VIDEO_STATE} is specified.
2257      * <p>
2258      * Once invoked, this method will cause the system to bind to the {@link ConnectionService}
2259      * associated with the {@link PhoneAccountHandle} and request additional information about the
2260      * call (See {@link ConnectionService#onCreateIncomingConnection}) before starting the incoming
2261      * call UI.
2262      * <p>
2263      * For a managed {@link ConnectionService}, a {@link SecurityException} will be thrown if either
2264      * the {@link PhoneAccountHandle} does not correspond to a registered {@link PhoneAccount} or
2265      * the associated {@link PhoneAccount} is not currently enabled by the user.
2266      * <p>
2267      * For a self-managed {@link ConnectionService}, a {@link SecurityException} will be thrown if
2268      * the {@link PhoneAccount} has {@link PhoneAccount#CAPABILITY_SELF_MANAGED} and the calling app
2269      * does not have {@link android.Manifest.permission#MANAGE_OWN_CALLS}.
2270      * <p>
2271      * <p>
2272      * <b>Note</b>: {@link android.app.Notification.CallStyle} notifications should be posted after
2273      * the call is added to Telecom in order for the notification to be non-dismissible.
2274      * @param phoneAccount A {@link PhoneAccountHandle} registered with
2275      *            {@link #registerPhoneAccount}.
2276      * @param extras A bundle that will be passed through to
2277      *            {@link ConnectionService#onCreateIncomingConnection}.
2278      */
addNewIncomingCall(PhoneAccountHandle phoneAccount, Bundle extras)2279     public void addNewIncomingCall(PhoneAccountHandle phoneAccount, Bundle extras) {
2280         ITelecomService service = getTelecomService();
2281         if (service != null) {
2282             try {
2283                 if (extras != null && extras.getBoolean(EXTRA_IS_HANDOVER) &&
2284                         mContext.getApplicationContext().getApplicationInfo().targetSdkVersion >
2285                                 Build.VERSION_CODES.O_MR1) {
2286                     Log.e("TAG", "addNewIncomingCall failed. Use public api " +
2287                             "acceptHandover for API > O-MR1");
2288                     return;
2289                 }
2290                 service.addNewIncomingCall(phoneAccount, extras == null ? new Bundle() : extras,
2291                         mContext.getPackageName());
2292             } catch (RemoteException e) {
2293                 Log.e(TAG, "RemoteException adding a new incoming call: " + phoneAccount, e);
2294             }
2295         }
2296     }
2297 
2298     /**
2299      * Registers a new incoming conference. A {@link ConnectionService} should invoke this method
2300      * when it has an incoming conference. An incoming {@link Conference} is an adhoc conference
2301      * call initiated on another device which the user is being invited to join in. For managed
2302      * {@link ConnectionService}s, the specified {@link PhoneAccountHandle} must have been
2303      * registered with {@link #registerPhoneAccount} and the user must have enabled the
2304      * corresponding {@link PhoneAccount}.  This can be checked using
2305      * {@link #getPhoneAccount(PhoneAccountHandle)}. Self-managed {@link ConnectionService}s must
2306      * have {@link android.Manifest.permission#MANAGE_OWN_CALLS} to add a new incoming call.
2307      * <p>
2308      * The incoming conference you are adding is assumed to have a video state of
2309      * {@link VideoProfile#STATE_AUDIO_ONLY}, unless the extra value
2310      * {@link #EXTRA_INCOMING_VIDEO_STATE} is specified.
2311      * <p>
2312      * Once invoked, this method will cause the system to bind to the {@link ConnectionService}
2313      * associated with the {@link PhoneAccountHandle} and request additional information about the
2314      * call (See
2315      * {@link ConnectionService#onCreateIncomingConference(PhoneAccountHandle, ConnectionRequest)})
2316      * before starting the incoming call UI.
2317      * <p>
2318      * For a managed {@link ConnectionService}, a {@link SecurityException} will be thrown if either
2319      * the {@link PhoneAccountHandle} does not correspond to a registered {@link PhoneAccount} or
2320      * the associated {@link PhoneAccount} is not currently enabled by the user.
2321      *
2322      * @param phoneAccount A {@link PhoneAccountHandle} registered with
2323      *            {@link #registerPhoneAccount}.
2324      * @param extras A bundle that will be passed through to
2325      *            {@link ConnectionService#onCreateIncomingConference}.
2326      */
addNewIncomingConference(@onNull PhoneAccountHandle phoneAccount, @NonNull Bundle extras)2327     public void addNewIncomingConference(@NonNull PhoneAccountHandle phoneAccount,
2328             @NonNull Bundle extras) {
2329         ITelecomService service = getTelecomService();
2330         if (service != null) {
2331             try {
2332                 service.addNewIncomingConference(
2333                         phoneAccount, extras == null ? new Bundle() : extras,
2334                         mContext.getPackageName());
2335             } catch (RemoteException e) {
2336                 Log.e(TAG, "RemoteException adding a new incoming conference: " + phoneAccount, e);
2337             }
2338         }
2339     }
2340 
2341     /**
2342      * Registers a new unknown call with Telecom. This can only be called by the system Telephony
2343      * service. This is invoked when Telephony detects a new unknown connection that was neither
2344      * a new incoming call, nor an user-initiated outgoing call.
2345      *
2346      * @param phoneAccount A {@link PhoneAccountHandle} registered with
2347      *            {@link #registerPhoneAccount}.
2348      * @param extras A bundle that will be passed through to
2349      *            {@link ConnectionService#onCreateIncomingConnection}.
2350      * @hide
2351      */
2352     @SystemApi
addNewUnknownCall(PhoneAccountHandle phoneAccount, Bundle extras)2353     public void addNewUnknownCall(PhoneAccountHandle phoneAccount, Bundle extras) {
2354         ITelecomService service = getTelecomService();
2355         if (service != null) {
2356             try {
2357                 service.addNewUnknownCall(
2358                         phoneAccount, extras == null ? new Bundle() : extras);
2359             } catch (RemoteException e) {
2360                 Log.e(TAG, "RemoteException adding a new unknown call: " + phoneAccount, e);
2361             }
2362         }
2363     }
2364 
2365     /**
2366      * Processes the specified dial string as an MMI code.
2367      * MMI codes are any sequence of characters entered into the dialpad that contain a "*" or "#".
2368      * Some of these sequences launch special behavior through handled by Telephony.
2369      * This method uses the default subscription.
2370      * <p>
2371      * Requires that the method-caller be set as the system dialer app.
2372      * </p>
2373      *
2374      * @param dialString The digits to dial.
2375      * @return True if the digits were processed as an MMI code, false otherwise.
2376      */
2377     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
2378     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
handleMmi(String dialString)2379     public boolean handleMmi(String dialString) {
2380         ITelecomService service = getTelecomService();
2381         if (service != null) {
2382             try {
2383                 return service.handlePinMmi(dialString, mContext.getOpPackageName());
2384             } catch (RemoteException e) {
2385                 Log.e(TAG, "Error calling ITelecomService#handlePinMmi", e);
2386             }
2387         }
2388         return false;
2389     }
2390 
2391     /**
2392      * Processes the specified dial string as an MMI code.
2393      * MMI codes are any sequence of characters entered into the dialpad that contain a "*" or "#".
2394      * Some of these sequences launch special behavior through handled by Telephony.
2395      * <p>
2396      * Requires that the method-caller be set as the system dialer app.
2397      * </p>
2398      *
2399      * @param accountHandle The handle for the account the MMI code should apply to.
2400      * @param dialString The digits to dial.
2401      * @return True if the digits were processed as an MMI code, false otherwise.
2402      */
2403     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
2404     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
handleMmi(String dialString, PhoneAccountHandle accountHandle)2405     public boolean handleMmi(String dialString, PhoneAccountHandle accountHandle) {
2406         ITelecomService service = getTelecomService();
2407         if (service != null) {
2408             try {
2409                 return service.handlePinMmiForPhoneAccount(accountHandle, dialString,
2410                         mContext.getOpPackageName());
2411             } catch (RemoteException e) {
2412                 Log.e(TAG, "Error calling ITelecomService#handlePinMmi", e);
2413             }
2414         }
2415         return false;
2416     }
2417 
2418     /**
2419      * Returns a URI (with the content:// scheme) specific to the specified {@link PhoneAccount}
2420      * for ADN content retrieval.
2421      * @param accountHandle The handle for the account to derive an adn query URI for or
2422      * {@code null} to return a URI which will use the default account.
2423      * @return The URI (with the content:// scheme) specific to the specified {@link PhoneAccount}
2424      * for the the content retrieve.
2425      */
2426     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle)2427     public Uri getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle) {
2428         ITelecomService service = getTelecomService();
2429         if (service != null && accountHandle != null) {
2430             try {
2431                 return service.getAdnUriForPhoneAccount(accountHandle, mContext.getOpPackageName());
2432             } catch (RemoteException e) {
2433                 Log.e(TAG, "Error calling ITelecomService#getAdnUriForPhoneAccount", e);
2434             }
2435         }
2436         return Uri.parse("content://icc/adn");
2437     }
2438 
2439     /**
2440      * Removes the missed-call notification if one is present and marks missed calls in the call
2441      * log as read.
2442      * <p>
2443      * Requires that the method-caller be set as the default dialer app.
2444      * </p>
2445      */
2446     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
cancelMissedCallsNotification()2447     public void cancelMissedCallsNotification() {
2448         ITelecomService service = getTelecomService();
2449         if (service != null) {
2450             try {
2451                 service.cancelMissedCallsNotification(mContext.getOpPackageName());
2452             } catch (RemoteException e) {
2453                 Log.e(TAG, "Error calling ITelecomService#cancelMissedCallsNotification", e);
2454             }
2455         }
2456     }
2457 
2458     /**
2459      * Brings the in-call screen to the foreground if there is an ongoing call. If there is
2460      * currently no ongoing call, then this method does nothing.
2461      * <p>
2462      * Requires that the method-caller be set as the system dialer app or have the
2463      * {@link android.Manifest.permission#READ_PHONE_STATE} permission.
2464      * </p>
2465      *
2466      * @param showDialpad Brings up the in-call dialpad as part of showing the in-call screen.
2467      */
2468     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
showInCallScreen(boolean showDialpad)2469     public void showInCallScreen(boolean showDialpad) {
2470         ITelecomService service = getTelecomService();
2471         if (service != null) {
2472             try {
2473                 service.showInCallScreen(showDialpad, mContext.getOpPackageName(),
2474                         mContext.getAttributionTag());
2475             } catch (RemoteException e) {
2476                 Log.e(TAG, "Error calling ITelecomService#showCallScreen", e);
2477             }
2478         }
2479     }
2480 
2481     /**
2482      * Places a new outgoing call to the provided address using the system telecom service with
2483      * the specified extras.
2484      *
2485      * This method is equivalent to placing an outgoing call using {@link Intent#ACTION_CALL},
2486      * except that the outgoing call will always be sent via the system telecom service. If
2487      * method-caller is either the user selected default dialer app or preloaded system dialer
2488      * app, then emergency calls will also be allowed.
2489      *
2490      * Placing a call via a managed {@link ConnectionService} requires permission:
2491      * {@link android.Manifest.permission#CALL_PHONE}
2492      *
2493      * Usage example:
2494      * <pre>
2495      * Uri uri = Uri.fromParts("tel", "12345", null);
2496      * Bundle extras = new Bundle();
2497      * extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true);
2498      * telecomManager.placeCall(uri, extras);
2499      * </pre>
2500      *
2501      * The following keys are supported in the supplied extras.
2502      * <ul>
2503      *   <li>{@link #EXTRA_OUTGOING_CALL_EXTRAS}</li>
2504      *   <li>{@link #EXTRA_PHONE_ACCOUNT_HANDLE}</li>
2505      *   <li>{@link #EXTRA_START_CALL_WITH_SPEAKERPHONE}</li>
2506      *   <li>{@link #EXTRA_START_CALL_WITH_VIDEO_STATE}</li>
2507      * </ul>
2508      * <p>
2509      * An app which implements the self-managed {@link ConnectionService} API uses
2510      * {@link #placeCall(Uri, Bundle)} to inform Telecom of a new outgoing call.  A self-managed
2511      * {@link ConnectionService} must include {@link #EXTRA_PHONE_ACCOUNT_HANDLE} to specify its
2512      * associated {@link android.telecom.PhoneAccountHandle}.
2513      *
2514      * Self-managed {@link ConnectionService}s require permission
2515      * {@link android.Manifest.permission#MANAGE_OWN_CALLS}.
2516      *
2517      * <p class="note"><strong>Note:</strong> If this method is used to place an emergency call, it
2518      * is not guaranteed that the call will be placed on the {@link PhoneAccount} provided in
2519      * the {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra (if specified) and may be placed on another
2520      * {@link PhoneAccount} with the {@link PhoneAccount#CAPABILITY_PLACE_EMERGENCY_CALLS}
2521      * capability, depending on external factors, such as network conditions and Modem/SIM status.
2522      * </p>
2523      * <p>
2524      * <p>
2525      * <b>Note</b>: {@link android.app.Notification.CallStyle} notifications should be posted after
2526      * the call is placed in order for the notification to be non-dismissible.
2527      * <p><b>Note</b>: Call Forwarding MMI codes can only be dialed by applications that are
2528      * configured as the user defined default dialer or system dialer role. If a call containing a
2529      * call forwarding MMI code is placed by an application that is not in one of these roles, the
2530      * dialer will be launched with a UI showing the MMI code already populated so that the user can
2531      * confirm the action before the call is placed.
2532      * @param address The address to make the call to.
2533      * @param extras Bundle of extras to use with the call.
2534      */
2535     @RequiresPermission(anyOf = {android.Manifest.permission.CALL_PHONE,
2536             android.Manifest.permission.MANAGE_OWN_CALLS})
placeCall(Uri address, Bundle extras)2537     public void placeCall(Uri address, Bundle extras) {
2538         ITelecomService service = getTelecomService();
2539         if (service != null) {
2540             if (address == null) {
2541                 Log.w(TAG, "Cannot place call to empty address.");
2542             }
2543             try {
2544                 service.placeCall(address, extras == null ? new Bundle() : extras,
2545                         mContext.getOpPackageName(), mContext.getAttributionTag());
2546             } catch (RemoteException e) {
2547                 Log.e(TAG, "Error calling ITelecomService#placeCall", e);
2548             }
2549         }
2550     }
2551 
2552 
2553     /**
2554      * Place a new adhoc conference call with the provided participants using the system telecom
2555      * service. This method doesn't support placing of emergency calls.
2556      *
2557      * An adhoc conference call is established by providing a list of addresses to
2558      * {@code TelecomManager#startConference(List<Uri>, int videoState)} where the
2559      * {@link ConnectionService} is responsible for connecting all indicated participants
2560      * to a conference simultaneously.
2561      * This is in contrast to conferences formed by merging calls together (e.g. using
2562      * {@link android.telecom.Call#mergeConference()}).
2563      *
2564      * The following keys are supported in the supplied extras.
2565      * <ul>
2566      *   <li>{@link #EXTRA_PHONE_ACCOUNT_HANDLE}</li>
2567      *   <li>{@link #EXTRA_START_CALL_WITH_SPEAKERPHONE}</li>
2568      *   <li>{@link #EXTRA_START_CALL_WITH_VIDEO_STATE}</li>
2569      * </ul>
2570      *
2571      * @param participants List of participants to start conference with
2572      * @param extras Bundle of extras to use with the call
2573      */
2574     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
startConference(@onNull List<Uri> participants, @NonNull Bundle extras)2575     public void startConference(@NonNull List<Uri> participants,
2576             @NonNull Bundle extras) {
2577         ITelecomService service = getTelecomService();
2578         if (service != null) {
2579             try {
2580                 service.startConference(participants, extras,
2581                         mContext.getOpPackageName());
2582             } catch (RemoteException e) {
2583                 Log.e(TAG, "Error calling ITelecomService#placeCall", e);
2584             }
2585         }
2586     }
2587 
2588     /**
2589      * Enables and disables specified phone account.
2590      *
2591      * @param handle Handle to the phone account.
2592      * @param isEnabled Enable state of the phone account.
2593      * @hide
2594      */
2595     @SystemApi
2596     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enablePhoneAccount(PhoneAccountHandle handle, boolean isEnabled)2597     public void enablePhoneAccount(PhoneAccountHandle handle, boolean isEnabled) {
2598         ITelecomService service = getTelecomService();
2599         if (service != null) {
2600             try {
2601                 service.enablePhoneAccount(handle, isEnabled);
2602             } catch (RemoteException e) {
2603                 Log.e(TAG, "Error enablePhoneAbbount", e);
2604             }
2605         }
2606     }
2607 
2608     /**
2609      * Dumps telecom analytics for uploading.
2610      *
2611      * @return
2612      * @hide
2613      */
2614     @SystemApi
2615     @RequiresPermission(Manifest.permission.DUMP)
dumpAnalytics()2616     public TelecomAnalytics dumpAnalytics() {
2617         ITelecomService service = getTelecomService();
2618         TelecomAnalytics result = null;
2619         if (service != null) {
2620             try {
2621                 result = service.dumpCallAnalytics();
2622             } catch (RemoteException e) {
2623                 Log.e(TAG, "Error dumping call analytics", e);
2624             }
2625         }
2626         return result;
2627     }
2628 
2629     /**
2630      * Creates the {@link Intent} which can be used with {@link Context#startActivity(Intent)} to
2631      * launch the activity to manage blocked numbers.
2632      * <p> The activity will display the UI to manage blocked numbers only if
2633      * {@link android.provider.BlockedNumberContract#canCurrentUserBlockNumbers(Context)} returns
2634      * {@code true} for the current user.
2635      */
createManageBlockedNumbersIntent()2636     public Intent createManageBlockedNumbersIntent() {
2637         ITelecomService service = getTelecomService();
2638         Intent result = null;
2639         if (service != null) {
2640             try {
2641                 result = service.createManageBlockedNumbersIntent(mContext.getPackageName());
2642                 if (result != null) {
2643                     result.prepareToEnterProcess(LOCAL_FLAG_FROM_SYSTEM,
2644                             mContext.getAttributionSource());
2645                 }
2646             } catch (RemoteException e) {
2647                 Log.e(TAG, "Error calling ITelecomService#createManageBlockedNumbersIntent", e);
2648             }
2649         }
2650         return result;
2651     }
2652 
2653 
2654     /**
2655      * Creates the {@link Intent} which can be used with {@link Context#startActivity(Intent)} to
2656      * launch the activity for emergency dialer.
2657      *
2658      * @param number Optional number to call in emergency dialer
2659      * @hide
2660      */
2661     @SystemApi
2662     @NonNull
createLaunchEmergencyDialerIntent(@ullable String number)2663     public Intent createLaunchEmergencyDialerIntent(@Nullable String number) {
2664         ITelecomService service = getTelecomService();
2665         if (service != null) {
2666             try {
2667                 Intent result = service.createLaunchEmergencyDialerIntent(number);
2668                 if (result != null) {
2669                     result.prepareToEnterProcess(LOCAL_FLAG_FROM_SYSTEM,
2670                             mContext.getAttributionSource());
2671                 }
2672                 return result;
2673             } catch (RemoteException e) {
2674                 Log.e(TAG, "Error createLaunchEmergencyDialerIntent", e);
2675             }
2676         } else {
2677             Log.w(TAG, "createLaunchEmergencyDialerIntent - Telecom service not available.");
2678         }
2679 
2680         // Telecom service knows the package name of the expected emergency dialer package; if it
2681         // is not available, then fallback to not targeting a specific package.
2682         Intent intent = new Intent(Intent.ACTION_DIAL_EMERGENCY);
2683         if (!TextUtils.isEmpty(number) && TextUtils.isDigitsOnly(number)) {
2684             intent.setData(Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null));
2685         }
2686         return intent;
2687     }
2688 
2689     /**
2690      * Determines whether Telecom would permit an incoming call to be added via the
2691      * {@link #addNewIncomingCall(PhoneAccountHandle, Bundle)} API for the specified
2692      * {@link PhoneAccountHandle}.
2693      * <p>
2694      * A {@link ConnectionService} may not add a call for the specified {@link PhoneAccountHandle}
2695      * in the following situations:
2696      * <ul>
2697      *     <li>{@link PhoneAccount} does not have property
2698      *     {@link PhoneAccount#CAPABILITY_SELF_MANAGED} set (i.e. it is a managed
2699      *     {@link ConnectionService}), and the active or held call limit has
2700      *     been reached.</li>
2701      *     <li>There is an ongoing emergency call.</li>
2702      * </ul>
2703      *
2704      * @param phoneAccountHandle The {@link PhoneAccountHandle} the call will be added for.
2705      * @return {@code true} if telecom will permit an incoming call to be added, {@code false}
2706      *      otherwise.
2707      */
isIncomingCallPermitted(PhoneAccountHandle phoneAccountHandle)2708     public boolean isIncomingCallPermitted(PhoneAccountHandle phoneAccountHandle) {
2709         if (phoneAccountHandle == null) {
2710             return false;
2711         }
2712 
2713         ITelecomService service = getTelecomService();
2714         if (service != null) {
2715             try {
2716                 return service.isIncomingCallPermitted(phoneAccountHandle,
2717                         mContext.getOpPackageName());
2718             } catch (RemoteException e) {
2719                 Log.e(TAG, "Error isIncomingCallPermitted", e);
2720             }
2721         }
2722         return false;
2723     }
2724 
2725     /**
2726      * Determines whether Telecom would permit an outgoing call to be placed via the
2727      * {@link #placeCall(Uri, Bundle)} API for the specified {@link PhoneAccountHandle}.
2728      * <p>
2729      * A {@link ConnectionService} may not place a call for the specified {@link PhoneAccountHandle}
2730      * in the following situations:
2731      * <ul>
2732      *     <li>{@link PhoneAccount} does not have property
2733      *     {@link PhoneAccount#CAPABILITY_SELF_MANAGED} set (i.e. it is a managed
2734      *     {@link ConnectionService}), and the active, held or ringing call limit has
2735      *     been reached.</li>
2736      *     <li>{@link PhoneAccount} has property {@link PhoneAccount#CAPABILITY_SELF_MANAGED} set
2737      *     (i.e. it is a self-managed {@link ConnectionService} and there is an ongoing call in
2738      *     another {@link ConnectionService}.</li>
2739      *     <li>There is an ongoing emergency call.</li>
2740      * </ul>
2741      *
2742      * @param phoneAccountHandle The {@link PhoneAccountHandle} the call will be added for.
2743      * @return {@code true} if telecom will permit an outgoing call to be placed, {@code false}
2744      *      otherwise.
2745      */
isOutgoingCallPermitted(PhoneAccountHandle phoneAccountHandle)2746     public boolean isOutgoingCallPermitted(PhoneAccountHandle phoneAccountHandle) {
2747         ITelecomService service = getTelecomService();
2748         if (service != null) {
2749             try {
2750                 return service.isOutgoingCallPermitted(phoneAccountHandle,
2751                         mContext.getOpPackageName());
2752             } catch (RemoteException e) {
2753                 Log.e(TAG, "Error isOutgoingCallPermitted", e);
2754             }
2755         }
2756         return false;
2757     }
2758 
2759     /**
2760      * Called by an app to indicate that it wishes to accept the handover of an ongoing call to a
2761      * {@link PhoneAccountHandle} it defines.
2762      * <p>
2763      * A call handover is the process where an ongoing call is transferred from one app (i.e.
2764      * {@link ConnectionService} to another app.  The user could, for example, choose to continue a
2765      * mobile network call in a video calling app.  The mobile network call via the Telephony stack
2766      * is referred to as the source of the handover, and the video calling app is referred to as the
2767      * destination.
2768      * <p>
2769      * When considering a handover scenario the <em>initiating</em> device is where a user initiated
2770      * the handover process (e.g. by calling {@link android.telecom.Call#handoverTo(
2771      * PhoneAccountHandle, int, Bundle)}, and the other device is considered the <em>receiving</em>
2772      * device.
2773      * <p>
2774      * For a full discussion of the handover process and the APIs involved, see
2775      * {@link android.telecom.Call#handoverTo(PhoneAccountHandle, int, Bundle)}.
2776      * <p>
2777      * This method is called from the <em>receiving</em> side of a handover to indicate a desire to
2778      * accept the handover of an ongoing call to another {@link ConnectionService} identified by
2779      * {@link PhoneAccountHandle} destAcct. For managed {@link ConnectionService}s, the specified
2780      * {@link PhoneAccountHandle} must have been registered with {@link #registerPhoneAccount} and
2781      * the user must have enabled the corresponding {@link PhoneAccount}.  This can be checked using
2782      * {@link #getPhoneAccount}. Self-managed {@link ConnectionService}s must have
2783      * {@link android.Manifest.permission#MANAGE_OWN_CALLS} to handover a call to it.
2784      * <p>
2785      * Once invoked, this method will cause the system to bind to the {@link ConnectionService}
2786      * associated with the {@link PhoneAccountHandle} destAcct and call
2787      * (See {@link ConnectionService#onCreateIncomingHandoverConnection}).
2788      * <p>
2789      * For a managed {@link ConnectionService}, a {@link SecurityException} will be thrown if either
2790      * the {@link PhoneAccountHandle} destAcct does not correspond to a registered
2791      * {@link PhoneAccount} or the associated {@link PhoneAccount} is not currently enabled by the
2792      * user.
2793      * <p>
2794      * For a self-managed {@link ConnectionService}, a {@link SecurityException} will be thrown if
2795      * the calling app does not have {@link android.Manifest.permission#MANAGE_OWN_CALLS}.
2796      *
2797      * @param srcAddr The {@link android.net.Uri} of the ongoing call to handover to the caller’s
2798      *                {@link ConnectionService}.
2799      * @param videoState Video state after the handover.
2800      * @param destAcct The {@link PhoneAccountHandle} registered to the calling package.
2801      */
acceptHandover(Uri srcAddr, @VideoProfile.VideoState int videoState, PhoneAccountHandle destAcct)2802     public void acceptHandover(Uri srcAddr, @VideoProfile.VideoState int videoState,
2803             PhoneAccountHandle destAcct) {
2804         ITelecomService service = getTelecomService();
2805         if (service != null) {
2806             try {
2807                 service.acceptHandover(srcAddr, videoState, destAcct, mContext.getPackageName());
2808             } catch (RemoteException e) {
2809                 Log.e(TAG, "RemoteException acceptHandover: " + e);
2810             }
2811         }
2812     }
2813 
2814     /**
2815      * Determines if there is an ongoing emergency call.  This can be either an outgoing emergency
2816      * call, as identified by the dialed number, or because a call was identified by the network
2817      * as an emergency call.
2818      * @return {@code true} if there is an ongoing emergency call, {@code false} otherwise.
2819      * @hide
2820      */
2821     @SystemApi
2822     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
isInEmergencyCall()2823     public boolean isInEmergencyCall() {
2824         ITelecomService service = getTelecomService();
2825         if (service != null) {
2826             try {
2827                 return service.isInEmergencyCall();
2828             } catch (RemoteException e) {
2829                 Log.e(TAG, "RemoteException isInEmergencyCall: " + e);
2830                 return false;
2831             }
2832         }
2833         return false;
2834     }
2835 
2836     /**
2837      * Determines whether there are any ongoing {@link PhoneAccount#CAPABILITY_SELF_MANAGED}
2838      * calls for a given {@code packageName} and {@code userHandle}. If UserHandle.ALL or a user
2839      * that isn't the calling user is passed in, the caller will need to have granted the ability
2840      * to interact across users.
2841      *
2842      * @param packageName the package name of the app to check calls for.
2843      * @param userHandle the user handle to check calls for.
2844      * @return {@code true} if there are ongoing calls, {@code false} otherwise.
2845      * @throws SecurityException if the userHandle is not the calling user and the caller does not
2846      * grant the ability to interact across users.
2847      * @hide
2848      */
2849     @SystemApi
2850     @FlaggedApi(Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
2851     @RequiresPermission(allOf = {Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
2852             Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true)
isInSelfManagedCall(@onNull String packageName, @NonNull UserHandle userHandle)2853     public boolean isInSelfManagedCall(@NonNull String packageName,
2854             @NonNull UserHandle userHandle) {
2855         ITelecomService service = getTelecomService();
2856         if (service != null) {
2857             try {
2858                 return service.isInSelfManagedCall(packageName, userHandle,
2859                         mContext.getOpPackageName());
2860             } catch (RemoteException e) {
2861                 Log.e(TAG, "RemoteException isInSelfManagedCall: " + e);
2862                 e.rethrowFromSystemServer();
2863                 return false;
2864             }
2865         } else {
2866             throw new IllegalStateException("Telecom service is not present");
2867         }
2868     }
2869 
2870     /**
2871      * Add a call to the Android system service Telecom. This allows the system to start tracking an
2872      * incoming or outgoing call with the specified {@link CallAttributes}.  Once a call is added,
2873      * a {@link android.app.Notification.CallStyle} notification should be posted and when the
2874      * call is ready to be disconnected, use {@link CallControl#disconnect(DisconnectCause,
2875      * Executor, OutcomeReceiver)} which is provided by the
2876      * {@code pendingControl#onResult(CallControl)}.
2877      * <p>
2878      * <p>
2879      * <p>
2880      * <b>Call Lifecycle</b>: Your app is given foreground execution priority as long as you have a
2881      * valid call and are posting a {@link android.app.Notification.CallStyle} notification.
2882      * When your application is given foreground execution priority, your app is treated as a
2883      * foreground service. Foreground execution priority will prevent the
2884      * {@link android.app.ActivityManager} from killing your application when it is placed the
2885      * background. Foreground execution priority is removed from your app when all of your app's
2886      * calls terminate or your app no longer posts a valid notification.
2887      * <p>
2888      * <p>
2889      * <p>
2890      * <b>Note</b>: Only packages that register with
2891      * {@link PhoneAccount#CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS}
2892      * can utilize this API. {@link PhoneAccount}s that set the capabilities
2893      * {@link PhoneAccount#CAPABILITY_SIM_SUBSCRIPTION},
2894      * {@link PhoneAccount#CAPABILITY_CALL_PROVIDER},
2895      * {@link PhoneAccount#CAPABILITY_CONNECTION_MANAGER}
2896      * are not supported and will cause an exception to be thrown.
2897      * <p>
2898      * <p>
2899      * <p>
2900      * <b>Usage example:</b>
2901      * <pre>
2902      *  // Its up to your app on how you want to wrap the objects. One such implementation can be:
2903      *  class MyVoipCall {
2904      *    ...
2905      *      public CallControlCallEventCallback handshakes = new  CallControlCallback() {
2906      *                         ...
2907      *                        }
2908      *
2909      *      public CallEventCallback events = new CallEventCallback() {
2910      *                         ...
2911      *                        }
2912      *
2913      *      public MyVoipCall(String id){
2914      *          ...
2915      *      }
2916      *  }
2917      *
2918      * MyVoipCall myFirstOutgoingCall = new MyVoipCall("1");
2919      *
2920      * telecomManager.addCall(callAttributes,
2921      *                        Runnable::run,
2922      *                        new OutcomeReceiver() {
2923      *                              public void onResult(CallControl callControl) {
2924      *                                 // The call has been added successfully. For demonstration
2925      *                                 // purposes, the call is disconnected immediately ...
2926      *                                 callControl.disconnect(
2927      *                                                 new DisconnectCause(DisconnectCause.LOCAL) )
2928      *                              }
2929      *                           },
2930      *                           myFirstOutgoingCall.handshakes,
2931      *                           myFirstOutgoingCall.events);
2932      * </pre>
2933      *
2934      * @param callAttributes attributes of the new call (incoming or outgoing, address, etc.)
2935      * @param executor       execution context to run {@link CallControlCallback} updates on
2936      * @param pendingControl Receives the result of addCall transaction. Upon success, a
2937      *                       CallControl object is provided which can be used to do things like
2938      *                       disconnect the call that was added.
2939      * @param handshakes     callback that receives <b>actionable</b> updates that originate from
2940      *                       Telecom.
2941      * @param events         callback that receives <b>non</b>-actionable updates that originate
2942      *                       from Telecom.
2943      */
2944     @RequiresPermission(android.Manifest.permission.MANAGE_OWN_CALLS)
2945     @SuppressLint("SamShouldBeLast")
addCall(@onNull CallAttributes callAttributes, @NonNull @CallbackExecutor Executor executor, @NonNull OutcomeReceiver<CallControl, CallException> pendingControl, @NonNull CallControlCallback handshakes, @NonNull CallEventCallback events)2946     public void addCall(@NonNull CallAttributes callAttributes,
2947             @NonNull @CallbackExecutor Executor executor,
2948             @NonNull OutcomeReceiver<CallControl, CallException> pendingControl,
2949             @NonNull CallControlCallback handshakes,
2950             @NonNull CallEventCallback events) {
2951         Objects.requireNonNull(callAttributes);
2952         Objects.requireNonNull(executor);
2953         Objects.requireNonNull(pendingControl);
2954         Objects.requireNonNull(handshakes);
2955         Objects.requireNonNull(events);
2956 
2957         ITelecomService service = getTelecomService();
2958         if (service != null) {
2959             try {
2960                 // create or add the new call to a service wrapper w/ the same phoneAccountHandle
2961                 ClientTransactionalServiceWrapper transactionalServiceWrapper =
2962                         mTransactionalServiceRepository.addNewCallForTransactionalServiceWrapper(
2963                                 callAttributes.getPhoneAccountHandle());
2964 
2965                 // couple all the args passed by the client
2966                 String newCallId = transactionalServiceWrapper.trackCall(callAttributes, executor,
2967                         pendingControl, handshakes, events);
2968 
2969                 // send args to server to process new call
2970                 service.addCall(callAttributes, transactionalServiceWrapper.getCallEventCallback(),
2971                         newCallId, mContext.getOpPackageName());
2972             } catch (RemoteException e) {
2973                 Log.e(TAG, "RemoteException addCall: " + e);
2974                 e.rethrowFromSystemServer();
2975             }
2976         } else {
2977             throw new IllegalStateException("Telecom service is not present");
2978         }
2979     }
2980 
2981     /**
2982      * Handles {@link Intent#ACTION_CALL} intents trampolined from UserCallActivity.
2983      * @param intent The {@link Intent#ACTION_CALL} intent to handle.
2984      * @param callingPackageProxy The original package that called this before it was trampolined.
2985      * @hide
2986      */
handleCallIntent(Intent intent, String callingPackageProxy)2987     public void handleCallIntent(Intent intent, String callingPackageProxy) {
2988         ITelecomService service = getTelecomService();
2989         if (service != null) {
2990             try {
2991                 service.handleCallIntent(intent, callingPackageProxy);
2992             } catch (RemoteException e) {
2993                 Log.e(TAG, "RemoteException handleCallIntent: " + e);
2994             }
2995         }
2996     }
2997 
isSystemProcess()2998     private boolean isSystemProcess() {
2999         return Process.myUid() == Process.SYSTEM_UID;
3000     }
3001 
getTelecomService()3002     private ITelecomService getTelecomService() {
3003         if (mTelecomServiceOverride != null) {
3004             return mTelecomServiceOverride;
3005         }
3006         if (sTelecomService == null) {
3007             ITelecomService temp = ITelecomService.Stub.asInterface(
3008                     ServiceManager.getService(Context.TELECOM_SERVICE));
3009             synchronized (CACHE_LOCK) {
3010                 if (sTelecomService == null && temp != null) {
3011                     try {
3012                         sTelecomService = temp;
3013                         sTelecomService.asBinder().linkToDeath(SERVICE_DEATH, 0);
3014                     } catch (Exception e) {
3015                         sTelecomService = null;
3016                     }
3017                 }
3018             }
3019         }
3020         return sTelecomService;
3021     }
3022 
3023     private static class DeathRecipient implements IBinder.DeathRecipient {
3024         @Override
binderDied()3025         public void binderDied() {
3026             resetServiceCache();
3027         }
3028     }
3029 
resetServiceCache()3030     private static void resetServiceCache() {
3031         synchronized (CACHE_LOCK) {
3032             if (sTelecomService != null) {
3033                 sTelecomService.asBinder().unlinkToDeath(SERVICE_DEATH, 0);
3034                 sTelecomService = null;
3035             }
3036         }
3037     }
3038 }
3039