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 android.Manifest;
18 import android.annotation.RequiresPermission;
19 import android.annotation.SuppressAutoDoc;
20 import android.annotation.SuppressLint;
21 import android.annotation.SystemApi;
22 import android.annotation.SystemService;
23 import android.content.ComponentName;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.net.Uri;
27 import android.os.Bundle;
28 import android.os.RemoteException;
29 import android.os.ServiceManager;
30 import android.telephony.TelephonyManager;
31 import android.text.TextUtils;
32 import android.util.Log;
33 
34 import com.android.internal.telecom.ITelecomService;
35 
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.List;
39 
40 /**
41  * Provides access to information about active calls and registration/call-management functionality.
42  * Apps can use methods in this class to determine the current call state.
43  * <p>
44  * Apps do not instantiate this class directly; instead, they retrieve a reference to an instance
45  * through {@link Context#getSystemService Context.getSystemService(Context.TELECOM_SERVICE)}.
46  * <p>
47  * Note that access to some telecom information is permission-protected. Your app cannot access the
48  * protected information or gain access to protected functionality unless it has the appropriate
49  * permissions declared in its manifest file. Where permissions apply, they are noted in the method
50  * descriptions.
51  */
52 @SuppressAutoDoc
53 @SystemService(Context.TELECOM_SERVICE)
54 public class TelecomManager {
55 
56     /**
57      * Activity action: Starts the UI for handing an incoming call. This intent starts the in-call
58      * UI by notifying the Telecom system that an incoming call exists for a specific call service
59      * (see {@link android.telecom.ConnectionService}). Telecom reads the Intent extras to find
60      * and bind to the appropriate {@link android.telecom.ConnectionService} which Telecom will
61      * ultimately use to control and get information about the call.
62      * <p>
63      * Input: get*Extra field {@link #EXTRA_PHONE_ACCOUNT_HANDLE} contains the component name of the
64      * {@link android.telecom.ConnectionService} that Telecom should bind to. Telecom will then
65      * ask the connection service for more information about the call prior to showing any UI.
66      *
67      * @deprecated Use {@link #addNewIncomingCall} instead.
68      */
69     public static final String ACTION_INCOMING_CALL = "android.telecom.action.INCOMING_CALL";
70 
71     /**
72      * Similar to {@link #ACTION_INCOMING_CALL}, but is used only by Telephony to add a new
73      * sim-initiated MO call for carrier testing.
74      * @deprecated Use {@link #addNewUnknownCall} instead.
75      * @hide
76      */
77     public static final String ACTION_NEW_UNKNOWN_CALL = "android.telecom.action.NEW_UNKNOWN_CALL";
78 
79     /**
80      * An {@link android.content.Intent} action sent by the telecom framework to start a
81      * configuration dialog for a registered {@link PhoneAccount}. There is no default dialog
82      * and each app that registers a {@link PhoneAccount} should provide one if desired.
83      * <p>
84      * A user can access the list of enabled {@link android.telecom.PhoneAccount}s through the Phone
85      * app's settings menu. For each entry, the settings app will add a click action. When
86      * triggered, the click-action will start this intent along with the extra
87      * {@link #EXTRA_PHONE_ACCOUNT_HANDLE} to indicate the {@link PhoneAccount} to configure. If the
88      * {@link PhoneAccount} package does not register an {@link android.app.Activity} for this
89      * intent, then it will not be sent.
90      */
91     public static final String ACTION_CONFIGURE_PHONE_ACCOUNT =
92             "android.telecom.action.CONFIGURE_PHONE_ACCOUNT";
93 
94     /**
95      * The {@link android.content.Intent} action used to show the call accessibility settings page.
96      */
97     public static final String ACTION_SHOW_CALL_ACCESSIBILITY_SETTINGS =
98             "android.telecom.action.SHOW_CALL_ACCESSIBILITY_SETTINGS";
99 
100     /**
101      * The {@link android.content.Intent} action used to show the call settings page.
102      */
103     public static final String ACTION_SHOW_CALL_SETTINGS =
104             "android.telecom.action.SHOW_CALL_SETTINGS";
105 
106     /**
107      * The {@link android.content.Intent} action used to show the respond via SMS settings page.
108      */
109     public static final String ACTION_SHOW_RESPOND_VIA_SMS_SETTINGS =
110             "android.telecom.action.SHOW_RESPOND_VIA_SMS_SETTINGS";
111 
112     /**
113      * The {@link android.content.Intent} action used to show the settings page used to configure
114      * {@link PhoneAccount} preferences.
115      */
116     public static final String ACTION_CHANGE_PHONE_ACCOUNTS =
117             "android.telecom.action.CHANGE_PHONE_ACCOUNTS";
118 
119     /**
120      * {@link android.content.Intent} action used indicate that a new phone account was just
121      * registered.
122      * <p>
123      * The Intent {@link Intent#getExtras() extras} will contain {@link #EXTRA_PHONE_ACCOUNT_HANDLE}
124      * to indicate which {@link PhoneAccount} was registered.
125      * <p>
126      * Will only be sent to the default dialer app (see {@link #getDefaultDialerPackage()}).
127      */
128     public static final String ACTION_PHONE_ACCOUNT_REGISTERED =
129             "android.telecom.action.PHONE_ACCOUNT_REGISTERED";
130 
131     /**
132      * {@link android.content.Intent} action used indicate that a phone account was just
133      * unregistered.
134      * <p>
135      * The Intent {@link Intent#getExtras() extras} will contain {@link #EXTRA_PHONE_ACCOUNT_HANDLE}
136      * to indicate which {@link PhoneAccount} was unregistered.
137      * <p>
138      * Will only be sent to the default dialer app (see {@link #getDefaultDialerPackage()}).
139      */
140     public static final String ACTION_PHONE_ACCOUNT_UNREGISTERED =
141             "android.telecom.action.PHONE_ACCOUNT_UNREGISTERED";
142 
143     /**
144      * Activity action: Shows a dialog asking the user whether or not they want to replace the
145      * current default Dialer with the one specified in
146      * {@link #EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME}.
147      *
148      * Usage example:
149      * <pre>
150      * Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
151      * intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
152      *         getActivity().getPackageName());
153      * startActivity(intent);
154      * </pre>
155      */
156     public static final String ACTION_CHANGE_DEFAULT_DIALER =
157             "android.telecom.action.CHANGE_DEFAULT_DIALER";
158 
159     /**
160      * Broadcast intent action indicating that the current default dialer has changed.
161      * The string extra {@link #EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME} will contain the
162      * name of the package that the default dialer was changed to.
163      *
164      * @see #EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME
165      */
166     public static final String ACTION_DEFAULT_DIALER_CHANGED =
167             "android.telecom.action.DEFAULT_DIALER_CHANGED";
168 
169     /**
170      * Extra value used to provide the package name for {@link #ACTION_CHANGE_DEFAULT_DIALER}.
171      */
172     public static final String EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME =
173             "android.telecom.extra.CHANGE_DEFAULT_DIALER_PACKAGE_NAME";
174 
175     /**
176      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing a boolean that
177      * determines whether the speakerphone should be automatically turned on for an outgoing call.
178      */
179     public static final String EXTRA_START_CALL_WITH_SPEAKERPHONE =
180             "android.telecom.extra.START_CALL_WITH_SPEAKERPHONE";
181 
182     /**
183      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing an integer that
184      * determines the desired video state for an outgoing call.
185      * Valid options:
186      * {@link VideoProfile#STATE_AUDIO_ONLY},
187      * {@link VideoProfile#STATE_BIDIRECTIONAL},
188      * {@link VideoProfile#STATE_RX_ENABLED},
189      * {@link VideoProfile#STATE_TX_ENABLED}.
190      */
191     public static final String EXTRA_START_CALL_WITH_VIDEO_STATE =
192             "android.telecom.extra.START_CALL_WITH_VIDEO_STATE";
193 
194     /**
195      * Optional extra for {@link #addNewIncomingCall(PhoneAccountHandle, Bundle)} containing an
196      * integer that determines the requested video state for an incoming call.
197      * Valid options:
198      * {@link VideoProfile#STATE_AUDIO_ONLY},
199      * {@link VideoProfile#STATE_BIDIRECTIONAL},
200      * {@link VideoProfile#STATE_RX_ENABLED},
201      * {@link VideoProfile#STATE_TX_ENABLED}.
202      */
203     public static final String EXTRA_INCOMING_VIDEO_STATE =
204             "android.telecom.extra.INCOMING_VIDEO_STATE";
205 
206     /**
207      * The extra used with an {@link android.content.Intent#ACTION_CALL} and
208      * {@link android.content.Intent#ACTION_DIAL} {@code Intent} to specify a
209      * {@link PhoneAccountHandle} to use when making the call.
210      * <p class="note">
211      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
212      */
213     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
214             "android.telecom.extra.PHONE_ACCOUNT_HANDLE";
215 
216     /**
217      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing a string call
218      * subject which will be associated with an outgoing call.  Should only be specified if the
219      * {@link PhoneAccount} supports the capability {@link PhoneAccount#CAPABILITY_CALL_SUBJECT}.
220      */
221     public static final String EXTRA_CALL_SUBJECT = "android.telecom.extra.CALL_SUBJECT";
222 
223     /**
224      * The extra used by a {@link ConnectionService} to provide the handle of the caller that
225      * has initiated a new incoming call.
226      */
227     public static final String EXTRA_INCOMING_CALL_ADDRESS =
228             "android.telecom.extra.INCOMING_CALL_ADDRESS";
229 
230     /**
231      * Optional extra for {@link #ACTION_INCOMING_CALL} containing a {@link Bundle} which contains
232      * metadata about the call. This {@link Bundle} will be returned to the
233      * {@link ConnectionService}.
234      */
235     public static final String EXTRA_INCOMING_CALL_EXTRAS =
236             "android.telecom.extra.INCOMING_CALL_EXTRAS";
237 
238     /**
239      * Optional extra for {@link android.content.Intent#ACTION_CALL} and
240      * {@link android.content.Intent#ACTION_DIAL} {@code Intent} containing a {@link Bundle}
241      * which contains metadata about the call. This {@link Bundle} will be saved into
242      * {@code Call.Details} and passed to the {@link ConnectionService} when placing the call.
243      */
244     public static final String EXTRA_OUTGOING_CALL_EXTRAS =
245             "android.telecom.extra.OUTGOING_CALL_EXTRAS";
246 
247     /**
248      * @hide
249      */
250     public static final String EXTRA_UNKNOWN_CALL_HANDLE =
251             "android.telecom.extra.UNKNOWN_CALL_HANDLE";
252 
253     /**
254      * Optional extra for incoming and outgoing calls containing a long which specifies the time the
255      * call was created. This value is in milliseconds since boot.
256      * @hide
257      */
258     public static final String EXTRA_CALL_CREATED_TIME_MILLIS =
259             "android.telecom.extra.CALL_CREATED_TIME_MILLIS";
260 
261     /**
262      * Optional extra for incoming and outgoing calls containing a long which specifies the time
263      * telecom began routing the call. This value is in milliseconds since boot.
264      * @hide
265      */
266     public static final String EXTRA_CALL_TELECOM_ROUTING_START_TIME_MILLIS =
267             "android.telecom.extra.CALL_TELECOM_ROUTING_START_TIME_MILLIS";
268 
269     /**
270      * Optional extra for incoming and outgoing calls containing a long which specifies the time
271      * telecom finished routing the call. This value is in milliseconds since boot.
272      * @hide
273      */
274     public static final String EXTRA_CALL_TELECOM_ROUTING_END_TIME_MILLIS =
275             "android.telecom.extra.CALL_TELECOM_ROUTING_END_TIME_MILLIS";
276 
277     /**
278      * Optional extra for {@link android.telephony.TelephonyManager#ACTION_PHONE_STATE_CHANGED}
279      * containing the disconnect code.
280      */
281     public static final String EXTRA_CALL_DISCONNECT_CAUSE =
282             "android.telecom.extra.CALL_DISCONNECT_CAUSE";
283 
284     /**
285      * Optional extra for {@link android.telephony.TelephonyManager#ACTION_PHONE_STATE_CHANGED}
286      * containing the disconnect message.
287      */
288     public static final String EXTRA_CALL_DISCONNECT_MESSAGE =
289             "android.telecom.extra.CALL_DISCONNECT_MESSAGE";
290 
291     /**
292      * Optional extra for {@link android.telephony.TelephonyManager#ACTION_PHONE_STATE_CHANGED}
293      * containing the component name of the associated connection service.
294      * @hide
295      */
296     @SystemApi
297     public static final String EXTRA_CONNECTION_SERVICE =
298             "android.telecom.extra.CONNECTION_SERVICE";
299 
300     /**
301      * Optional extra for communicating the call technology used by a
302      * {@link com.android.internal.telephony.Connection} to Telecom
303      * @hide
304      */
305     public static final String EXTRA_CALL_TECHNOLOGY_TYPE =
306             "android.telecom.extra.CALL_TECHNOLOGY_TYPE";
307 
308     /**
309      * An optional {@link android.content.Intent#ACTION_CALL} intent extra denoting the
310      * package name of the app specifying an alternative gateway for the call.
311      * The value is a string.
312      *
313      * (The following comment corresponds to the all GATEWAY_* extras)
314      * An app which sends the {@link android.content.Intent#ACTION_CALL} intent can specify an
315      * alternative address to dial which is different from the one specified and displayed to
316      * the user. This alternative address is referred to as the gateway address.
317      */
318     public static final String GATEWAY_PROVIDER_PACKAGE =
319             "android.telecom.extra.GATEWAY_PROVIDER_PACKAGE";
320 
321     /**
322      * An optional {@link android.content.Intent#ACTION_CALL} intent extra corresponding to the
323      * original address to dial for the call. This is used when an alternative gateway address is
324      * provided to recall the original address.
325      * The value is a {@link android.net.Uri}.
326      *
327      * (See {@link #GATEWAY_PROVIDER_PACKAGE} for details)
328      */
329     public static final String GATEWAY_ORIGINAL_ADDRESS =
330             "android.telecom.extra.GATEWAY_ORIGINAL_ADDRESS";
331 
332     /**
333      * The number which the party on the other side of the line will see (and use to return the
334      * call).
335      * <p>
336      * {@link ConnectionService}s which interact with {@link RemoteConnection}s should only populate
337      * this if the {@link android.telephony.TelephonyManager#getLine1Number()} value, as that is the
338      * user's expected caller ID.
339      */
340     public static final String EXTRA_CALL_BACK_NUMBER = "android.telecom.extra.CALL_BACK_NUMBER";
341 
342     /**
343      * The number of milliseconds that Telecom should wait after disconnecting a call via the
344      * ACTION_NEW_OUTGOING_CALL broadcast, in order to wait for the app which cancelled the call
345      * to make a new one.
346      * @hide
347      */
348     public static final String EXTRA_NEW_OUTGOING_CALL_CANCEL_TIMEOUT =
349             "android.telecom.extra.NEW_OUTGOING_CALL_CANCEL_TIMEOUT";
350 
351     /**
352      * A boolean extra, which when set on the {@link Intent#ACTION_CALL} intent or on the bundle
353      * passed into {@link #placeCall(Uri, Bundle)}, indicates that the call should be initiated with
354      * an RTT session open. See {@link android.telecom.Call.RttCall} for more information on RTT.
355      */
356     public static final String EXTRA_START_CALL_WITH_RTT =
357             "android.telecom.extra.START_CALL_WITH_RTT";
358 
359     /**
360      * A boolean meta-data value indicating whether an {@link InCallService} implements an
361      * in-call user interface. Dialer implementations (see {@link #getDefaultDialerPackage()}) which
362      * would also like to replace the in-call interface should set this meta-data to {@code true} in
363      * the manifest registration of their {@link InCallService}.
364      */
365     public static final String METADATA_IN_CALL_SERVICE_UI = "android.telecom.IN_CALL_SERVICE_UI";
366 
367     /**
368      * A boolean meta-data value indicating whether an {@link InCallService} implements an
369      * in-call user interface to be used while the device is in car-mode (see
370      * {@link android.content.res.Configuration.UI_MODE_TYPE_CAR}).
371      *
372      * @hide
373      */
374     public static final String METADATA_IN_CALL_SERVICE_CAR_MODE_UI =
375             "android.telecom.IN_CALL_SERVICE_CAR_MODE_UI";
376 
377     /**
378      * A boolean meta-data value indicating whether an {@link InCallService} implements ringing.
379      * Dialer implementations (see {@link #getDefaultDialerPackage()}) which would also like to
380      * override the system provided ringing should set this meta-data to {@code true} in the
381      * manifest registration of their {@link InCallService}.
382      */
383     public static final String METADATA_IN_CALL_SERVICE_RINGING =
384             "android.telecom.IN_CALL_SERVICE_RINGING";
385 
386     /**
387      * A boolean meta-data value indicating whether an {@link InCallService} wants to be informed of
388      * calls which have the {@link Call.Details#PROPERTY_IS_EXTERNAL_CALL} property.  An external
389      * call is one which a {@link ConnectionService} knows about, but is not connected to directly.
390      * Dialer implementations (see {@link #getDefaultDialerPackage()}) which would like to be
391      * informed of external calls should set this meta-data to {@code true} in the manifest
392      * registration of their {@link InCallService}.  By default, the {@link InCallService} will NOT
393      * be informed of external calls.
394      */
395     public static final String METADATA_INCLUDE_EXTERNAL_CALLS =
396             "android.telecom.INCLUDE_EXTERNAL_CALLS";
397 
398     /**
399      * A boolean meta-data value indicating whether an {@link InCallService} wants to be informed of
400      * calls which have the {@link Call.Details#PROPERTY_SELF_MANAGED} property.  A self-managed
401      * call is one which originates from a self-managed {@link ConnectionService} which has chosen
402      * to implement its own call user interface.  An {@link InCallService} implementation which
403      * would like to be informed of external calls should set this meta-data to {@code true} in the
404      * manifest registration of their {@link InCallService}.  By default, the {@link InCallService}
405      * will NOT be informed about self-managed calls.
406      * <p>
407      * An {@link InCallService} which receives self-managed calls is free to view and control the
408      * state of calls in the self-managed {@link ConnectionService}.  An example use-case is
409      * exposing these calls to an automotive device via its companion app.
410      * <p>
411      * This meta-data can only be set for an {@link InCallService} which also sets
412      * {@link #METADATA_IN_CALL_SERVICE_UI}. Only the default phone/dialer app, or a car-mode
413      * {@link InCallService} can see self-managed calls.
414      * <p>
415      * See also {@link Connection#PROPERTY_SELF_MANAGED}.
416      */
417     public static final String METADATA_INCLUDE_SELF_MANAGED_CALLS =
418             "android.telecom.INCLUDE_SELF_MANAGED_CALLS";
419 
420     /**
421      * The dual tone multi-frequency signaling character sent to indicate the dialing system should
422      * pause for a predefined period.
423      */
424     public static final char DTMF_CHARACTER_PAUSE = ',';
425 
426     /**
427      * The dual-tone multi-frequency signaling character sent to indicate the dialing system should
428      * wait for user confirmation before proceeding.
429      */
430     public static final char DTMF_CHARACTER_WAIT = ';';
431 
432     /**
433      * TTY (teletypewriter) mode is off.
434      *
435      * @hide
436      */
437     public static final int TTY_MODE_OFF = 0;
438 
439     /**
440      * TTY (teletypewriter) mode is on. The speaker is off and the microphone is muted. The user
441      * will communicate with the remote party by sending and receiving text messages.
442      *
443      * @hide
444      */
445     public static final int TTY_MODE_FULL = 1;
446 
447     /**
448      * TTY (teletypewriter) mode is in hearing carryover mode (HCO). The microphone is muted but the
449      * speaker is on. The user will communicate with the remote party by sending text messages and
450      * hearing an audible reply.
451      *
452      * @hide
453      */
454     public static final int TTY_MODE_HCO = 2;
455 
456     /**
457      * TTY (teletypewriter) mode is in voice carryover mode (VCO). The speaker is off but the
458      * microphone is still on. User will communicate with the remote party by speaking and receiving
459      * text message replies.
460      *
461      * @hide
462      */
463     public static final int TTY_MODE_VCO = 3;
464 
465     /**
466      * Broadcast intent action indicating that the current TTY mode has changed. An intent extra
467      * provides this state as an int.
468      *
469      * @see #EXTRA_CURRENT_TTY_MODE
470      * @hide
471      */
472     public static final String ACTION_CURRENT_TTY_MODE_CHANGED =
473             "android.telecom.action.CURRENT_TTY_MODE_CHANGED";
474 
475     /**
476      * The lookup key for an int that indicates the current TTY mode.
477      * Valid modes are:
478      * - {@link #TTY_MODE_OFF}
479      * - {@link #TTY_MODE_FULL}
480      * - {@link #TTY_MODE_HCO}
481      * - {@link #TTY_MODE_VCO}
482      *
483      * @hide
484      */
485     public static final String EXTRA_CURRENT_TTY_MODE =
486             "android.telecom.intent.extra.CURRENT_TTY_MODE";
487 
488     /**
489      * Broadcast intent action indicating that the TTY preferred operating mode has changed. An
490      * intent extra provides the new mode as an int.
491      *
492      * @see #EXTRA_TTY_PREFERRED_MODE
493      * @hide
494      */
495     public static final String ACTION_TTY_PREFERRED_MODE_CHANGED =
496             "android.telecom.action.TTY_PREFERRED_MODE_CHANGED";
497 
498     /**
499      * The lookup key for an int that indicates preferred TTY mode. Valid modes are: -
500      * {@link #TTY_MODE_OFF} - {@link #TTY_MODE_FULL} - {@link #TTY_MODE_HCO} -
501      * {@link #TTY_MODE_VCO}
502      *
503      * @hide
504      */
505     public static final String EXTRA_TTY_PREFERRED_MODE =
506             "android.telecom.intent.extra.TTY_PREFERRED";
507 
508     /**
509      * Broadcast intent action for letting custom component know to show the missed call
510      * notification. If no custom component exists then this is sent to the default dialer which
511      * should post a missed-call notification.
512      */
513     public static final String ACTION_SHOW_MISSED_CALLS_NOTIFICATION =
514             "android.telecom.action.SHOW_MISSED_CALLS_NOTIFICATION";
515 
516     /**
517      * The number of calls associated with the notification. If the number is zero then the missed
518      * call notification should be dismissed.
519      */
520     public static final String EXTRA_NOTIFICATION_COUNT =
521             "android.telecom.extra.NOTIFICATION_COUNT";
522 
523     /**
524      * The number associated with the missed calls. This number is only relevant
525      * when EXTRA_NOTIFICATION_COUNT is 1.
526      */
527     public static final String EXTRA_NOTIFICATION_PHONE_NUMBER =
528             "android.telecom.extra.NOTIFICATION_PHONE_NUMBER";
529 
530     /**
531      * The intent to clear missed calls.
532      * @hide
533      */
534     @SystemApi
535     public static final String EXTRA_CLEAR_MISSED_CALLS_INTENT =
536             "android.telecom.extra.CLEAR_MISSED_CALLS_INTENT";
537 
538     /**
539      * The intent to call back a missed call.
540      * @hide
541      */
542     @SystemApi
543     public static final String EXTRA_CALL_BACK_INTENT =
544             "android.telecom.extra.CALL_BACK_INTENT";
545 
546     /**
547      * The following 4 constants define how properties such as phone numbers and names are
548      * displayed to the user.
549      */
550 
551     /**
552      * Indicates that the address or number of a call is allowed to be displayed for caller ID.
553     */
554     public static final int PRESENTATION_ALLOWED = 1;
555 
556     /**
557      * Indicates that the address or number of a call is blocked by the other party.
558      */
559     public static final int PRESENTATION_RESTRICTED = 2;
560 
561     /**
562      * Indicates that the address or number of a call is not specified or known by the carrier.
563      */
564     public static final int PRESENTATION_UNKNOWN = 3;
565 
566     /**
567      * Indicates that the address or number of a call belongs to a pay phone.
568      */
569     public static final int PRESENTATION_PAYPHONE = 4;
570 
571     private static final String TAG = "TelecomManager";
572 
573     private final Context mContext;
574 
575     private final ITelecomService mTelecomServiceOverride;
576 
577     /**
578      * @hide
579      */
from(Context context)580     public static TelecomManager from(Context context) {
581         return (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
582     }
583 
584     /**
585      * @hide
586      */
TelecomManager(Context context)587     public TelecomManager(Context context) {
588         this(context, null);
589     }
590 
591     /**
592      * @hide
593      */
TelecomManager(Context context, ITelecomService telecomServiceImpl)594     public TelecomManager(Context context, ITelecomService telecomServiceImpl) {
595         Context appContext = context.getApplicationContext();
596         if (appContext != null) {
597             mContext = appContext;
598         } else {
599             mContext = context;
600         }
601         mTelecomServiceOverride = telecomServiceImpl;
602         android.telecom.Log.initMd5Sum();
603     }
604 
605     /**
606      * Return the {@link PhoneAccount} which will be used to place outgoing calls to addresses with
607      * the specified {@code uriScheme}. This {@link PhoneAccount} will always be a member of the
608      * list which is returned from invoking {@link #getCallCapablePhoneAccounts()}. The specific
609      * account returned depends on the following priorities:
610      * <ul>
611      * <li> If the user-selected default {@link PhoneAccount} supports the specified scheme, it will
612      * be returned.
613      * </li>
614      * <li> If there exists only one {@link PhoneAccount} that supports the specified scheme, it
615      * will be returned.
616      * </li>
617      * </ul>
618      * <p>
619      * If no {@link PhoneAccount} fits the criteria above, this method will return {@code null}.
620      *
621      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
622      *
623      * @param uriScheme The URI scheme.
624      * @return The {@link PhoneAccountHandle} corresponding to the account to be used.
625      */
626     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getDefaultOutgoingPhoneAccount(String uriScheme)627     public PhoneAccountHandle getDefaultOutgoingPhoneAccount(String uriScheme) {
628         try {
629             if (isServiceConnected()) {
630                 return getTelecomService().getDefaultOutgoingPhoneAccount(uriScheme,
631                         mContext.getOpPackageName());
632             }
633         } catch (RemoteException e) {
634             Log.e(TAG, "Error calling ITelecomService#getDefaultOutgoingPhoneAccount", e);
635         }
636         return null;
637     }
638 
639     /**
640      * Return the {@link PhoneAccount} which is the user-chosen default for making outgoing phone
641      * calls. This {@code PhoneAccount} will always be a member of the list which is returned from
642      * calling {@link #getCallCapablePhoneAccounts()}
643      * <p>
644      * Apps must be prepared for this method to return {@code null}, indicating that there currently
645      * exists no user-chosen default {@code PhoneAccount}.
646      *
647      * @return The user outgoing phone account selected by the user.
648      * @hide
649      */
getUserSelectedOutgoingPhoneAccount()650     public PhoneAccountHandle getUserSelectedOutgoingPhoneAccount() {
651         try {
652             if (isServiceConnected()) {
653                 return getTelecomService().getUserSelectedOutgoingPhoneAccount();
654             }
655         } catch (RemoteException e) {
656             Log.e(TAG, "Error calling ITelecomService#getUserSelectedOutgoingPhoneAccount", e);
657         }
658         return null;
659     }
660 
661     /**
662      * Sets the user-chosen default for making outgoing phone calls.
663      * @hide
664      */
setUserSelectedOutgoingPhoneAccount(PhoneAccountHandle accountHandle)665     public void setUserSelectedOutgoingPhoneAccount(PhoneAccountHandle accountHandle) {
666         try {
667             if (isServiceConnected()) {
668                 getTelecomService().setUserSelectedOutgoingPhoneAccount(accountHandle);
669             }
670         } catch (RemoteException e) {
671             Log.e(TAG, "Error calling ITelecomService#setUserSelectedOutgoingPhoneAccount");
672         }
673     }
674 
675     /**
676      * Returns the current SIM call manager. Apps must be prepared for this method to return
677      * {@code null}, indicating that there currently exists no user-chosen default
678      * {@code PhoneAccount}.
679      *
680      * @return The phone account handle of the current sim call manager.
681      */
getSimCallManager()682     public PhoneAccountHandle getSimCallManager() {
683         try {
684             if (isServiceConnected()) {
685                 return getTelecomService().getSimCallManager();
686             }
687         } catch (RemoteException e) {
688             Log.e(TAG, "Error calling ITelecomService#getSimCallManager");
689         }
690         return null;
691     }
692 
693     /**
694      * Returns the current SIM call manager for the specified user. Apps must be prepared for this
695      * method to return {@code null}, indicating that there currently exists no user-chosen default
696      * {@code PhoneAccount}.
697      *
698      * @return The phone account handle of the current sim call manager.
699      *
700      * @hide
701      */
getSimCallManager(int userId)702     public PhoneAccountHandle getSimCallManager(int userId) {
703         try {
704             if (isServiceConnected()) {
705                 return getTelecomService().getSimCallManagerForUser(userId);
706             }
707         } catch (RemoteException e) {
708             Log.e(TAG, "Error calling ITelecomService#getSimCallManagerForUser");
709         }
710         return null;
711     }
712 
713     /**
714      * Returns the current connection manager. Apps must be prepared for this method to return
715      * {@code null}, indicating that there currently exists no user-chosen default
716      * {@code PhoneAccount}.
717      *
718      * @return The phone account handle of the current connection manager.
719      * @hide
720      */
721     @SystemApi
getConnectionManager()722     public PhoneAccountHandle getConnectionManager() {
723         return getSimCallManager();
724     }
725 
726     /**
727      * Returns a list of the {@link PhoneAccountHandle}s which can be used to make and receive phone
728      * calls which support the specified URI scheme.
729      * <P>
730      * For example, invoking with {@code "tel"} will find all {@link PhoneAccountHandle}s which
731      * support telephone calls (e.g. URIs such as {@code tel:555-555-1212}).  Invoking with
732      * {@code "sip"} will find all {@link PhoneAccountHandle}s which support SIP calls (e.g. URIs
733      * such as {@code sip:example@sipexample.com}).
734      *
735      * @param uriScheme The URI scheme.
736      * @return A list of {@code PhoneAccountHandle} objects supporting the URI scheme.
737      * @hide
738      */
739     @SystemApi
740     @RequiresPermission(anyOf = {
741             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
742             android.Manifest.permission.READ_PHONE_STATE
743     })
getPhoneAccountsSupportingScheme(String uriScheme)744     public List<PhoneAccountHandle> getPhoneAccountsSupportingScheme(String uriScheme) {
745         try {
746             if (isServiceConnected()) {
747                 return getTelecomService().getPhoneAccountsSupportingScheme(uriScheme,
748                         mContext.getOpPackageName());
749             }
750         } catch (RemoteException e) {
751             Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsSupportingScheme", e);
752         }
753         return new ArrayList<>();
754     }
755 
756 
757     /**
758      * Returns a list of {@link PhoneAccountHandle}s which can be used to make and receive phone
759      * calls. The returned list includes only those accounts which have been explicitly enabled
760      * by the user.
761      *
762      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
763      *
764      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
765      * @return A list of {@code PhoneAccountHandle} objects.
766      */
767     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCallCapablePhoneAccounts()768     public List<PhoneAccountHandle> getCallCapablePhoneAccounts() {
769         return getCallCapablePhoneAccounts(false);
770     }
771 
772     /**
773      * Returns a list of {@link PhoneAccountHandle}s for self-managed {@link ConnectionService}s.
774      * <p>
775      * Self-Managed {@link ConnectionService}s have a {@link PhoneAccount} with
776      * {@link PhoneAccount#CAPABILITY_SELF_MANAGED}.
777      * <p>
778      * Requires permission {@link android.Manifest.permission#READ_PHONE_STATE}, or that the caller
779      * is the default dialer app.
780      * <p>
781      * A {@link SecurityException} will be thrown if a called is not the default dialer, or lacks
782      * the {@link android.Manifest.permission#READ_PHONE_STATE} permission.
783      *
784      * @return A list of {@code PhoneAccountHandle} objects.
785      */
786     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getSelfManagedPhoneAccounts()787     public List<PhoneAccountHandle> getSelfManagedPhoneAccounts() {
788         try {
789             if (isServiceConnected()) {
790                 return getTelecomService().getSelfManagedPhoneAccounts(mContext.getOpPackageName());
791             }
792         } catch (RemoteException e) {
793             Log.e(TAG, "Error calling ITelecomService#getSelfManagedPhoneAccounts()", e);
794         }
795         return new ArrayList<>();
796     }
797 
798     /**
799      * Returns a list of {@link PhoneAccountHandle}s including those which have not been enabled
800      * by the user.
801      *
802      * @return A list of {@code PhoneAccountHandle} objects.
803      * @hide
804      */
getCallCapablePhoneAccounts(boolean includeDisabledAccounts)805     public List<PhoneAccountHandle> getCallCapablePhoneAccounts(boolean includeDisabledAccounts) {
806         try {
807             if (isServiceConnected()) {
808                 return getTelecomService().getCallCapablePhoneAccounts(
809                         includeDisabledAccounts, mContext.getOpPackageName());
810             }
811         } catch (RemoteException e) {
812             Log.e(TAG, "Error calling ITelecomService#getCallCapablePhoneAccounts(" +
813                     includeDisabledAccounts + ")", e);
814         }
815         return new ArrayList<>();
816     }
817 
818     /**
819      *  Returns a list of all {@link PhoneAccount}s registered for the calling package.
820      *
821      * @return A list of {@code PhoneAccountHandle} objects.
822      * @hide
823      */
824     @SystemApi
825     @SuppressLint("Doclava125")
getPhoneAccountsForPackage()826     public List<PhoneAccountHandle> getPhoneAccountsForPackage() {
827         try {
828             if (isServiceConnected()) {
829                 return getTelecomService().getPhoneAccountsForPackage(mContext.getPackageName());
830             }
831         } catch (RemoteException e) {
832             Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsForPackage", e);
833         }
834         return null;
835     }
836 
837     /**
838      * Return the {@link PhoneAccount} for a specified {@link PhoneAccountHandle}. Object includes
839      * resources which can be used in a user interface.
840      *
841      * @param account The {@link PhoneAccountHandle}.
842      * @return The {@link PhoneAccount} object.
843      */
getPhoneAccount(PhoneAccountHandle account)844     public PhoneAccount getPhoneAccount(PhoneAccountHandle account) {
845         try {
846             if (isServiceConnected()) {
847                 return getTelecomService().getPhoneAccount(account);
848             }
849         } catch (RemoteException e) {
850             Log.e(TAG, "Error calling ITelecomService#getPhoneAccount", e);
851         }
852         return null;
853     }
854 
855     /**
856      * Returns a count of all {@link PhoneAccount}s.
857      *
858      * @return The count of {@link PhoneAccount}s.
859      * @hide
860      */
861     @SystemApi
getAllPhoneAccountsCount()862     public int getAllPhoneAccountsCount() {
863         try {
864             if (isServiceConnected()) {
865                 return getTelecomService().getAllPhoneAccountsCount();
866             }
867         } catch (RemoteException e) {
868             Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccountsCount", e);
869         }
870         return 0;
871     }
872 
873     /**
874      * Returns a list of all {@link PhoneAccount}s.
875      *
876      * @return All {@link PhoneAccount}s.
877      * @hide
878      */
879     @SystemApi
getAllPhoneAccounts()880     public List<PhoneAccount> getAllPhoneAccounts() {
881         try {
882             if (isServiceConnected()) {
883                 return getTelecomService().getAllPhoneAccounts();
884             }
885         } catch (RemoteException e) {
886             Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccounts", e);
887         }
888         return Collections.EMPTY_LIST;
889     }
890 
891     /**
892      * Returns a list of all {@link PhoneAccountHandle}s.
893      *
894      * @return All {@link PhoneAccountHandle}s.
895      * @hide
896      */
897     @SystemApi
getAllPhoneAccountHandles()898     public List<PhoneAccountHandle> getAllPhoneAccountHandles() {
899         try {
900             if (isServiceConnected()) {
901                 return getTelecomService().getAllPhoneAccountHandles();
902             }
903         } catch (RemoteException e) {
904             Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccountHandles", e);
905         }
906         return Collections.EMPTY_LIST;
907     }
908 
909     /**
910      * Register a {@link PhoneAccount} for use by the system that will be stored in Device Encrypted
911      * storage. When registering {@link PhoneAccount}s, existing registrations will be overwritten
912      * if the {@link PhoneAccountHandle} matches that of a {@link PhoneAccount} which is already
913      * registered. Once registered, the {@link PhoneAccount} is listed to the user as an option
914      * when placing calls. The user may still need to enable the {@link PhoneAccount} within
915      * the phone app settings before the account is usable.
916      * <p>
917      * A {@link SecurityException} will be thrown if an app tries to register a
918      * {@link PhoneAccountHandle} where the package name specified within
919      * {@link PhoneAccountHandle#getComponentName()} does not match the package name of the app.
920      *
921      * @param account The complete {@link PhoneAccount}.
922      */
registerPhoneAccount(PhoneAccount account)923     public void registerPhoneAccount(PhoneAccount account) {
924         try {
925             if (isServiceConnected()) {
926                 getTelecomService().registerPhoneAccount(account);
927             }
928         } catch (RemoteException e) {
929             Log.e(TAG, "Error calling ITelecomService#registerPhoneAccount", e);
930         }
931     }
932 
933     /**
934      * Remove a {@link PhoneAccount} registration from the system.
935      *
936      * @param accountHandle A {@link PhoneAccountHandle} for the {@link PhoneAccount} to unregister.
937      */
unregisterPhoneAccount(PhoneAccountHandle accountHandle)938     public void unregisterPhoneAccount(PhoneAccountHandle accountHandle) {
939         try {
940             if (isServiceConnected()) {
941                 getTelecomService().unregisterPhoneAccount(accountHandle);
942             }
943         } catch (RemoteException e) {
944             Log.e(TAG, "Error calling ITelecomService#unregisterPhoneAccount", e);
945         }
946     }
947 
948     /**
949      * Remove all Accounts that belong to the calling package from the system.
950      * @hide
951      */
952     @SystemApi
953     @SuppressLint("Doclava125")
clearPhoneAccounts()954     public void clearPhoneAccounts() {
955         clearAccounts();
956     }
957     /**
958      * Remove all Accounts that belong to the calling package from the system.
959      * @deprecated Use {@link #clearPhoneAccounts()} instead.
960      * @hide
961      */
962     @SystemApi
963     @SuppressLint("Doclava125")
clearAccounts()964     public void clearAccounts() {
965         try {
966             if (isServiceConnected()) {
967                 getTelecomService().clearAccounts(mContext.getPackageName());
968             }
969         } catch (RemoteException e) {
970             Log.e(TAG, "Error calling ITelecomService#clearAccounts", e);
971         }
972     }
973 
974     /**
975      * Remove all Accounts that belong to the specified package from the system.
976      * @hide
977      */
clearAccountsForPackage(String packageName)978     public void clearAccountsForPackage(String packageName) {
979         try {
980             if (isServiceConnected() && !TextUtils.isEmpty(packageName)) {
981                 getTelecomService().clearAccounts(packageName);
982             }
983         } catch (RemoteException e) {
984             Log.e(TAG, "Error calling ITelecomService#clearAccountsForPackage", e);
985         }
986     }
987 
988 
989     /**
990      * @deprecated - Use {@link TelecomManager#getDefaultDialerPackage} to directly access
991      *         the default dialer's package name instead.
992      * @hide
993      */
994     @SystemApi
995     @SuppressLint("Doclava125")
getDefaultPhoneApp()996     public ComponentName getDefaultPhoneApp() {
997         try {
998             if (isServiceConnected()) {
999                 return getTelecomService().getDefaultPhoneApp();
1000             }
1001         } catch (RemoteException e) {
1002             Log.e(TAG, "RemoteException attempting to get the default phone app.", e);
1003         }
1004         return null;
1005     }
1006 
1007     /**
1008      * Used to determine the currently selected default dialer package.
1009      *
1010      * @return package name for the default dialer package or null if no package has been
1011      *         selected as the default dialer.
1012      */
getDefaultDialerPackage()1013     public String getDefaultDialerPackage() {
1014         try {
1015             if (isServiceConnected()) {
1016                 return getTelecomService().getDefaultDialerPackage();
1017             }
1018         } catch (RemoteException e) {
1019             Log.e(TAG, "RemoteException attempting to get the default dialer package name.", e);
1020         }
1021         return null;
1022     }
1023 
1024     /**
1025      * Used to set the default dialer package.
1026      *
1027      * @param packageName to set the default dialer to..
1028      *
1029      * @result {@code true} if the default dialer was successfully changed, {@code false} if
1030      *         the specified package does not correspond to an installed dialer, or is already
1031      *         the default dialer.
1032      *
1033      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE}
1034      * Requires permission: {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
1035      *
1036      * @hide
1037      */
setDefaultDialer(String packageName)1038     public boolean setDefaultDialer(String packageName) {
1039         try {
1040             if (isServiceConnected()) {
1041                 return getTelecomService().setDefaultDialer(packageName);
1042             }
1043         } catch (RemoteException e) {
1044             Log.e(TAG, "RemoteException attempting to set the default dialer.", e);
1045         }
1046         return false;
1047     }
1048 
1049     /**
1050      * Used to determine the dialer package that is preloaded on the system partition.
1051      *
1052      * @return package name for the system dialer package or null if no system dialer is preloaded.
1053      * @hide
1054      */
getSystemDialerPackage()1055     public String getSystemDialerPackage() {
1056         try {
1057             if (isServiceConnected()) {
1058                 return getTelecomService().getSystemDialerPackage();
1059             }
1060         } catch (RemoteException e) {
1061             Log.e(TAG, "RemoteException attempting to get the system dialer package name.", e);
1062         }
1063         return null;
1064     }
1065 
1066     /**
1067      * Return whether a given phone number is the configured voicemail number for a
1068      * particular phone account.
1069      *
1070      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
1071      *
1072      * @param accountHandle The handle for the account to check the voicemail number against
1073      * @param number The number to look up.
1074      */
1075     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isVoiceMailNumber(PhoneAccountHandle accountHandle, String number)1076     public boolean isVoiceMailNumber(PhoneAccountHandle accountHandle, String number) {
1077         try {
1078             if (isServiceConnected()) {
1079                 return getTelecomService().isVoiceMailNumber(accountHandle, number,
1080                         mContext.getOpPackageName());
1081             }
1082         } catch (RemoteException e) {
1083             Log.e(TAG, "RemoteException calling ITelecomService#isVoiceMailNumber.", e);
1084         }
1085         return false;
1086     }
1087 
1088     /**
1089      * Return the voicemail number for a given phone account.
1090      *
1091      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
1092      *
1093      * @param accountHandle The handle for the phone account.
1094      * @return The voicemail number for the phone account, and {@code null} if one has not been
1095      *         configured.
1096      */
1097     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailNumber(PhoneAccountHandle accountHandle)1098     public String getVoiceMailNumber(PhoneAccountHandle accountHandle) {
1099         try {
1100             if (isServiceConnected()) {
1101                 return getTelecomService().getVoiceMailNumber(accountHandle,
1102                         mContext.getOpPackageName());
1103             }
1104         } catch (RemoteException e) {
1105             Log.e(TAG, "RemoteException calling ITelecomService#hasVoiceMailNumber.", e);
1106         }
1107         return null;
1108     }
1109 
1110     /**
1111      * Return the line 1 phone number for given phone account.
1112      *
1113      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
1114      *
1115      * @param accountHandle The handle for the account retrieve a number for.
1116      * @return A string representation of the line 1 phone number.
1117      */
1118     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1Number(PhoneAccountHandle accountHandle)1119     public String getLine1Number(PhoneAccountHandle accountHandle) {
1120         try {
1121             if (isServiceConnected()) {
1122                 return getTelecomService().getLine1Number(accountHandle,
1123                         mContext.getOpPackageName());
1124             }
1125         } catch (RemoteException e) {
1126             Log.e(TAG, "RemoteException calling ITelecomService#getLine1Number.", e);
1127         }
1128         return null;
1129     }
1130 
1131     /**
1132      * Returns whether there is an ongoing phone call (can be in dialing, ringing, active or holding
1133      * states) originating from either a manager or self-managed {@link ConnectionService}.
1134      * <p>
1135      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
1136      *
1137      * @return {@code true} if there is an ongoing call in either a managed or self-managed
1138      *      {@link ConnectionService}, {@code false} otherwise.
1139      */
1140     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isInCall()1141     public boolean isInCall() {
1142         try {
1143             if (isServiceConnected()) {
1144                 return getTelecomService().isInCall(mContext.getOpPackageName());
1145             }
1146         } catch (RemoteException e) {
1147             Log.e(TAG, "RemoteException calling isInCall().", e);
1148         }
1149         return false;
1150     }
1151 
1152     /**
1153      * Returns whether there is an ongoing call originating from a managed
1154      * {@link ConnectionService}.  An ongoing call can be in dialing, ringing, active or holding
1155      * states.
1156      * <p>
1157      * If you also need to know if there are ongoing self-managed calls, use {@link #isInCall()}
1158      * instead.
1159      * <p>
1160      * Requires permission: {@link android.Manifest.permission#READ_PHONE_STATE}
1161      *
1162      * @return {@code true} if there is an ongoing call in a managed {@link ConnectionService},
1163      *      {@code false} otherwise.
1164      */
1165     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isInManagedCall()1166     public boolean isInManagedCall() {
1167         try {
1168             if (isServiceConnected()) {
1169                 return getTelecomService().isInManagedCall(mContext.getOpPackageName());
1170             }
1171         } catch (RemoteException e) {
1172             Log.e(TAG, "RemoteException calling isInManagedCall().", e);
1173         }
1174         return false;
1175     }
1176 
1177     /**
1178      * Returns one of the following constants that represents the current state of Telecom:
1179      *
1180      * {@link TelephonyManager#CALL_STATE_RINGING}
1181      * {@link TelephonyManager#CALL_STATE_OFFHOOK}
1182      * {@link TelephonyManager#CALL_STATE_IDLE}
1183      *
1184      * Note that this API does not require the
1185      * {@link android.Manifest.permission#READ_PHONE_STATE} permission. This is intentional, to
1186      * preserve the behavior of {@link TelephonyManager#getCallState()}, which also did not require
1187      * the permission.
1188      *
1189      * Takes into consideration both managed and self-managed calls.
1190      *
1191      * @hide
1192      */
1193     @SystemApi
getCallState()1194     public int getCallState() {
1195         try {
1196             if (isServiceConnected()) {
1197                 return getTelecomService().getCallState();
1198             }
1199         } catch (RemoteException e) {
1200             Log.d(TAG, "RemoteException calling getCallState().", e);
1201         }
1202         return TelephonyManager.CALL_STATE_IDLE;
1203     }
1204 
1205     /**
1206      * Returns whether there currently exists is a ringing incoming-call.
1207      *
1208      * @return {@code true} if there is a managed or self-managed ringing call.
1209      * @hide
1210      */
1211     @SystemApi
1212     @RequiresPermission(anyOf = {
1213             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1214             android.Manifest.permission.READ_PHONE_STATE
1215     })
isRinging()1216     public boolean isRinging() {
1217         try {
1218             if (isServiceConnected()) {
1219                 return getTelecomService().isRinging(mContext.getOpPackageName());
1220             }
1221         } catch (RemoteException e) {
1222             Log.e(TAG, "RemoteException attempting to get ringing state of phone app.", e);
1223         }
1224         return false;
1225     }
1226 
1227     /**
1228      * Ends an ongoing call.
1229      * TODO: L-release - need to convert all invocations of ITelecomService#endCall to use this
1230      * method (clockwork & gearhead).
1231      * @hide
1232      */
1233     @SystemApi
1234     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
endCall()1235     public boolean endCall() {
1236         try {
1237             if (isServiceConnected()) {
1238                 return getTelecomService().endCall();
1239             }
1240         } catch (RemoteException e) {
1241             Log.e(TAG, "Error calling ITelecomService#endCall", e);
1242         }
1243         return false;
1244     }
1245 
1246     /**
1247      * If there is a ringing incoming call, this method accepts the call on behalf of the user.
1248      *
1249      * If the incoming call is a video call, the call will be answered with the same video state as
1250      * the incoming call requests.  This means, for example, that an incoming call requesting
1251      * {@link VideoProfile#STATE_BIDIRECTIONAL} will be answered, accepting that state.
1252      *
1253      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
1254      * {@link android.Manifest.permission#ANSWER_PHONE_CALLS}
1255      */
1256     //TODO: L-release - need to convert all invocation of ITelecmmService#answerRingingCall to use
1257     // this method (clockwork & gearhead).
1258     @RequiresPermission(anyOf =
1259             {Manifest.permission.ANSWER_PHONE_CALLS, Manifest.permission.MODIFY_PHONE_STATE})
acceptRingingCall()1260     public void acceptRingingCall() {
1261         try {
1262             if (isServiceConnected()) {
1263                 getTelecomService().acceptRingingCall(mContext.getPackageName());
1264             }
1265         } catch (RemoteException e) {
1266             Log.e(TAG, "Error calling ITelecomService#acceptRingingCall", e);
1267         }
1268     }
1269 
1270     /**
1271      * If there is a ringing incoming call, this method accepts the call on behalf of the user,
1272      * with the specified video state.
1273      *
1274      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
1275      * {@link android.Manifest.permission#ANSWER_PHONE_CALLS}
1276      *
1277      * @param videoState The desired video state to answer the call with.
1278      */
1279     @RequiresPermission(anyOf =
1280             {Manifest.permission.ANSWER_PHONE_CALLS, Manifest.permission.MODIFY_PHONE_STATE})
acceptRingingCall(int videoState)1281     public void acceptRingingCall(int videoState) {
1282         try {
1283             if (isServiceConnected()) {
1284                 getTelecomService().acceptRingingCallWithVideoState(
1285                         mContext.getPackageName(), videoState);
1286             }
1287         } catch (RemoteException e) {
1288             Log.e(TAG, "Error calling ITelecomService#acceptRingingCallWithVideoState", e);
1289         }
1290     }
1291 
1292     /**
1293      * Silences the ringer if a ringing call exists.
1294      *
1295      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE}
1296      */
1297     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
silenceRinger()1298     public void silenceRinger() {
1299         try {
1300             if (isServiceConnected()) {
1301                 getTelecomService().silenceRinger(mContext.getOpPackageName());
1302             }
1303         } catch (RemoteException e) {
1304             Log.e(TAG, "Error calling ITelecomService#silenceRinger", e);
1305         }
1306     }
1307 
1308     /**
1309      * Returns whether TTY is supported on this device.
1310      *
1311      * @hide
1312      */
1313     @SystemApi
1314     @RequiresPermission(anyOf = {
1315             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
1316             android.Manifest.permission.READ_PHONE_STATE
1317     })
isTtySupported()1318     public boolean isTtySupported() {
1319         try {
1320             if (isServiceConnected()) {
1321                 return getTelecomService().isTtySupported(mContext.getOpPackageName());
1322             }
1323         } catch (RemoteException e) {
1324             Log.e(TAG, "RemoteException attempting to get TTY supported state.", e);
1325         }
1326         return false;
1327     }
1328 
1329     /**
1330      * Returns the current TTY mode of the device. For TTY to be on the user must enable it in
1331      * settings and have a wired headset plugged in.
1332      * Valid modes are:
1333      * - {@link TelecomManager#TTY_MODE_OFF}
1334      * - {@link TelecomManager#TTY_MODE_FULL}
1335      * - {@link TelecomManager#TTY_MODE_HCO}
1336      * - {@link TelecomManager#TTY_MODE_VCO}
1337      * @hide
1338      */
getCurrentTtyMode()1339     public int getCurrentTtyMode() {
1340         try {
1341             if (isServiceConnected()) {
1342                 return getTelecomService().getCurrentTtyMode(mContext.getOpPackageName());
1343             }
1344         } catch (RemoteException e) {
1345             Log.e(TAG, "RemoteException attempting to get the current TTY mode.", e);
1346         }
1347         return TTY_MODE_OFF;
1348     }
1349 
1350     /**
1351      * Registers a new incoming call. A {@link ConnectionService} should invoke this method when it
1352      * has an incoming call. For managed {@link ConnectionService}s, the specified
1353      * {@link PhoneAccountHandle} must have been registered with {@link #registerPhoneAccount} and
1354      * the user must have enabled the corresponding {@link PhoneAccount}.  This can be checked using
1355      * {@link #getPhoneAccount}. Self-managed {@link ConnectionService}s must have
1356      * {@link android.Manifest.permission#MANAGE_OWN_CALLS} to add a new incoming call.
1357      * <p>
1358      * The incoming call you are adding is assumed to have a video state of
1359      * {@link VideoProfile#STATE_AUDIO_ONLY}, unless the extra value
1360      * {@link #EXTRA_INCOMING_VIDEO_STATE} is specified.
1361      * <p>
1362      * Once invoked, this method will cause the system to bind to the {@link ConnectionService}
1363      * associated with the {@link PhoneAccountHandle} and request additional information about the
1364      * call (See {@link ConnectionService#onCreateIncomingConnection}) before starting the incoming
1365      * call UI.
1366      * <p>
1367      * For a managed {@link ConnectionService}, a {@link SecurityException} will be thrown if either
1368      * the {@link PhoneAccountHandle} does not correspond to a registered {@link PhoneAccount} or
1369      * the associated {@link PhoneAccount} is not currently enabled by the user.
1370      * <p>
1371      * For a self-managed {@link ConnectionService}, a {@link SecurityException} will be thrown if
1372      * the {@link PhoneAccount} has {@link PhoneAccount#CAPABILITY_SELF_MANAGED} and the calling app
1373      * does not have {@link android.Manifest.permission#MANAGE_OWN_CALLS}.
1374      *
1375      * @param phoneAccount A {@link PhoneAccountHandle} registered with
1376      *            {@link #registerPhoneAccount}.
1377      * @param extras A bundle that will be passed through to
1378      *            {@link ConnectionService#onCreateIncomingConnection}.
1379      */
addNewIncomingCall(PhoneAccountHandle phoneAccount, Bundle extras)1380     public void addNewIncomingCall(PhoneAccountHandle phoneAccount, Bundle extras) {
1381         try {
1382             if (isServiceConnected()) {
1383                 getTelecomService().addNewIncomingCall(
1384                         phoneAccount, extras == null ? new Bundle() : extras);
1385             }
1386         } catch (RemoteException e) {
1387             Log.e(TAG, "RemoteException adding a new incoming call: " + phoneAccount, e);
1388         }
1389     }
1390 
1391     /**
1392      * Registers a new unknown call with Telecom. This can only be called by the system Telephony
1393      * service. This is invoked when Telephony detects a new unknown connection that was neither
1394      * a new incoming call, nor an user-initiated outgoing call.
1395      *
1396      * @param phoneAccount A {@link PhoneAccountHandle} registered with
1397      *            {@link #registerPhoneAccount}.
1398      * @param extras A bundle that will be passed through to
1399      *            {@link ConnectionService#onCreateIncomingConnection}.
1400      * @hide
1401      */
1402     @SystemApi
addNewUnknownCall(PhoneAccountHandle phoneAccount, Bundle extras)1403     public void addNewUnknownCall(PhoneAccountHandle phoneAccount, Bundle extras) {
1404         try {
1405             if (isServiceConnected()) {
1406                 getTelecomService().addNewUnknownCall(
1407                         phoneAccount, extras == null ? new Bundle() : extras);
1408             }
1409         } catch (RemoteException e) {
1410             Log.e(TAG, "RemoteException adding a new unknown call: " + phoneAccount, e);
1411         }
1412     }
1413 
1414     /**
1415      * Processes the specified dial string as an MMI code.
1416      * MMI codes are any sequence of characters entered into the dialpad that contain a "*" or "#".
1417      * Some of these sequences launch special behavior through handled by Telephony.
1418      * This method uses the default subscription.
1419      * <p>
1420      * Requires that the method-caller be set as the system dialer app.
1421      * </p>
1422      *
1423      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE}
1424      *
1425      * @param dialString The digits to dial.
1426      * @return True if the digits were processed as an MMI code, false otherwise.
1427      */
1428     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handleMmi(String dialString)1429     public boolean handleMmi(String dialString) {
1430         ITelecomService service = getTelecomService();
1431         if (service != null) {
1432             try {
1433                 return service.handlePinMmi(dialString, mContext.getOpPackageName());
1434             } catch (RemoteException e) {
1435                 Log.e(TAG, "Error calling ITelecomService#handlePinMmi", e);
1436             }
1437         }
1438         return false;
1439     }
1440 
1441     /**
1442      * Processes the specified dial string as an MMI code.
1443      * MMI codes are any sequence of characters entered into the dialpad that contain a "*" or "#".
1444      * Some of these sequences launch special behavior through handled by Telephony.
1445      * <p>
1446      * Requires that the method-caller be set as the system dialer app.
1447      * </p>
1448      *
1449      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE}
1450      *
1451      * @param accountHandle The handle for the account the MMI code should apply to.
1452      * @param dialString The digits to dial.
1453      * @return True if the digits were processed as an MMI code, false otherwise.
1454      */
1455     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handleMmi(String dialString, PhoneAccountHandle accountHandle)1456     public boolean handleMmi(String dialString, PhoneAccountHandle accountHandle) {
1457         ITelecomService service = getTelecomService();
1458         if (service != null) {
1459             try {
1460                 return service.handlePinMmiForPhoneAccount(accountHandle, dialString,
1461                         mContext.getOpPackageName());
1462             } catch (RemoteException e) {
1463                 Log.e(TAG, "Error calling ITelecomService#handlePinMmi", e);
1464             }
1465         }
1466         return false;
1467     }
1468 
1469     /**
1470      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE}
1471      *
1472      * @param accountHandle The handle for the account to derive an adn query URI for or
1473      * {@code null} to return a URI which will use the default account.
1474      * @return The URI (with the content:// scheme) specific to the specified {@link PhoneAccount}
1475      * for the the content retrieve.
1476      */
1477     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle)1478     public Uri getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle) {
1479         ITelecomService service = getTelecomService();
1480         if (service != null && accountHandle != null) {
1481             try {
1482                 return service.getAdnUriForPhoneAccount(accountHandle, mContext.getOpPackageName());
1483             } catch (RemoteException e) {
1484                 Log.e(TAG, "Error calling ITelecomService#getAdnUriForPhoneAccount", e);
1485             }
1486         }
1487         return Uri.parse("content://icc/adn");
1488     }
1489 
1490     /**
1491      * Removes the missed-call notification if one is present.
1492      * <p>
1493      * Requires that the method-caller be set as the system dialer app.
1494      * </p>
1495      *
1496      * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE}
1497      */
1498     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
cancelMissedCallsNotification()1499     public void cancelMissedCallsNotification() {
1500         ITelecomService service = getTelecomService();
1501         if (service != null) {
1502             try {
1503                 service.cancelMissedCallsNotification(mContext.getOpPackageName());
1504             } catch (RemoteException e) {
1505                 Log.e(TAG, "Error calling ITelecomService#cancelMissedCallsNotification", e);
1506             }
1507         }
1508     }
1509 
1510     /**
1511      * Brings the in-call screen to the foreground if there is an ongoing call. If there is
1512      * currently no ongoing call, then this method does nothing.
1513      * <p>
1514      * Requires that the method-caller be set as the system dialer app or have the
1515      * {@link android.Manifest.permission#READ_PHONE_STATE} permission.
1516      * </p>
1517      *
1518      * @param showDialpad Brings up the in-call dialpad as part of showing the in-call screen.
1519      */
1520     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
showInCallScreen(boolean showDialpad)1521     public void showInCallScreen(boolean showDialpad) {
1522         ITelecomService service = getTelecomService();
1523         if (service != null) {
1524             try {
1525                 service.showInCallScreen(showDialpad, mContext.getOpPackageName());
1526             } catch (RemoteException e) {
1527                 Log.e(TAG, "Error calling ITelecomService#showCallScreen", e);
1528             }
1529         }
1530     }
1531 
1532     /**
1533      * Places a new outgoing call to the provided address using the system telecom service with
1534      * the specified extras.
1535      *
1536      * This method is equivalent to placing an outgoing call using {@link Intent#ACTION_CALL},
1537      * except that the outgoing call will always be sent via the system telecom service. If
1538      * method-caller is either the user selected default dialer app or preloaded system dialer
1539      * app, then emergency calls will also be allowed.
1540      *
1541      * Placing a call via a managed {@link ConnectionService} requires permission:
1542      * {@link android.Manifest.permission#CALL_PHONE}
1543      *
1544      * Usage example:
1545      * <pre>
1546      * Uri uri = Uri.fromParts("tel", "12345", null);
1547      * Bundle extras = new Bundle();
1548      * extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true);
1549      * telecomManager.placeCall(uri, extras);
1550      * </pre>
1551      *
1552      * The following keys are supported in the supplied extras.
1553      * <ul>
1554      *   <li>{@link #EXTRA_OUTGOING_CALL_EXTRAS}</li>
1555      *   <li>{@link #EXTRA_PHONE_ACCOUNT_HANDLE}</li>
1556      *   <li>{@link #EXTRA_START_CALL_WITH_SPEAKERPHONE}</li>
1557      *   <li>{@link #EXTRA_START_CALL_WITH_VIDEO_STATE}</li>
1558      * </ul>
1559      * <p>
1560      * An app which implements the self-managed {@link ConnectionService} API uses
1561      * {@link #placeCall(Uri, Bundle)} to inform Telecom of a new outgoing call.  A self-managed
1562      * {@link ConnectionService} must include {@link #EXTRA_PHONE_ACCOUNT_HANDLE} to specify its
1563      * associated {@link android.telecom.PhoneAccountHandle}.
1564      *
1565      * Self-managed {@link ConnectionService}s require permission
1566      * {@link android.Manifest.permission#MANAGE_OWN_CALLS}.
1567      *
1568      * @param address The address to make the call to.
1569      * @param extras Bundle of extras to use with the call.
1570      */
1571     @RequiresPermission(anyOf = {android.Manifest.permission.CALL_PHONE,
1572             android.Manifest.permission.MANAGE_OWN_CALLS})
placeCall(Uri address, Bundle extras)1573     public void placeCall(Uri address, Bundle extras) {
1574         ITelecomService service = getTelecomService();
1575         if (service != null) {
1576             if (address == null) {
1577                 Log.w(TAG, "Cannot place call to empty address.");
1578             }
1579             try {
1580                 service.placeCall(address, extras == null ? new Bundle() : extras,
1581                         mContext.getOpPackageName());
1582             } catch (RemoteException e) {
1583                 Log.e(TAG, "Error calling ITelecomService#placeCall", e);
1584             }
1585         }
1586     }
1587 
1588     /**
1589      * Enables and disables specified phone account.
1590      *
1591      * @param handle Handle to the phone account.
1592      * @param isEnabled Enable state of the phone account.
1593      * @hide
1594      */
1595     @SystemApi
1596     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enablePhoneAccount(PhoneAccountHandle handle, boolean isEnabled)1597     public void enablePhoneAccount(PhoneAccountHandle handle, boolean isEnabled) {
1598         ITelecomService service = getTelecomService();
1599         if (service != null) {
1600             try {
1601                 service.enablePhoneAccount(handle, isEnabled);
1602             } catch (RemoteException e) {
1603                 Log.e(TAG, "Error enablePhoneAbbount", e);
1604             }
1605         }
1606     }
1607 
1608     /**
1609      * Dumps telecom analytics for uploading.
1610      *
1611      * @return
1612      * @hide
1613      */
1614     @SystemApi
1615     @RequiresPermission(Manifest.permission.DUMP)
dumpAnalytics()1616     public TelecomAnalytics dumpAnalytics() {
1617         ITelecomService service = getTelecomService();
1618         TelecomAnalytics result = null;
1619         if (service != null) {
1620             try {
1621                 result = service.dumpCallAnalytics();
1622             } catch (RemoteException e) {
1623                 Log.e(TAG, "Error dumping call analytics", e);
1624             }
1625         }
1626         return result;
1627     }
1628 
1629     /**
1630      * Creates the {@link Intent} which can be used with {@link Context#startActivity(Intent)} to
1631      * launch the activity to manage blocked numbers.
1632      * <p> The activity will display the UI to manage blocked numbers only if
1633      * {@link android.provider.BlockedNumberContract#canCurrentUserBlockNumbers(Context)} returns
1634      * {@code true} for the current user.
1635      */
createManageBlockedNumbersIntent()1636     public Intent createManageBlockedNumbersIntent() {
1637         ITelecomService service = getTelecomService();
1638         Intent result = null;
1639         if (service != null) {
1640             try {
1641                 result = service.createManageBlockedNumbersIntent();
1642             } catch (RemoteException e) {
1643                 Log.e(TAG, "Error calling ITelecomService#createManageBlockedNumbersIntent", e);
1644             }
1645         }
1646         return result;
1647     }
1648 
1649     /**
1650      * Determines whether Telecom would permit an incoming call to be added via the
1651      * {@link #addNewIncomingCall(PhoneAccountHandle, Bundle)} API for the specified
1652      * {@link PhoneAccountHandle}.
1653      * <p>
1654      * A {@link ConnectionService} may not add a call for the specified {@link PhoneAccountHandle}
1655      * in the following situations:
1656      * <ul>
1657      *     <li>{@link PhoneAccount} does not have property
1658      *     {@link PhoneAccount#CAPABILITY_SELF_MANAGED} set (i.e. it is a managed
1659      *     {@link ConnectionService}), and the active or held call limit has
1660      *     been reached.</li>
1661      *     <li>There is an ongoing emergency call.</li>
1662      * </ul>
1663      *
1664      * @param phoneAccountHandle The {@link PhoneAccountHandle} the call will be added for.
1665      * @return {@code true} if telecom will permit an incoming call to be added, {@code false}
1666      *      otherwise.
1667      */
isIncomingCallPermitted(PhoneAccountHandle phoneAccountHandle)1668     public boolean isIncomingCallPermitted(PhoneAccountHandle phoneAccountHandle) {
1669         if (phoneAccountHandle == null) {
1670             return false;
1671         }
1672 
1673         ITelecomService service = getTelecomService();
1674         if (service != null) {
1675             try {
1676                 return service.isIncomingCallPermitted(phoneAccountHandle);
1677             } catch (RemoteException e) {
1678                 Log.e(TAG, "Error isIncomingCallPermitted", e);
1679             }
1680         }
1681         return false;
1682     }
1683 
1684     /**
1685      * Determines whether Telecom would permit an outgoing call to be placed via the
1686      * {@link #placeCall(Uri, Bundle)} API for the specified {@link PhoneAccountHandle}.
1687      * <p>
1688      * A {@link ConnectionService} may not place a call for the specified {@link PhoneAccountHandle}
1689      * in the following situations:
1690      * <ul>
1691      *     <li>{@link PhoneAccount} does not have property
1692      *     {@link PhoneAccount#CAPABILITY_SELF_MANAGED} set (i.e. it is a managed
1693      *     {@link ConnectionService}), and the active, held or ringing call limit has
1694      *     been reached.</li>
1695      *     <li>{@link PhoneAccount} has property {@link PhoneAccount#CAPABILITY_SELF_MANAGED} set
1696      *     (i.e. it is a self-managed {@link ConnectionService} and there is an ongoing call in
1697      *     another {@link ConnectionService}.</li>
1698      *     <li>There is an ongoing emergency call.</li>
1699      * </ul>
1700      *
1701      * @param phoneAccountHandle The {@link PhoneAccountHandle} the call will be added for.
1702      * @return {@code true} if telecom will permit an outgoing call to be placed, {@code false}
1703      *      otherwise.
1704      */
isOutgoingCallPermitted(PhoneAccountHandle phoneAccountHandle)1705     public boolean isOutgoingCallPermitted(PhoneAccountHandle phoneAccountHandle) {
1706         ITelecomService service = getTelecomService();
1707         if (service != null) {
1708             try {
1709                 return service.isOutgoingCallPermitted(phoneAccountHandle);
1710             } catch (RemoteException e) {
1711                 Log.e(TAG, "Error isOutgoingCallPermitted", e);
1712             }
1713         }
1714         return false;
1715     }
1716 
1717 
getTelecomService()1718     private ITelecomService getTelecomService() {
1719         if (mTelecomServiceOverride != null) {
1720             return mTelecomServiceOverride;
1721         }
1722         return ITelecomService.Stub.asInterface(ServiceManager.getService(Context.TELECOM_SERVICE));
1723     }
1724 
isServiceConnected()1725     private boolean isServiceConnected() {
1726         boolean isConnected = getTelecomService() != null;
1727         if (!isConnected) {
1728             Log.w(TAG, "Telecom Service not found.");
1729         }
1730         return isConnected;
1731     }
1732 }
1733