1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.telephony;
18 
19 import static android.content.Context.TELECOM_SERVICE;
20 import static android.provider.Telephony.Carriers.DPC_URI;
21 import static android.provider.Telephony.Carriers.INVALID_APN_ID;
22 
23 import static com.android.internal.util.Preconditions.checkNotNull;
24 
25 import android.Manifest;
26 import android.annotation.CallbackExecutor;
27 import android.annotation.IntDef;
28 import android.annotation.LongDef;
29 import android.annotation.NonNull;
30 import android.annotation.Nullable;
31 import android.annotation.RequiresPermission;
32 import android.annotation.SdkConstant;
33 import android.annotation.SdkConstant.SdkConstantType;
34 import android.annotation.SuppressAutoDoc;
35 import android.annotation.SuppressLint;
36 import android.annotation.SystemApi;
37 import android.annotation.SystemService;
38 import android.annotation.TestApi;
39 import android.annotation.WorkerThread;
40 import android.app.PendingIntent;
41 import android.compat.Compatibility;
42 import android.compat.annotation.ChangeId;
43 import android.compat.annotation.EnabledAfter;
44 import android.compat.annotation.UnsupportedAppUsage;
45 import android.content.ComponentName;
46 import android.content.Context;
47 import android.content.Intent;
48 import android.database.Cursor;
49 import android.net.ConnectivityManager;
50 import android.net.Uri;
51 import android.os.AsyncTask;
52 import android.os.Binder;
53 import android.os.Build;
54 import android.os.Bundle;
55 import android.os.Handler;
56 import android.os.ParcelFileDescriptor;
57 import android.os.PersistableBundle;
58 import android.os.Process;
59 import android.os.RemoteException;
60 import android.os.ResultReceiver;
61 import android.os.ServiceManager;
62 import android.os.SystemProperties;
63 import android.os.WorkSource;
64 import android.provider.Settings.SettingNotFoundException;
65 import android.service.carrier.CarrierIdentifier;
66 import android.sysprop.TelephonyProperties;
67 import android.telecom.CallScreeningService;
68 import android.telecom.InCallService;
69 import android.telecom.PhoneAccount;
70 import android.telecom.PhoneAccountHandle;
71 import android.telecom.TelecomManager;
72 import android.telephony.Annotation.ApnType;
73 import android.telephony.Annotation.CallState;
74 import android.telephony.Annotation.CarrierPrivilegeStatus;
75 import android.telephony.Annotation.NetworkType;
76 import android.telephony.Annotation.RadioPowerState;
77 import android.telephony.Annotation.SimActivationState;
78 import android.telephony.Annotation.UiccAppType;
79 import android.telephony.CallForwardingInfo.CallForwardingReason;
80 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
81 import android.telephony.data.ApnSetting;
82 import android.telephony.data.ApnSetting.MvnoType;
83 import android.telephony.emergency.EmergencyNumber;
84 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
85 import android.telephony.ims.ImsMmTelManager;
86 import android.telephony.ims.aidl.IImsConfig;
87 import android.telephony.ims.aidl.IImsMmTelFeature;
88 import android.telephony.ims.aidl.IImsRcsFeature;
89 import android.telephony.ims.aidl.IImsRegistration;
90 import android.telephony.ims.feature.MmTelFeature;
91 import android.telephony.ims.stub.ImsRegistrationImplBase;
92 import android.text.TextUtils;
93 import android.util.Log;
94 import android.util.Pair;
95 
96 import com.android.ims.internal.IImsServiceFeatureCallback;
97 import com.android.internal.annotations.VisibleForTesting;
98 import com.android.internal.telephony.CellNetworkScanResult;
99 import com.android.internal.telephony.IBooleanConsumer;
100 import com.android.internal.telephony.INumberVerificationCallback;
101 import com.android.internal.telephony.IOns;
102 import com.android.internal.telephony.IPhoneSubInfo;
103 import com.android.internal.telephony.ISetOpportunisticDataCallback;
104 import com.android.internal.telephony.ITelephony;
105 import com.android.internal.telephony.ITelephonyRegistry;
106 import com.android.internal.telephony.IUpdateAvailableNetworksCallback;
107 import com.android.internal.telephony.OperatorInfo;
108 import com.android.internal.telephony.PhoneConstants;
109 import com.android.internal.telephony.RILConstants;
110 import com.android.internal.telephony.SmsApplication;
111 import com.android.telephony.Rlog;
112 
113 import java.lang.annotation.Retention;
114 import java.lang.annotation.RetentionPolicy;
115 import java.util.ArrayList;
116 import java.util.Collections;
117 import java.util.HashMap;
118 import java.util.List;
119 import java.util.Locale;
120 import java.util.Map;
121 import java.util.Objects;
122 import java.util.UUID;
123 import java.util.concurrent.Executor;
124 import java.util.function.Consumer;
125 
126 /**
127  * Provides access to information about the telephony services on
128  * the device. Applications can use the methods in this class to
129  * determine telephony services and states, as well as to access some
130  * types of subscriber information. Applications can also register
131  * a listener to receive notification of telephony state changes.
132  * <p>
133  * The returned TelephonyManager will use the default subscription for all calls.
134  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
135  * <code>
136  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
137  * </code>
138  * <p>
139  * Note that access to some telephony information is
140  * permission-protected. Your application cannot access the protected
141  * information unless it has the appropriate permissions declared in
142  * its manifest file. Where permissions apply, they are noted in the
143  * the methods through which you access the protected information.
144  */
145 @SystemService(Context.TELEPHONY_SERVICE)
146 public class TelephonyManager {
147     private static final String TAG = "TelephonyManager";
148 
149     /**
150      * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
151      * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
152      */
153     @ChangeId
154     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
155     public static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
156 
157     /**
158      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
159      * into the ResultReceiver Bundle.
160      * @hide
161      */
162     public static final String MODEM_ACTIVITY_RESULT_KEY = "controller_activity";
163 
164     /**
165      * The process name of the Phone app as well as many other apps that use this process name, such
166      * as settings and vendor components.
167      * @hide
168      */
169     public static final String PHONE_PROCESS_NAME = "com.android.phone";
170 
171     /**
172      * The allowed states of Wi-Fi calling.
173      *
174      * @hide
175      */
176     public interface WifiCallingChoices {
177         /** Always use Wi-Fi calling */
178         static final int ALWAYS_USE = 0;
179         /** Ask the user whether to use Wi-Fi on every call */
180         static final int ASK_EVERY_TIME = 1;
181         /** Never use Wi-Fi calling */
182         static final int NEVER_USE = 2;
183     }
184 
185     /** @hide */
186     @Retention(RetentionPolicy.SOURCE)
187     @IntDef(prefix = {"NETWORK_SELECTION_MODE_"},
188             value = {
189                     NETWORK_SELECTION_MODE_UNKNOWN,
190                     NETWORK_SELECTION_MODE_AUTO,
191                     NETWORK_SELECTION_MODE_MANUAL})
192     public @interface NetworkSelectionMode {}
193 
194     public static final int NETWORK_SELECTION_MODE_UNKNOWN = 0;
195     public static final int NETWORK_SELECTION_MODE_AUTO = 1;
196     public static final int NETWORK_SELECTION_MODE_MANUAL = 2;
197 
198     /** The otaspMode passed to PhoneStateListener#onOtaspChanged */
199     /** @hide */
200     static public final int OTASP_UNINITIALIZED = 0;
201     /** @hide */
202     static public final int OTASP_UNKNOWN = 1;
203     /** @hide */
204     static public final int OTASP_NEEDED = 2;
205     /** @hide */
206     static public final int OTASP_NOT_NEEDED = 3;
207     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
208     /** @hide */
209     static public final int OTASP_SIM_UNPROVISIONED = 5;
210 
211     /**
212      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
213      * available for use in ePDG links.
214      *
215      * @hide
216      */
217     @SystemApi
218     static public final int KEY_TYPE_EPDG = 1;
219 
220     /**
221      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
222      * available for use in WLAN links.
223      *
224      * @hide
225      */
226     @SystemApi
227     static public final int KEY_TYPE_WLAN = 2;
228 
229     /** @hide */
230     @Retention(RetentionPolicy.SOURCE)
231     @IntDef(prefix = {"KEY_TYPE_"}, value = {KEY_TYPE_EPDG, KEY_TYPE_WLAN})
232     public @interface KeyType {}
233 
234     /**
235      * No Single Radio Voice Call Continuity (SRVCC) handover is active.
236      * See TS 23.216 for more information.
237      * @hide
238      */
239     @SystemApi
240     public static final int SRVCC_STATE_HANDOVER_NONE  = -1;
241 
242     /**
243      * Single Radio Voice Call Continuity (SRVCC) handover has been started on the network.
244      * See TS 23.216 for more information.
245      * @hide
246      */
247     @SystemApi
248     public static final int SRVCC_STATE_HANDOVER_STARTED  = 0;
249 
250     /**
251      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has successfully completed.
252      * See TS 23.216 for more information.
253      * @hide
254      */
255     @SystemApi
256     public static final int SRVCC_STATE_HANDOVER_COMPLETED = 1;
257 
258     /**
259      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has failed.
260      * See TS 23.216 for more information.
261      * @hide
262      */
263     @SystemApi
264     public static final int SRVCC_STATE_HANDOVER_FAILED   = 2;
265 
266     /**
267      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has been canceled.
268      * See TS 23.216 for more information.
269      * @hide
270      */
271     @SystemApi
272     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
273 
274     /**
275      * A UICC card identifier used if the device does not support the operation.
276      * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
277      * eUICC, or the eUICC cannot be read.
278      */
279     public static final int UNSUPPORTED_CARD_ID = -1;
280 
281     /**
282      * A UICC card identifier used before the UICC card is loaded. See
283      * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
284      * <p>
285      * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
286      */
287     public static final int UNINITIALIZED_CARD_ID = -2;
288 
289     private final Context mContext;
290     private final int mSubId;
291     @UnsupportedAppUsage
292     private SubscriptionManager mSubscriptionManager;
293     private TelephonyScanManager mTelephonyScanManager;
294 
295     /** Enum indicating multisim variants
296      *  DSDS - Dual SIM Dual Standby
297      *  DSDA - Dual SIM Dual Active
298      *  TSTS - Triple SIM Triple Standby
299      **/
300     /** @hide */
301     @UnsupportedAppUsage(implicitMember =
302             "values()[Landroid/telephony/TelephonyManager$MultiSimVariants;")
303     public enum MultiSimVariants {
304         @UnsupportedAppUsage
305         DSDS,
306         @UnsupportedAppUsage
307         DSDA,
308         @UnsupportedAppUsage
309         TSTS,
310         @UnsupportedAppUsage
311         UNKNOWN
312     };
313 
314     /** @hide */
315     @UnsupportedAppUsage
TelephonyManager(Context context)316     public TelephonyManager(Context context) {
317       this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
318     }
319 
320     /** @hide */
321     @UnsupportedAppUsage
TelephonyManager(Context context, int subId)322     public TelephonyManager(Context context, int subId) {
323         mSubId = subId;
324         Context appContext = context.getApplicationContext();
325         if (appContext != null) {
326             mContext = appContext;
327         } else {
328             mContext = context;
329         }
330         mSubscriptionManager = SubscriptionManager.from(mContext);
331     }
332 
333     /** @hide */
334     @UnsupportedAppUsage
TelephonyManager()335     private TelephonyManager() {
336         mContext = null;
337         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
338     }
339 
340     private static TelephonyManager sInstance = new TelephonyManager();
341 
342     /** @hide
343     /* @deprecated - use getSystemService as described above */
344     @Deprecated
345     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDefault()346     public static TelephonyManager getDefault() {
347         return sInstance;
348     }
349 
getOpPackageName()350     private String getOpPackageName() {
351         // For legacy reasons the TelephonyManager has API for getting
352         // a static instance with no context set preventing us from
353         // getting the op package name. As a workaround we do a best
354         // effort and get the context from the current activity thread.
355         if (mContext != null) {
356             return mContext.getOpPackageName();
357         } else {
358             ITelephony telephony = getITelephony();
359             if (telephony == null) return null;
360             try {
361                 return telephony.getCurrentPackageName();
362             } catch (RemoteException ex) {
363                 return null;
364             } catch (NullPointerException ex) {
365                 return null;
366             }
367         }
368     }
369 
getFeatureId()370     private String getFeatureId() {
371         return null;
372     }
373 
isSystemProcess()374     private boolean isSystemProcess() {
375         return Process.myUid() == Process.SYSTEM_UID;
376     }
377 
378     /**
379      * Returns the multi SIM variant
380      * Returns DSDS for Dual SIM Dual Standby
381      * Returns DSDA for Dual SIM Dual Active
382      * Returns TSTS for Triple SIM Triple Standby
383      * Returns UNKNOWN for others
384      */
385     /** {@hide} */
386     @UnsupportedAppUsage
getMultiSimConfiguration()387     public MultiSimVariants getMultiSimConfiguration() {
388         String mSimConfig =
389                 TelephonyProperties.multi_sim_config().orElse("");
390         if (mSimConfig.equals("dsds")) {
391             return MultiSimVariants.DSDS;
392         } else if (mSimConfig.equals("dsda")) {
393             return MultiSimVariants.DSDA;
394         } else if (mSimConfig.equals("tsts")) {
395             return MultiSimVariants.TSTS;
396         } else {
397             return MultiSimVariants.UNKNOWN;
398         }
399     }
400 
401     /**
402      * Returns the number of phones available.
403      * Returns 0 if none of voice, sms, data is not supported
404      * Returns 1 for Single standby mode (Single SIM functionality).
405      * Returns 2 for Dual standby mode (Dual SIM functionality).
406      * Returns 3 for Tri standby mode (Tri SIM functionality).
407      * @deprecated Use {@link #getActiveModemCount} instead.
408      */
409     @Deprecated
getPhoneCount()410     public int getPhoneCount() {
411         return getActiveModemCount();
412     }
413 
414     /**
415      * Returns the number of logical modems currently configured to be activated.
416      *
417      * Returns 0 if none of voice, sms, data is not supported
418      * Returns 1 for Single standby mode (Single SIM functionality).
419      * Returns 2 for Dual standby mode (Dual SIM functionality).
420      * Returns 3 for Tri standby mode (Tri SIM functionality).
421      */
getActiveModemCount()422     public int getActiveModemCount() {
423         int modemCount = 1;
424         switch (getMultiSimConfiguration()) {
425             case UNKNOWN:
426                 modemCount = 1;
427                 // check for voice and data support, 0 if not supported
428                 if (!isVoiceCapable() && !isSmsCapable() && !isDataCapable()) {
429                     modemCount = 0;
430                 }
431                 break;
432             case DSDS:
433             case DSDA:
434                 modemCount = 2;
435                 break;
436             case TSTS:
437                 modemCount = 3;
438                 break;
439         }
440         return modemCount;
441     }
442 
443     /**
444      * Return how many logical modem can be potentially active simultaneously, in terms of hardware
445      * capability.
446      * It might return different value from {@link #getActiveModemCount}. For example, for a
447      * dual-SIM capable device operating in single SIM mode (only one logical modem is turned on),
448      * {@link #getActiveModemCount} returns 1 while this API returns 2.
449      */
getSupportedModemCount()450     public int getSupportedModemCount() {
451         return TelephonyProperties.max_active_modems().orElse(getActiveModemCount());
452     }
453 
454     /**
455      * Gets the maximum number of SIMs that can be active, based on the device's multisim
456      * configuration.
457      * @return 1 for single-SIM, DSDS, and TSTS devices. 2 for DSDA devices.
458      * @hide
459      */
460     @SystemApi
getMaxNumberOfSimultaneouslyActiveSims()461     public int getMaxNumberOfSimultaneouslyActiveSims() {
462         switch (getMultiSimConfiguration()) {
463             case UNKNOWN:
464             case DSDS:
465             case TSTS:
466                 return 1;
467             case DSDA:
468                 return 2;
469         }
470         return 1;
471     }
472 
473     /** {@hide} */
474     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)475     public static TelephonyManager from(Context context) {
476         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
477     }
478 
479     /**
480      * Create a new TelephonyManager object pinned to the given subscription ID.
481      *
482      * @return a TelephonyManager that uses the given subId for all calls.
483      */
createForSubscriptionId(int subId)484     public TelephonyManager createForSubscriptionId(int subId) {
485       // Don't reuse any TelephonyManager objects.
486       return new TelephonyManager(mContext, subId);
487     }
488 
489     /**
490      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
491      * phone account.
492      *
493      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
494      * if the phone account does not correspond to a valid subscription ID.
495      */
496     @Nullable
createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle)497     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
498         int subId = getSubscriptionId(phoneAccountHandle);
499         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
500             return null;
501         }
502         return new TelephonyManager(mContext, subId);
503     }
504 
505     /** {@hide} */
506     @UnsupportedAppUsage
isMultiSimEnabled()507     public boolean isMultiSimEnabled() {
508         return getPhoneCount() > 1;
509     }
510 
511     //
512     // Broadcast Intent actions
513     //
514 
515     /**
516      * Broadcast intent action indicating that the call state
517      * on the device has changed.
518      *
519      * <p>
520      * The {@link #EXTRA_STATE} extra indicates the new call state.
521      * If a receiving app has {@link android.Manifest.permission#READ_CALL_LOG} permission, a second
522      * extra {@link #EXTRA_INCOMING_NUMBER} provides the phone number for incoming and outgoing
523      * calls as a String.
524      * <p>
525      * If the receiving app has
526      * {@link android.Manifest.permission#READ_CALL_LOG} and
527      * {@link android.Manifest.permission#READ_PHONE_STATE} permission, it will receive the
528      * broadcast twice; one with the {@link #EXTRA_INCOMING_NUMBER} populated with the phone number,
529      * and another with it blank.  Due to the nature of broadcasts, you cannot assume the order
530      * in which these broadcasts will arrive, however you are guaranteed to receive two in this
531      * case.  Apps which are interested in the {@link #EXTRA_INCOMING_NUMBER} can ignore the
532      * broadcasts where {@link #EXTRA_INCOMING_NUMBER} is not present in the extras (e.g. where
533      * {@link Intent#hasExtra(String)} returns {@code false}).
534      * <p class="note">
535      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
536      * broadcast in version 1.0, but it is no longer sticky.
537      * Instead, use {@link #getCallState} to synchronously query the current call state.
538      *
539      * @see #EXTRA_STATE
540      * @see #EXTRA_INCOMING_NUMBER
541      * @see #getCallState
542      */
543     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
544     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
545     public static final String ACTION_PHONE_STATE_CHANGED =
546             "android.intent.action.PHONE_STATE";
547 
548     /**
549      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
550      * call. By default, the device's default SMS app consumes this message and sends a text message
551      * to the caller. A third party app can also provide this functionality by consuming this Intent
552      * with a {@link android.app.Service} and sending the message using its own messaging system.
553      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
554      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
555      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
556      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
557      * set of phone numbers if there are multiple recipients. For example, {@code
558      * smsto:2065551234}.</p>
559      *
560      * <p>The intent may also contain extras for the message text (in {@link
561      * android.content.Intent#EXTRA_TEXT}) and a message subject
562      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
563      *
564      * <p class="note"><strong>Note:</strong>
565      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
566      * that requires the
567      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
568      * <p>For example, the service that receives this intent can be declared in the manifest file
569      * with an intent filter like this:</p>
570      * <pre>
571      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
572      * &lt;service android:name=".HeadlessSmsSendService"
573      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
574      *          android:exported="true" >
575      *   &lt;intent-filter>
576      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
577      *     &lt;category android:name="android.intent.category.DEFAULT" />
578      *     &lt;data android:scheme="sms" />
579      *     &lt;data android:scheme="smsto" />
580      *     &lt;data android:scheme="mms" />
581      *     &lt;data android:scheme="mmsto" />
582      *   &lt;/intent-filter>
583      * &lt;/service></pre>
584      * <p>
585      * Output: nothing.
586      */
587     @SdkConstant(SdkConstantType.SERVICE_ACTION)
588     public static final String ACTION_RESPOND_VIA_MESSAGE =
589             "android.intent.action.RESPOND_VIA_MESSAGE";
590 
591     /**
592      * The emergency dialer may choose to present activities with intent filters for this
593      * action as emergency assistance buttons that launch the activity when clicked.
594      *
595      * @hide
596      */
597     @SystemApi
598     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
599     public static final String ACTION_EMERGENCY_ASSISTANCE =
600             "android.telephony.action.EMERGENCY_ASSISTANCE";
601 
602     /**
603      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
604      * call settings page launched by
605      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
606      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
607      * which would also like to manage voicemail settings should set this meta-data to {@code true}
608      * in the manifest registration of their application.
609      *
610      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
611      * @see #ACTION_CONFIGURE_VOICEMAIL
612      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
613      */
614     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
615             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
616 
617     /**
618      * Open the voicemail settings activity to make changes to voicemail configuration.
619      *
620      * <p>
621      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} to
622      * configure voicemail.
623      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
624      * API if set.
625      *
626      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
627      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
628      */
629     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
630     public static final String ACTION_CONFIGURE_VOICEMAIL =
631             "android.telephony.action.CONFIGURE_VOICEMAIL";
632 
633     /**
634      * The boolean value indicating whether the voicemail settings activity launched by {@link
635      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
636      * used by dialer implementations which provides their own voicemail settings UI, but still
637      * needs to expose device specific voicemail settings to the user.
638      *
639      * @see #ACTION_CONFIGURE_VOICEMAIL
640      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
641      */
642     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
643             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
644 
645     /**
646      * @hide
647      */
648     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
649 
650     /**
651      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
652      * for a String containing the new call state.
653      *
654      * <p class="note">
655      * Retrieve with
656      * {@link android.content.Intent#getStringExtra(String)}.
657      *
658      * @see #EXTRA_STATE_IDLE
659      * @see #EXTRA_STATE_RINGING
660      * @see #EXTRA_STATE_OFFHOOK
661      */
662     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
663 
664     /**
665      * Value used with {@link #EXTRA_STATE} corresponding to
666      * {@link #CALL_STATE_IDLE}.
667      */
668     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
669 
670     /**
671      * Value used with {@link #EXTRA_STATE} corresponding to
672      * {@link #CALL_STATE_RINGING}.
673      */
674     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
675 
676     /**
677      * Value used with {@link #EXTRA_STATE} corresponding to
678      * {@link #CALL_STATE_OFFHOOK}.
679      */
680     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
681 
682     /**
683      * Extra key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
684      * for a String containing the incoming or outgoing phone number.
685      * <p>
686      * This extra is only populated for receivers of the {@link #ACTION_PHONE_STATE_CHANGED}
687      * broadcast which have been granted the {@link android.Manifest.permission#READ_CALL_LOG} and
688      * {@link android.Manifest.permission#READ_PHONE_STATE} permissions.
689      * <p>
690      * For incoming calls, the phone number is only guaranteed to be populated when the
691      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_RINGING}.
692      * If the incoming caller is from an unknown number, the extra will be populated with an empty
693      * string.
694      * For outgoing calls, the phone number is only guaranteed to be populated when the
695      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_OFFHOOK}.
696      * <p class="note">
697      * Retrieve with
698      * {@link android.content.Intent#getStringExtra(String)}.
699      * <p>
700      *
701      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
702      * to retrieve the phone number for calls instead.  Apps performing call screening should use
703      * the {@link CallScreeningService} API instead.
704      */
705     @Deprecated
706     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
707 
708     /**
709      * Broadcast intent action indicating that call disconnect cause has changed.
710      *
711      * <p>
712      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
713      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
714      *
715      * <p class="note">
716      * Requires the READ_PRECISE_PHONE_STATE permission.
717      *
718      * @see #EXTRA_DISCONNECT_CAUSE
719      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
720      *
721      * @hide
722      */
723     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
724     public static final String ACTION_CALL_DISCONNECT_CAUSE_CHANGED =
725             "android.intent.action.CALL_DISCONNECT_CAUSE";
726 
727     /**
728      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
729      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
730      * containing the disconnect cause.
731      *
732      * @see DisconnectCause
733      *
734      * <p class="note">
735      * Retrieve with
736      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
737      *
738      * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
739      * @hide
740      */
741     @Deprecated
742     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
743 
744     /**
745      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
746      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
747      * containing the disconnect cause provided by the RIL.
748      *
749      * @see PreciseDisconnectCause
750      *
751      * <p class="note">
752      * Retrieve with
753      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
754      *
755      * @hide
756      */
757     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
758 
759     /**
760      * Broadcast intent action for letting the default dialer to know to show voicemail
761      * notification.
762      *
763      * <p>
764      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
765      * voicemail is received on.
766      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
767      * voicemails.
768      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
769      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
770      * will call the voicemail number when sent. This extra will be empty if the voicemail number
771      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
772      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
773      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
774      * available when the voicemail number is not set.
775      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
776      * notification.
777      *
778      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
779      * @see #EXTRA_NOTIFICATION_COUNT
780      * @see #EXTRA_VOICEMAIL_NUMBER
781      * @see #EXTRA_CALL_VOICEMAIL_INTENT
782      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
783      * @see #EXTRA_IS_REFRESH
784      */
785     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
786             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
787 
788     /**
789      * The extra used with an {@link #ACTION_CONFIGURE_VOICEMAIL} and
790      * {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify the
791      * {@link PhoneAccountHandle} the configuration or notification is for.
792      * <p class="note">
793      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
794      */
795     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
796             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
797 
798     /**
799      * The number of voice messages associated with the notification.
800      */
801     public static final String EXTRA_NOTIFICATION_COUNT =
802             "android.telephony.extra.NOTIFICATION_COUNT";
803 
804     /**
805      * The voicemail number.
806      */
807     public static final String EXTRA_VOICEMAIL_NUMBER =
808             "android.telephony.extra.VOICEMAIL_NUMBER";
809 
810     /**
811      * The intent to call voicemail.
812      */
813     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
814             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
815 
816     /**
817      * The intent to launch voicemail settings.
818      */
819     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
820             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
821 
822     /**
823      * Boolean value representing whether the {@link
824      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
825      * notification. Notification refresh happens after reboot or connectivity changes. The user has
826      * already been notified for the voicemail so it should not alert the user, and should not be
827      * shown again if the user has dismissed it.
828      */
829     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
830 
831     /**
832      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
833      * successfully handed over from WIFI to LTE.
834      * <p>
835      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
836      * The {@link Bundle} parameter is expected to be null when this connection event is used.
837      * @hide
838      */
839     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
840             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
841 
842     /**
843      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
844      * successfully handed over from LTE to WIFI.
845      * <p>
846      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
847      * The {@link Bundle} parameter is expected to be null when this connection event is used.
848      * @hide
849      */
850     public static final String EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI =
851             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI";
852 
853     /**
854      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
855      * handed over from LTE to WIFI.
856      * <p>
857      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
858      * The {@link Bundle} parameter is expected to be null when this connection event is used.
859      * @hide
860      */
861     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
862             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
863 
864     /**
865      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
866      * audio because the data limit was reached.
867      * <p>
868      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
869      * The {@link Bundle} parameter is expected to be null when this connection event is used.
870      * @hide
871      */
872     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
873             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
874 
875     /**
876      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
877      * audio because the data was disabled.
878      * <p>
879      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
880      * The {@link Bundle} parameter is expected to be null when this connection event is used.
881      * @hide
882      */
883     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
884             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
885 
886     /**
887      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
888      * the user when an international call is placed while on WFC only.
889      * <p>
890      * Used when the carrier config value
891      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
892      * is on WFC (VoLTE not available) and an international number is dialed.
893      * <p>
894      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
895      * The {@link Bundle} parameter is expected to be null when this connection event is used.
896      * @hide
897      */
898     public static final String EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
899             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
900 
901     /**
902      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
903      * forwarded to another number.
904      * <p>
905      * Sent in response to an IMS supplementary service notification indicating the call has been
906      * forwarded.
907      * <p>
908      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
909      * The {@link Bundle} parameter is expected to be null when this connection event is used.
910      * @hide
911      */
912     public static final String EVENT_CALL_FORWARDED =
913             "android.telephony.event.EVENT_CALL_FORWARDED";
914 
915     /**
916      * {@link android.telecom.Connection} event used to indicate that a supplementary service
917      * notification has been received.
918      * <p>
919      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
920      * The {@link Bundle} parameter is expected to include the following extras:
921      * <ul>
922      *     <li>{@link #EXTRA_NOTIFICATION_TYPE} - the notification type.</li>
923      *     <li>{@link #EXTRA_NOTIFICATION_CODE} - the notification code.</li>
924      *     <li>{@link #EXTRA_NOTIFICATION_MESSAGE} - human-readable message associated with the
925      *     supplementary service notification.</li>
926      * </ul>
927      * @hide
928      */
929     public static final String EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION =
930             "android.telephony.event.EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION";
931 
932     /**
933      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
934      * the type of supplementary service notification which occurred.
935      * Will be either
936      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_1}
937      * or
938      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_2}
939      * <p>
940      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
941      * @hide
942      */
943     public static final String EXTRA_NOTIFICATION_TYPE =
944             "android.telephony.extra.NOTIFICATION_TYPE";
945 
946     /**
947      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
948      * the supplementary service notification which occurred.
949      * <p>
950      * Depending on the {@link #EXTRA_NOTIFICATION_TYPE}, the code will be one of the {@code CODE_*}
951      * codes defined in {@link com.android.internal.telephony.gsm.SuppServiceNotification}.
952      * <p>
953      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
954      * @hide
955      */
956     public static final String EXTRA_NOTIFICATION_CODE =
957             "android.telephony.extra.NOTIFICATION_CODE";
958 
959     /**
960      * {@link CharSequence} extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION}
961      * which contains a human-readable message which can be displayed to the user for the
962      * supplementary service notification.
963      * <p>
964      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
965      * @hide
966      */
967     public static final String EXTRA_NOTIFICATION_MESSAGE =
968             "android.telephony.extra.NOTIFICATION_MESSAGE";
969 
970     /* Visual voicemail protocols */
971 
972     /**
973      * The OMTP protocol.
974      */
975     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
976 
977     /**
978      * A flavor of OMTP protocol with a different mobile originated (MO) format
979      */
980     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
981 
982     /**
983      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
984      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
985      * setting, this key will not exist.
986      *
987      * @see #getVisualVoicemailSettings()
988      * @hide
989      */
990     @SystemApi
991     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
992             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
993 
994     /**
995      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
996      * access PIN scrambled during the auto provisioning process. The user is expected to reset
997      * their PIN if this value is not {@code null}.
998      *
999      * @see #getVisualVoicemailSettings()
1000      * @hide
1001      */
1002     @SystemApi
1003     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
1004             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
1005 
1006     /**
1007      * Broadcast action to be received by Broadcast receivers.
1008      *
1009      * Indicates multi-SIM configuration is changed. For example, it changed
1010      * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
1011      *
1012      * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
1013      * or that all steps during multi-SIM change are done. To know those information you still need
1014      * to listen to SIM_STATE changes or active subscription changes.
1015      *
1016      * See extra of {@link #EXTRA_ACTIVE_SIM_SUPPORTED_COUNT} for updated value.
1017      */
1018     public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
1019             "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
1020 
1021 
1022     /**
1023      * The number of active SIM supported by current multi-SIM config. It's not related to how many
1024      * SIM/subscriptions are currently active.
1025      *
1026      * Same value will be returned by {@link #getActiveModemCount()}.
1027      *
1028      * For single SIM mode, it's 1.
1029      * For DSDS or DSDA mode, it's 2.
1030      * For triple-SIM mode, it's 3.
1031      *
1032      * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
1033      *
1034      * type: integer
1035      */
1036     public static final String EXTRA_ACTIVE_SIM_SUPPORTED_COUNT =
1037             "android.telephony.extra.ACTIVE_SIM_SUPPORTED_COUNT";
1038 
1039     /**
1040      * @hide
1041      */
1042     public static final String USSD_RESPONSE = "USSD_RESPONSE";
1043 
1044     /**
1045      * USSD return code success.
1046      * @hide
1047      */
1048     public static final int USSD_RETURN_SUCCESS = 100;
1049 
1050     /**
1051      * Failed code returned when the mobile network has failed to complete a USSD request.
1052      * <p>
1053      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1054      * TelephonyManager, String, int)}.
1055      */
1056     public static final int USSD_RETURN_FAILURE = -1;
1057 
1058     /**
1059      * Failure code returned when a USSD request has failed to execute because the Telephony
1060      * service is unavailable.
1061      * <p>
1062      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1063      * TelephonyManager, String, int)}.
1064      */
1065     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
1066 
1067     /**
1068      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which leaves the roaming
1069      * mode set to the radio default or to the user's preference if they've indicated one.
1070      */
1071     public static final int CDMA_ROAMING_MODE_RADIO_DEFAULT = -1;
1072     /**
1073      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which only permits
1074      * connections on home networks.
1075      */
1076     public static final int CDMA_ROAMING_MODE_HOME = 0;
1077     /**
1078      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1079      * affiliated networks.
1080      */
1081     public static final int CDMA_ROAMING_MODE_AFFILIATED = 1;
1082     /**
1083      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1084      * any network.
1085      */
1086     public static final int CDMA_ROAMING_MODE_ANY = 2;
1087 
1088     /** @hide */
1089     @IntDef(prefix = { "CDMA_ROAMING_MODE_" }, value = {
1090             CDMA_ROAMING_MODE_RADIO_DEFAULT,
1091             CDMA_ROAMING_MODE_HOME,
1092             CDMA_ROAMING_MODE_AFFILIATED,
1093             CDMA_ROAMING_MODE_ANY
1094     })
1095     @Retention(RetentionPolicy.SOURCE)
1096     public @interface CdmaRoamingMode{}
1097 
1098     /**
1099      * An unknown carrier id. It could either be subscription unavailable or the subscription
1100      * carrier cannot be recognized. Unrecognized carriers here means
1101      * {@link #getSimOperator() MCC+MNC} cannot be identified.
1102      */
1103     public static final int UNKNOWN_CARRIER_ID = -1;
1104 
1105     /**
1106      * An unknown carrier id list version.
1107      * @hide
1108      */
1109     @TestApi
1110     public static final int UNKNOWN_CARRIER_ID_LIST_VERSION = -1;
1111 
1112     /**
1113      * Broadcast Action: The subscription carrier identity has changed.
1114      * This intent could be sent on the following events:
1115      * <ul>
1116      *   <li>Subscription absent. Carrier identity could change from a valid id to
1117      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID}.</li>
1118      *   <li>Subscription loaded. Carrier identity could change from
1119      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID} to a valid id.</li>
1120      *   <li>The subscription carrier is recognized after a remote update.</li>
1121      * </ul>
1122      * The intent will have the following extra values:
1123      * <ul>
1124      *   <li>{@link #EXTRA_CARRIER_ID} The up-to-date carrier id of the current subscription id.
1125      *   </li>
1126      *   <li>{@link #EXTRA_CARRIER_NAME} The up-to-date carrier name of the current subscription.
1127      *   </li>
1128      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1129      *   identity.
1130      *   </li>
1131      * </ul>
1132      * <p class="note">This is a protected intent that can only be sent by the system.
1133      */
1134     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1135     public static final String ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED =
1136             "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED";
1137 
1138     /**
1139      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which indicates
1140      * the updated carrier id returned by {@link TelephonyManager#getSimCarrierId()}.
1141      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1142      * the carrier cannot be identified.
1143      */
1144     public static final String EXTRA_CARRIER_ID = "android.telephony.extra.CARRIER_ID";
1145 
1146     /**
1147      * An string extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which
1148      * indicates the updated carrier name of the current subscription.
1149      * @see TelephonyManager#getSimCarrierIdName()
1150      * <p>Carrier name is a user-facing name of the carrier id {@link #EXTRA_CARRIER_ID},
1151      * usually the brand name of the subsidiary (e.g. T-Mobile).
1152      */
1153     public static final String EXTRA_CARRIER_NAME = "android.telephony.extra.CARRIER_NAME";
1154 
1155     /**
1156      * Broadcast Action: The subscription specific carrier identity has changed.
1157      *
1158      * A specific carrier ID returns the fine-grained carrier ID of the current subscription.
1159      * It can represent the fact that a carrier may be in effect an aggregation of other carriers
1160      * (ie in an MVNO type scenario) where each of these specific carriers which are used to make
1161      * up the actual carrier service may have different carrier configurations.
1162      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
1163      * different carrier configuration for different service offering such as a prepaid plan.
1164      *
1165      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
1166      * about the carrier itself should use the regular carrier ID returned by
1167      * {@link #getSimCarrierId()}.
1168      *
1169      * <p>Similar like {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED}, this intent will be
1170      * sent on the event of {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} while its also
1171      * possible to be sent without {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} when
1172      * specific carrier ID changes while carrier ID remains the same.
1173      * e.g, the same subscription switches to different IMSI could potentially change its
1174      * specific carrier ID while carrier id remains the same.
1175      * @see #getSimSpecificCarrierId()
1176      * @see #getSimCarrierId()
1177      *
1178      * The intent will have the following extra values:
1179      * <ul>
1180      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_ID} The up-to-date specific carrier id of the
1181      *   current subscription.
1182      *   </li>
1183      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_NAME} The up-to-date name of the specific carrier id.
1184      *   </li>
1185      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1186      *   identity.
1187      *   </li>
1188      * </ul>
1189      * <p class="note">This is a protected intent that can only be sent by the system.
1190      */
1191     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1192     public static final String ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED =
1193             "android.telephony.action.SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED";
1194 
1195     /**
1196      * An int extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED} which
1197      * indicates the updated specific carrier id returned by
1198      * {@link TelephonyManager#getSimSpecificCarrierId()}. Note, its possible specific carrier id
1199      * changes while {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} remains the same
1200      * e.g, when subscription switch to different IMSIs.
1201      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1202      * the carrier cannot be identified.
1203      */
1204     public static final String EXTRA_SPECIFIC_CARRIER_ID =
1205             "android.telephony.extra.SPECIFIC_CARRIER_ID";
1206 
1207     /**
1208      * An string extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED}
1209      * which indicates the updated specific carrier name returned by
1210      * {@link TelephonyManager#getSimSpecificCarrierIdName()}.
1211      * <p>it's a user-facing name of the specific carrier id {@link #EXTRA_SPECIFIC_CARRIER_ID}
1212      * e.g, Tracfone-AT&T
1213      */
1214     public static final String EXTRA_SPECIFIC_CARRIER_NAME =
1215             "android.telephony.extra.SPECIFIC_CARRIER_NAME";
1216 
1217     /**
1218      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} to indicate the
1219      * subscription which has changed; or in general whenever a subscription ID needs specified.
1220      */
1221     public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
1222 
1223     /**
1224      * Broadcast Action: The Service Provider string(s) have been updated. Activities or
1225      * services that use these strings should update their display.
1226      *
1227      * <p>The intent will have the following extra values:
1228      * <dl>
1229      *   <dt>{@link #EXTRA_SHOW_PLMN}</dt>
1230      *   <dd>Boolean that indicates whether the PLMN should be shown.</dd>
1231      *   <dt>{@link #EXTRA_PLMN}</dt>
1232      *   <dd>The operator name of the registered network, as a string.</dd>
1233      *   <dt>{@link #EXTRA_SHOW_SPN}</dt>
1234      *   <dd>Boolean that indicates whether the SPN should be shown.</dd>
1235      *   <dt>{@link #EXTRA_SPN}</dt>
1236      *   <dd>The service provider name, as a string.</dd>
1237      *   <dt>{@link #EXTRA_DATA_SPN}</dt>
1238      *   <dd>The service provider name for data service, as a string.</dd>
1239      * </dl>
1240      *
1241      * Note that {@link #EXTRA_SHOW_PLMN} may indicate that {@link #EXTRA_PLMN} should be displayed,
1242      * even though the value for {@link #EXTRA_PLMN} is null. This can happen, for example, if the
1243      * phone has not registered to a network yet. In this case the receiver may substitute an
1244      * appropriate placeholder string (eg, "No service").
1245      *
1246      * It is recommended to display {@link #EXTRA_PLMN} before / above {@link #EXTRA_SPN} if
1247      * both are displayed.
1248      *
1249      * <p>Note: this is a protected intent that can only be sent by the system.
1250      * @hide
1251      */
1252     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1253     public static final String ACTION_SERVICE_PROVIDERS_UPDATED =
1254             "android.telephony.action.SERVICE_PROVIDERS_UPDATED";
1255 
1256     /**
1257      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1258      * whether the PLMN should be shown.
1259      * @hide
1260      */
1261     public static final String EXTRA_SHOW_PLMN = "android.telephony.extra.SHOW_PLMN";
1262 
1263     /**
1264      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1265      * the operator name of the registered network.
1266      * @hide
1267      */
1268     public static final String EXTRA_PLMN = "android.telephony.extra.PLMN";
1269 
1270     /**
1271      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1272      * whether the PLMN should be shown.
1273      * @hide
1274      */
1275     public static final String EXTRA_SHOW_SPN = "android.telephony.extra.SHOW_SPN";
1276 
1277     /**
1278      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1279      * the service provider name.
1280      * @hide
1281      */
1282     public static final String EXTRA_SPN = "android.telephony.extra.SPN";
1283 
1284     /**
1285      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1286      * the service provider name for data service.
1287      * @hide
1288      */
1289     public static final String EXTRA_DATA_SPN = "android.telephony.extra.DATA_SPN";
1290 
1291     /**
1292      * Broadcast intent action indicating that when data stall recovery is attempted by Telephony,
1293      * intended for report every data stall recovery step attempted.
1294      *
1295      * <p>
1296      * The {@link #EXTRA_RECOVERY_ACTION} extra indicates the action associated with the data
1297      * stall recovery.
1298      * The phone id where the data stall recovery is attempted.
1299      *
1300      * <p class="note">
1301      * Requires the READ_PHONE_STATE permission.
1302      *
1303      * <p class="note">
1304      * This is a protected intent that can only be sent by the system.
1305      *
1306      * @see #EXTRA_RECOVERY_ACTION
1307      *
1308      * @hide
1309      */
1310     // TODO(b/78370030) : Restrict this to system applications only
1311     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1312     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1313     public static final String ACTION_DATA_STALL_DETECTED =
1314             "android.intent.action.DATA_STALL_DETECTED";
1315 
1316     /**
1317      * A service action that identifies
1318      * a {@link android.service.carrier.CarrierMessagingClientService} subclass in the
1319      * AndroidManifest.xml.
1320      *
1321      * <p>See {@link android.service.carrier.CarrierMessagingClientService} for the details.
1322      */
1323     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1324     public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE =
1325             "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
1326 
1327     /**
1328      * An int extra used with {@link #ACTION_DATA_STALL_DETECTED} to indicate the
1329      * action associated with the data stall recovery.
1330      *
1331      * @see #ACTION_DATA_STALL_DETECTED
1332      *
1333      * @hide
1334      */
1335     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
1336 
1337     private static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000;
1338 
1339     /**
1340      * Intent sent when an error occurs that debug tools should log and possibly take further
1341      * action such as capturing vendor-specific logs.
1342      *
1343      * A privileged application that reads these events should take appropriate vendor-specific
1344      * action to record the event and collect further information to assist in analysis, debugging,
1345      * and resolution of any associated issue.
1346      *
1347      * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
1348      * should generally be sent at a low rate. Instead, this mechanism should be used for the
1349      * framework to notify a debugging application that an event (such as a bug) has occured
1350      * within the framework if that event should trigger the collection and preservation of other
1351      * more detailed device state for debugging.
1352      *
1353      * <p>At most one application can receive these events and should register a receiver in
1354      * in the application manifest. For performance reasons, if no application to receive these
1355      * events is detected at boot, then these events will not be sent.
1356      *
1357      * <p>Each event will include an {@link EXTRA_ANOMALY_ID} that will uniquely identify the
1358      * event that has occurred. Each event will be sent to the diagnostic monitor only once per
1359      * boot cycle (as another optimization).
1360      *
1361      * @see #EXTRA_ANOMALY_ID
1362      * @see #EXTRA_ANOMALY_DESCRIPTION
1363      * @hide
1364      */
1365     @SystemApi
1366     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1367     public static final String ACTION_ANOMALY_REPORTED =
1368             "android.telephony.action.ANOMALY_REPORTED";
1369 
1370     /**
1371      * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
1372      *
1373      * This field must be included in all {@link ACTION_ANOMALY_REPORTED} events.
1374      *
1375      * @see #ACTION_ANOMALY_REPORTED
1376      * @hide
1377      */
1378     @SystemApi
1379     public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
1380 
1381     /**
1382      * A freeform string description of the Anomaly.
1383      *
1384      * This field is optional for all {@link ACTION_ANOMALY_REPORTED}s, as a guideline should not
1385      * exceed 80 characters, and should be as short as possible to convey the essence of the event.
1386      *
1387      * @see #ACTION_ANOMALY_REPORTED
1388      * @hide
1389      */
1390     @SystemApi
1391     public static final String EXTRA_ANOMALY_DESCRIPTION =
1392             "android.telephony.extra.ANOMALY_DESCRIPTION";
1393 
1394     /**
1395      * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
1396      *
1397      * @hide
1398      */
1399     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1400     public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
1401             "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
1402 
1403     /**
1404      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1405      * to indicate what type of SIM selection is needed.
1406      *
1407      * @hide
1408      */
1409     public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
1410             "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
1411 
1412     /** @hide */
1413     @IntDef({
1414             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE,
1415             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
1416             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE,
1417             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS,
1418             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL
1419     })
1420     @Retention(RetentionPolicy.SOURCE)
1421     public @interface DefaultSubscriptionSelectType{}
1422 
1423     /**
1424      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1425      * to indicate there's no need to re-select any default subscription.
1426      * @hide
1427      */
1428     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
1429 
1430     /**
1431      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1432      * to indicate there's a need to select default data subscription.
1433      * @hide
1434      */
1435     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
1436 
1437     /**
1438      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1439      * to indicate there's a need to select default voice call subscription.
1440      * @hide
1441      */
1442     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
1443 
1444     /**
1445      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1446      * to indicate there's a need to select default sms subscription.
1447      * @hide
1448      */
1449     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
1450 
1451     /**
1452      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1453      * to indicate user to decide whether current SIM should be preferred for all
1454      * data / voice / sms. {@link #EXTRA_SUBSCRIPTION_ID} will specified to indicate
1455      * which subscription should be the default subscription.
1456      * @hide
1457      */
1458     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL = 4;
1459 
1460     /**
1461      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1462      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1463      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1464      *
1465      * @hide
1466      */
1467     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1468             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1469 
1470     /** @hide */
1471     @IntDef({
1472             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1473             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1474     })
1475     @Retention(RetentionPolicy.SOURCE)
1476     public @interface SimCombinationWarningType{}
1477 
1478     /**
1479      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1480      * to indicate there's no SIM combination warning.
1481      * @hide
1482      */
1483     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1484 
1485     /**
1486      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1487      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1488      * @hide
1489      */
1490     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1491 
1492     /**
1493      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1494      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1495      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1496      * name will be "operator1 & operator2".
1497      *
1498      * @hide
1499      */
1500     public static final String EXTRA_SIM_COMBINATION_NAMES =
1501             "android.telephony.extra.SIM_COMBINATION_NAMES";
1502 
1503     /**
1504      * <p>Broadcast Action: The emergency callback mode is changed.
1505      * <ul>
1506      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1507      *   false=ECM off</li>
1508      * </ul>
1509      * <p class="note">
1510      * You can <em>not</em> receive this through components declared
1511      * in manifests, only by explicitly registering for it with
1512      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1513      * android.content.IntentFilter) Context.registerReceiver()}.
1514      *
1515      * <p class="note">This is a protected intent that can only be sent by the system.
1516      *
1517      * @see #EXTRA_PHONE_IN_ECM_STATE
1518      *
1519      * @hide
1520      */
1521     @SystemApi
1522     @SuppressLint("ActionValue")
1523     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1524             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1525 
1526 
1527     /**
1528      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1529      * Indicates whether the phone is in an emergency phone state.
1530      *
1531      * @hide
1532      */
1533     @SystemApi
1534     public static final String EXTRA_PHONE_IN_ECM_STATE =
1535             "android.telephony.extra.PHONE_IN_ECM_STATE";
1536 
1537     /**
1538      * <p>Broadcast Action: when data connections get redirected with validation failure.
1539      * intended for sim/account status checks and only sent to the specified carrier app
1540      * The intent will have the following extra values:</p>
1541      * <ul>
1542      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1543      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1544      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>redirection url string</dd>
1545      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1546      * </ul>
1547      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1548      * @hide
1549      */
1550     @SystemApi
1551     @SuppressLint("ActionValue")
1552     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1553             "com.android.internal.telephony.CARRIER_SIGNAL_REDIRECTED";
1554 
1555     /**
1556      * <p>Broadcast Action: when data connections setup fails.
1557      * intended for sim/account status checks and only sent to the specified carrier app
1558      * The intent will have the following extra values:</p>
1559      * <ul>
1560      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1561      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1562      *   <li>{@link #EXTRA_ERROR_CODE}</li><dd>A integer with dataFailCause.</dd>
1563      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1564      * </ul>
1565      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1566      * @hide
1567      */
1568     @SystemApi
1569     @SuppressLint("ActionValue")
1570     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1571             "com.android.internal.telephony.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1572 
1573     /**
1574      * <p>Broadcast Action: when pco value is available.
1575      * intended for sim/account status checks and only sent to the specified carrier app
1576      * The intent will have the following extra values:</p>
1577      * <ul>
1578      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>A string with the apn type.</dd>
1579      *   <li>{@link #EXTRA_APN_TYPE_INT}</li><dd>A integer with the apn type.</dd>
1580      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>A string with the protocol of the apn connection
1581      *      (IP,IPV6, IPV4V6)</dd>
1582      *   <li>{@link #EXTRA_APN_PROTOCOL_INT}</li><dd>A integer with the protocol of the apn
1583      *      connection (IP,IPV6, IPV4V6)</dd>
1584      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the pco id for the data.</dd>
1585      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of pco data read from modem.</dd>
1586      *   <li>subId</li><dd>Sub Id which associated the data connection.</dd>
1587      * </ul>
1588      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1589      * @hide
1590      */
1591     @SystemApi
1592     @SuppressLint("ActionValue")
1593     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1594             "com.android.internal.telephony.CARRIER_SIGNAL_PCO_VALUE";
1595 
1596     /**
1597      * <p>Broadcast Action: when system default network available/unavailable with
1598      * carrier-disabled mobile data. Intended for carrier apps to set/reset carrier actions when
1599      * other network becomes system default network, Wi-Fi for example.
1600      * The intent will have the following extra values:</p>
1601      * <ul>
1602      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1603      *   <dd>A boolean indicates default network available.</dd>
1604      *   <li>subId</li><dd>Sub Id which associated the default data.</dd>
1605      * </ul>
1606      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1607      * @hide
1608      */
1609     @SystemApi
1610     @SuppressLint("ActionValue")
1611     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1612             "com.android.internal.telephony.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1613 
1614     /**
1615      * <p>Broadcast Action: when framework reset all carrier actions on sim load or absent.
1616      * intended for carrier apps clean up (clear UI e.g.) and only sent to the specified carrier app
1617      * The intent will have the following extra values:</p>
1618      * <ul>
1619      *   <li>subId</li><dd>Sub Id which associated the data connection failure.</dd>
1620      * </ul>
1621      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1622      * @hide
1623      */
1624     @SystemApi
1625     @SuppressLint("ActionValue")
1626     public static final String ACTION_CARRIER_SIGNAL_RESET =
1627             "com.android.internal.telephony.CARRIER_SIGNAL_RESET";
1628 
1629     // CARRIER_SIGNAL_ACTION extra keys
1630     /**
1631      *  An string extra of redirected url upon {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
1632      *  @hide
1633      */
1634     @SystemApi
1635     @SuppressLint("ActionValue")
1636     public static final String EXTRA_REDIRECTION_URL = "redirectionUrl";
1637 
1638     /**
1639      *  An integer extra of error code upon {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}.
1640      *  Check {@link DataFailCause} for all possible values.
1641      *  @hide
1642      */
1643     @SystemApi
1644     @SuppressLint("ActionValue")
1645     public static final String EXTRA_ERROR_CODE = "errorCode";
1646 
1647     /**
1648      *  An string extra of corresponding apn type upon
1649      *  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1650      *  {@link #ACTION_CARRIER_SIGNAL_REDIRECTED} and
1651      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1652      *  @deprecated This is kept for backward compatibility reason. Use {@link #EXTRA_APN_TYPE_INT}
1653      *  instead.
1654      *
1655      *  @hide
1656      */
1657     @SystemApi
1658     @Deprecated
1659     @SuppressLint("ActionValue")
1660     public static final String EXTRA_APN_TYPE = "apnType";
1661 
1662     /**
1663      *  An string integer of corresponding apn type upon
1664      *  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1665      *  {@link #ACTION_CARRIER_SIGNAL_REDIRECTED} and
1666      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1667      *  Check {@link ApnSetting} TYPE_* for its values.
1668      *  @hide
1669      */
1670     @SystemApi
1671     @SuppressLint("ActionValue")
1672     public static final String EXTRA_APN_TYPE_INT = "apnTypeInt";
1673 
1674     /**
1675      *  An string extra with the protocol of the apn connection (IP,IPV6, IPV4V6) upon
1676      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1677      *  @deprecated This is kept for backward compatibility reason.
1678      *  Use {@link #EXTRA_APN_PROTOCOL_INT} instead.
1679      *
1680      *  @hide
1681      */
1682     @SystemApi
1683     @Deprecated
1684     @SuppressLint("ActionValue")
1685     public static final String EXTRA_APN_PROTOCOL = "apnProto";
1686 
1687     /**
1688      *  An integer extra with the protocol of the apn connection (IP,IPV6, IPV4V6) upon
1689      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1690      *  Check {@link ApnSetting} PROTOCOL_* for its values.
1691      *  @hide
1692      */
1693     @SystemApi
1694     @SuppressLint("ActionValue")
1695     public static final String EXTRA_APN_PROTOCOL_INT = "apnProtoInt";
1696 
1697     /**
1698      *  An integer extra indicating the pco id for the data upon
1699      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1700      *  @hide
1701      */
1702     @SystemApi
1703     @SuppressLint("ActionValue")
1704     public static final String EXTRA_PCO_ID = "pcoId";
1705 
1706     /**
1707      *  An extra of byte array of pco data read from modem upon
1708      *  {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcasts.
1709      *  @hide
1710      */
1711     @SystemApi
1712     @SuppressLint("ActionValue")
1713     public static final String EXTRA_PCO_VALUE = "pcoValue";
1714 
1715     /**
1716      *  An boolean extra indicating default network available upon
1717      *  {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcasts.
1718      *  @hide
1719      */
1720     @SystemApi
1721     @SuppressLint("ActionValue")
1722     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE = "defaultNetworkAvailable";
1723 
1724     /**
1725      * <p>Broadcast Action: The emergency call state is changed.
1726      * <ul>
1727      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
1728      *   call, false otherwise</li>
1729      * </ul>
1730      * <p class="note">
1731      * You can <em>not</em> receive this through components declared
1732      * in manifests, only by explicitly registering for it with
1733      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1734      * android.content.IntentFilter) Context.registerReceiver()}.
1735      *
1736      * <p class="note">This is a protected intent that can only be sent by the system.
1737      *
1738      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
1739      *
1740      * @hide
1741      */
1742     @SystemApi
1743     @SuppressLint("ActionValue")
1744     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
1745             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
1746 
1747 
1748     /**
1749      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
1750      * It indicates whether the phone is making an emergency call.
1751      *
1752      * @hide
1753      */
1754     @SystemApi
1755     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
1756             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
1757 
1758     //
1759     //
1760     // Device Info
1761     //
1762     //
1763 
1764     /**
1765      * Returns the software version number for the device, for example,
1766      * the IMEI/SV for GSM phones. Return null if the software version is
1767      * not available.
1768      * <p>
1769      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}.
1770      */
1771     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1772     @Nullable
getDeviceSoftwareVersion()1773     public String getDeviceSoftwareVersion() {
1774         return getDeviceSoftwareVersion(getSlotIndex());
1775     }
1776 
1777     /**
1778      * Returns the software version number for the device, for example,
1779      * the IMEI/SV for GSM phones. Return null if the software version is
1780      * not available.
1781      * <p>
1782      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
1783      *
1784      * @param slotIndex of which deviceID is returned
1785      *
1786      * @hide
1787      */
1788     @SystemApi
1789     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1790     @Nullable
getDeviceSoftwareVersion(int slotIndex)1791     public String getDeviceSoftwareVersion(int slotIndex) {
1792         ITelephony telephony = getITelephony();
1793         if (telephony == null) return null;
1794 
1795         try {
1796             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
1797                     getFeatureId());
1798         } catch (RemoteException ex) {
1799             return null;
1800         } catch (NullPointerException ex) {
1801             return null;
1802         }
1803     }
1804 
1805     /**
1806      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
1807      * or ESN for CDMA phones. Return null if device ID is not available.
1808      *
1809      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
1810      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
1811      * privileges (see {@link #hasCarrierPrivileges}) on any active subscription. The profile owner
1812      * is an app that owns a managed profile on the device; for more details see <a
1813      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
1814      * access is deprecated and will be removed in a future release.
1815      *
1816      * <p>If the calling app does not meet one of these requirements then this method will behave
1817      * as follows:
1818      *
1819      * <ul>
1820      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1821      *     READ_PHONE_STATE permission then null is returned.</li>
1822      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1823      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1824      *     higher, then a SecurityException is thrown.</li>
1825      * </ul>
1826      *
1827      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1828      * MEID for CDMA.
1829      */
1830     @Deprecated
1831     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1832     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()1833     public String getDeviceId() {
1834         try {
1835             ITelephony telephony = getITelephony();
1836             if (telephony == null)
1837                 return null;
1838             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
1839                     null);
1840         } catch (RemoteException ex) {
1841             return null;
1842         } catch (NullPointerException ex) {
1843             return null;
1844         }
1845     }
1846 
1847     /**
1848      * Returns the unique device ID of a subscription, for example, the IMEI for
1849      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
1850      *
1851      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
1852      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
1853      * privileges (see {@link #hasCarrierPrivileges}) on any active subscription. The profile owner
1854      * is an app that owns a managed profile on the device; for more details see <a
1855      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
1856      * access is deprecated and will be removed in a future release.
1857      *
1858      * <p>If the calling app does not meet one of these requirements then this method will behave
1859      * as follows:
1860      *
1861      * <ul>
1862      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1863      *     READ_PHONE_STATE permission then null is returned.</li>
1864      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1865      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1866      *     higher, then a SecurityException is thrown.</li>
1867      * </ul>
1868      *
1869      * @param slotIndex of which deviceID is returned
1870      *
1871      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1872      * MEID for CDMA.
1873      */
1874     @Deprecated
1875     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1876     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)1877     public String getDeviceId(int slotIndex) {
1878         // FIXME this assumes phoneId == slotIndex
1879         try {
1880             IPhoneSubInfo info = getSubscriberInfo();
1881             if (info == null)
1882                 return null;
1883             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
1884                     null);
1885         } catch (RemoteException ex) {
1886             return null;
1887         } catch (NullPointerException ex) {
1888             return null;
1889         }
1890     }
1891 
1892     /**
1893      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
1894      * available.
1895      *
1896      * See {@link #getImei(int)} for details on the required permissions and behavior
1897      * when the caller does not hold sufficient permissions.
1898      */
1899     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1900     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei()1901     public String getImei() {
1902         return getImei(getSlotIndex());
1903     }
1904 
1905     /**
1906      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
1907      * available.
1908      *
1909      * <p>This API requires one of the following:
1910      * <ul>
1911      *     <li>The caller holds the READ_PRIVILEGED_PHONE_STATE permission.</li>
1912      *     <li>If the caller is the device or profile owner, the caller holds the
1913      *     {@link Manifest.permission#READ_PHONE_STATE} permission.</li>
1914      *     <li>The caller has carrier privileges (see {@link #hasCarrierPrivileges()} on any
1915      *     active subscription.</li>
1916      *     <li>The caller is the default SMS app for the device.</li>
1917      * </ul>
1918      * <p>The profile owner is an app that owns a managed profile on the device; for more details
1919      * see <a href="https://developer.android.com/work/managed-profiles">Work profiles</a>.
1920      * Access by profile owners is deprecated and will be removed in a future release.
1921      *
1922      * <p>If the calling app does not meet one of these requirements then this method will behave
1923      * as follows:
1924      *
1925      * <ul>
1926      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1927      *     READ_PHONE_STATE permission then null is returned.</li>
1928      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1929      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1930      *     higher, then a SecurityException is thrown.</li>
1931      * </ul>
1932      *
1933      * @param slotIndex of which IMEI is returned
1934      */
1935     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1936     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei(int slotIndex)1937     public String getImei(int slotIndex) {
1938         ITelephony telephony = getITelephony();
1939         if (telephony == null) return null;
1940 
1941         try {
1942             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getFeatureId());
1943         } catch (RemoteException ex) {
1944             return null;
1945         } catch (NullPointerException ex) {
1946             return null;
1947         }
1948     }
1949 
1950     /**
1951      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
1952      * available.
1953      */
1954     @Nullable
getTypeAllocationCode()1955     public String getTypeAllocationCode() {
1956         return getTypeAllocationCode(getSlotIndex());
1957     }
1958 
1959     /**
1960      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
1961      * available.
1962      *
1963      * @param slotIndex of which Type Allocation Code is returned
1964      */
1965     @Nullable
getTypeAllocationCode(int slotIndex)1966     public String getTypeAllocationCode(int slotIndex) {
1967         ITelephony telephony = getITelephony();
1968         if (telephony == null) return null;
1969 
1970         try {
1971             return telephony.getTypeAllocationCodeForSlot(slotIndex);
1972         } catch (RemoteException ex) {
1973             return null;
1974         } catch (NullPointerException ex) {
1975             return null;
1976         }
1977     }
1978 
1979     /**
1980      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
1981      *
1982      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
1983      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
1984      * privileges (see {@link #hasCarrierPrivileges}) on any active subscription. The profile owner
1985      * is an app that owns a managed profile on the device; for more details see <a
1986      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
1987      * access is deprecated and will be removed in a future release.
1988      *
1989      * <p>If the calling app does not meet one of these requirements then this method will behave
1990      * as follows:
1991      *
1992      * <ul>
1993      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1994      *     READ_PHONE_STATE permission then null is returned.</li>
1995      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1996      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1997      *     higher, then a SecurityException is thrown.</li>
1998      * </ul>
1999      */
2000     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2001     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid()2002     public String getMeid() {
2003         return getMeid(getSlotIndex());
2004     }
2005 
2006     /**
2007      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2008      *
2009      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
2010      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
2011      * privileges (see {@link #hasCarrierPrivileges}) on any active subscription. The profile owner
2012      * is an app that owns a managed profile on the device; for more details see <a
2013      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
2014      * access is deprecated and will be removed in a future release.
2015      *
2016      * <p>If the calling app does not meet one of these requirements then this method will behave
2017      * as follows:
2018      *
2019      * <ul>
2020      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2021      *     READ_PHONE_STATE permission then null is returned.</li>
2022      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2023      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2024      *     higher, then a SecurityException is thrown.</li>
2025      * </ul>
2026      *
2027      * @param slotIndex of which MEID is returned
2028      */
2029     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2030     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid(int slotIndex)2031     public String getMeid(int slotIndex) {
2032         ITelephony telephony = getITelephony();
2033         if (telephony == null) return null;
2034 
2035         try {
2036             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(), getFeatureId());
2037             if (TextUtils.isEmpty(meid)) {
2038                 Log.d(TAG, "getMeid: return null because MEID is not available");
2039                 return null;
2040             }
2041             return meid;
2042         } catch (RemoteException ex) {
2043             return null;
2044         } catch (NullPointerException ex) {
2045             return null;
2046         }
2047     }
2048 
2049     /**
2050      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2051      * available.
2052      */
2053     @Nullable
getManufacturerCode()2054     public String getManufacturerCode() {
2055         return getManufacturerCode(getSlotIndex());
2056     }
2057 
2058     /**
2059      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2060      * available.
2061      *
2062      * @param slotIndex of which Type Allocation Code is returned
2063      */
2064     @Nullable
getManufacturerCode(int slotIndex)2065     public String getManufacturerCode(int slotIndex) {
2066         ITelephony telephony = getITelephony();
2067         if (telephony == null) return null;
2068 
2069         try {
2070             return telephony.getManufacturerCodeForSlot(slotIndex);
2071         } catch (RemoteException ex) {
2072             return null;
2073         } catch (NullPointerException ex) {
2074             return null;
2075         }
2076     }
2077 
2078     /**
2079      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2080      *
2081      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
2082      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
2083      * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
2084      * managed profile on the device; for more details see <a
2085      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
2086      * access is deprecated and will be removed in a future release.
2087      *
2088      * <ul>
2089      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2090      *     READ_PHONE_STATE permission then null is returned.</li>
2091      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2092      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2093      *     higher, then a SecurityException is thrown.</li>
2094      * </ul>
2095      */
2096     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2097     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNai()2098     public String getNai() {
2099         return getNaiBySubscriberId(getSubId());
2100     }
2101 
2102     /**
2103      * Returns the NAI. Return null if NAI is not available.
2104      *
2105      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
2106      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
2107      * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
2108      * managed profile on the device; for more details see <a
2109      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
2110      * access is deprecated and will be removed in a future release.
2111      *
2112      * <ul>
2113      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2114      *     READ_PHONE_STATE permission then null is returned.</li>
2115      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2116      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2117      *     higher, then a SecurityException is thrown.</li>
2118      * </ul>
2119      *
2120      *  @param slotIndex of which Nai is returned
2121      */
2122     /** {@hide}*/
2123     @UnsupportedAppUsage
getNai(int slotIndex)2124     public String getNai(int slotIndex) {
2125         int[] subId = SubscriptionManager.getSubId(slotIndex);
2126         if (subId == null) {
2127             return null;
2128         }
2129         return getNaiBySubscriberId(subId[0]);
2130     }
2131 
getNaiBySubscriberId(int subId)2132     private String getNaiBySubscriberId(int subId) {
2133         try {
2134             IPhoneSubInfo info = getSubscriberInfo();
2135             if (info == null)
2136                 return null;
2137             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2138                     null);
2139             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2140                 Rlog.v(TAG, "Nai = " + nai);
2141             }
2142             return nai;
2143         } catch (RemoteException ex) {
2144             return null;
2145         } catch (NullPointerException ex) {
2146             return null;
2147         }
2148     }
2149 
2150     /**
2151      * Returns the current location of the device.
2152      *<p>
2153      * If there is only one radio in the device and that radio has an LTE connection,
2154      * this method will return null. The implementation must not to try add LTE
2155      * identifiers into the existing cdma/gsm classes.
2156      *<p>
2157      * @return Current location of the device or null if not available.
2158      *
2159      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2160      */
2161     @Deprecated
2162     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getCellLocation()2163     public CellLocation getCellLocation() {
2164         try {
2165             ITelephony telephony = getITelephony();
2166             if (telephony == null) {
2167                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2168                 return null;
2169             }
2170 
2171             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2172                     null);
2173             CellLocation cl = cellIdentity.asCellLocation();
2174             if (cl == null || cl.isEmpty()) {
2175                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2176                         + " phone type doesn't match CellLocation type");
2177                 return null;
2178             }
2179 
2180             return cl;
2181         } catch (RemoteException ex) {
2182             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2183             return null;
2184         }
2185     }
2186 
2187     /**
2188      * Returns the neighboring cell information of the device.
2189      *
2190      * @return List of NeighboringCellInfo or null if info unavailable.
2191      *
2192      * @removed
2193      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2194      *             from NeighboringCellInfo, including LTE cell information.
2195      */
2196     @Deprecated
2197     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
getNeighboringCellInfo()2198     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2199         try {
2200             ITelephony telephony = getITelephony();
2201             if (telephony == null)
2202                 return null;
2203             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2204                     null);
2205         } catch (RemoteException ex) {
2206             return null;
2207         } catch (NullPointerException ex) {
2208             return null;
2209         }
2210     }
2211 
2212     /** No phone radio. */
2213     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2214     /** Phone radio is GSM. */
2215     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2216     /** Phone radio is CDMA. */
2217     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2218     /** Phone is via SIP. */
2219     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2220 
2221     /**
2222      * Phone is via IMS.
2223      *
2224      * @hide
2225      */
2226     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2227 
2228     /**
2229      * Phone is via Third Party.
2230      *
2231      * @hide
2232      */
2233     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2234 
2235     /**
2236      * Returns the current phone type.
2237      * TODO: This is a last minute change and hence hidden.
2238      *
2239      * @see #PHONE_TYPE_NONE
2240      * @see #PHONE_TYPE_GSM
2241      * @see #PHONE_TYPE_CDMA
2242      * @see #PHONE_TYPE_SIP
2243      *
2244      * {@hide}
2245      */
2246     @SystemApi
getCurrentPhoneType()2247     public int getCurrentPhoneType() {
2248         return getCurrentPhoneType(getSubId());
2249     }
2250 
2251     /**
2252      * Returns a constant indicating the device phone type for a subscription.
2253      *
2254      * @see #PHONE_TYPE_NONE
2255      * @see #PHONE_TYPE_GSM
2256      * @see #PHONE_TYPE_CDMA
2257      *
2258      * @param subId for which phone type is returned
2259      * @hide
2260      */
2261     @SystemApi
getCurrentPhoneType(int subId)2262     public int getCurrentPhoneType(int subId) {
2263         int phoneId;
2264         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2265             // if we don't have any sims, we don't have subscriptions, but we
2266             // still may want to know what type of phone we've got.
2267             phoneId = 0;
2268         } else {
2269             phoneId = SubscriptionManager.getPhoneId(subId);
2270         }
2271 
2272         return getCurrentPhoneTypeForSlot(phoneId);
2273     }
2274 
2275     /**
2276      * See getCurrentPhoneType.
2277      *
2278      * @hide
2279      */
getCurrentPhoneTypeForSlot(int slotIndex)2280     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2281         try{
2282             ITelephony telephony = getITelephony();
2283             if (telephony != null) {
2284                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2285             } else {
2286                 // This can happen when the ITelephony interface is not up yet.
2287                 return getPhoneTypeFromProperty(slotIndex);
2288             }
2289         } catch (RemoteException ex) {
2290             // This shouldn't happen in the normal case, as a backup we
2291             // read from the system property.
2292             return getPhoneTypeFromProperty(slotIndex);
2293         } catch (NullPointerException ex) {
2294             // This shouldn't happen in the normal case, as a backup we
2295             // read from the system property.
2296             return getPhoneTypeFromProperty(slotIndex);
2297         }
2298     }
2299 
2300     /**
2301      * Returns a constant indicating the device phone type.  This
2302      * indicates the type of radio used to transmit voice calls.
2303      *
2304      * @see #PHONE_TYPE_NONE
2305      * @see #PHONE_TYPE_GSM
2306      * @see #PHONE_TYPE_CDMA
2307      * @see #PHONE_TYPE_SIP
2308      */
getPhoneType()2309     public int getPhoneType() {
2310         if (!isVoiceCapable()) {
2311             return PHONE_TYPE_NONE;
2312         }
2313         return getCurrentPhoneType();
2314     }
2315 
getPhoneTypeFromProperty()2316     private int getPhoneTypeFromProperty() {
2317         return getPhoneTypeFromProperty(getPhoneId());
2318     }
2319 
2320     /** {@hide} */
2321     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2322     private int getPhoneTypeFromProperty(int phoneId) {
2323         Integer type = getTelephonyProperty(
2324                 phoneId, TelephonyProperties.current_active_phone(), null);
2325         if (type != null) return type;
2326         return getPhoneTypeFromNetworkType(phoneId);
2327     }
2328 
getPhoneTypeFromNetworkType()2329     private int getPhoneTypeFromNetworkType() {
2330         return getPhoneTypeFromNetworkType(getPhoneId());
2331     }
2332 
2333     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2334     private int getPhoneTypeFromNetworkType(int phoneId) {
2335         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2336         // use the system property for default network type.
2337         // This is a fail safe, and can only happen at first boot.
2338         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2339         if (mode != null) {
2340             return TelephonyManager.getPhoneType(mode);
2341         }
2342         return TelephonyManager.PHONE_TYPE_NONE;
2343     }
2344 
2345     /**
2346      * This function returns the type of the phone, depending
2347      * on the network mode.
2348      *
2349      * @param networkMode
2350      * @return Phone Type
2351      *
2352      * @hide
2353      */
2354     @UnsupportedAppUsage
getPhoneType(int networkMode)2355     public static int getPhoneType(int networkMode) {
2356         switch(networkMode) {
2357         case RILConstants.NETWORK_MODE_CDMA:
2358         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2359         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2360             return PhoneConstants.PHONE_TYPE_CDMA;
2361 
2362         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2363         case RILConstants.NETWORK_MODE_GSM_ONLY:
2364         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2365         case RILConstants.NETWORK_MODE_GSM_UMTS:
2366         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2367         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2368         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2369         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2370         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2371         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2372         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2373         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2374         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2375         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2376         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2377         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2378             return PhoneConstants.PHONE_TYPE_GSM;
2379 
2380         // Use CDMA Phone for the global mode including CDMA
2381         case RILConstants.NETWORK_MODE_GLOBAL:
2382         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2383         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2384             return PhoneConstants.PHONE_TYPE_CDMA;
2385 
2386         case RILConstants.NETWORK_MODE_LTE_ONLY:
2387             if (TelephonyProperties.lte_on_cdma_device().orElse(
2388                     PhoneConstants.LTE_ON_CDMA_FALSE) == PhoneConstants.LTE_ON_CDMA_TRUE) {
2389                 return PhoneConstants.PHONE_TYPE_CDMA;
2390             } else {
2391                 return PhoneConstants.PHONE_TYPE_GSM;
2392             }
2393         default:
2394             return PhoneConstants.PHONE_TYPE_GSM;
2395         }
2396     }
2397 
2398     /**
2399      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2400      * @hide
2401      */
2402     @SystemApi
getMaxNumberVerificationTimeoutMillis()2403     public static long getMaxNumberVerificationTimeoutMillis() {
2404         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2405     }
2406 
2407     //
2408     //
2409     // Current Network
2410     //
2411     //
2412 
2413     /**
2414      * Returns the alphabetic name of current registered operator.
2415      * <p>
2416      * Availability: Only when user is registered to a network. Result may be
2417      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2418      * on a CDMA network).
2419      */
getNetworkOperatorName()2420     public String getNetworkOperatorName() {
2421         return getNetworkOperatorName(getSubId());
2422     }
2423 
2424     /**
2425      * Returns the alphabetic name of current registered operator
2426      * for a particular subscription.
2427      * <p>
2428      * Availability: Only when user is registered to a network. Result may be
2429      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2430      * on a CDMA network).
2431      * @param subId
2432      * @hide
2433      */
2434     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2435     public String getNetworkOperatorName(int subId) {
2436         int phoneId = SubscriptionManager.getPhoneId(subId);
2437         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2438     }
2439 
2440     /**
2441      * Returns the numeric name (MCC+MNC) of current registered operator.
2442      * <p>
2443      * Availability: Only when user is registered to a network. Result may be
2444      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2445      * on a CDMA network).
2446      */
getNetworkOperator()2447     public String getNetworkOperator() {
2448         return getNetworkOperatorForPhone(getPhoneId());
2449     }
2450 
2451     /**
2452      * Returns the numeric name (MCC+MNC) of current registered operator
2453      * for a particular subscription.
2454      * <p>
2455      * Availability: Only when user is registered to a network. Result may be
2456      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2457      * on a CDMA network).
2458      *
2459      * @param subId
2460      * @hide
2461      */
2462     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2463     public String getNetworkOperator(int subId) {
2464         int phoneId = SubscriptionManager.getPhoneId(subId);
2465         return getNetworkOperatorForPhone(phoneId);
2466      }
2467 
2468     /**
2469      * Returns the numeric name (MCC+MNC) of current registered operator
2470      * for a particular subscription.
2471      * <p>
2472      * Availability: Only when user is registered to a network. Result may be
2473      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2474      * on a CDMA network).
2475      *
2476      * @param phoneId
2477      * @hide
2478      **/
2479     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2480     public String getNetworkOperatorForPhone(int phoneId) {
2481         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2482     }
2483 
2484 
2485     /**
2486      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2487      * network specifier is used by {@link
2488      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2489      * android.net.NetworkRequest} that connects through the subscription.
2490      *
2491      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2492      * @see #createForSubscriptionId(int)
2493      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2494      */
getNetworkSpecifier()2495     public String getNetworkSpecifier() {
2496         return String.valueOf(getSubId());
2497     }
2498 
2499     /**
2500      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
2501      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
2502      * default values.
2503      *
2504      * <p>This method may take several seconds to complete, so it should only be called from a
2505      * worker thread.
2506      *
2507      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2508      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2509      *
2510      * @see CarrierConfigManager#getConfigForSubId(int)
2511      * @see #createForSubscriptionId(int)
2512      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2513      */
2514     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2515     @WorkerThread
2516     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCarrierConfig()2517     public PersistableBundle getCarrierConfig() {
2518         CarrierConfigManager carrierConfigManager = mContext
2519                 .getSystemService(CarrierConfigManager.class);
2520         return carrierConfigManager.getConfigForSubId(getSubId());
2521     }
2522 
2523     /**
2524      * Returns true if the device is considered roaming on the current
2525      * network, for GSM purposes.
2526      * <p>
2527      * Availability: Only when user registered to a network.
2528      */
isNetworkRoaming()2529     public boolean isNetworkRoaming() {
2530         return isNetworkRoaming(getSubId());
2531     }
2532 
2533     /**
2534      * Returns true if the device is considered roaming on the current
2535      * network for a subscription.
2536      * <p>
2537      * Availability: Only when user registered to a network.
2538      *
2539      * @param subId
2540      * @hide
2541      */
2542     @UnsupportedAppUsage
isNetworkRoaming(int subId)2543     public boolean isNetworkRoaming(int subId) {
2544         int phoneId = SubscriptionManager.getPhoneId(subId);
2545         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
2546     }
2547 
2548     /**
2549      * Returns the ISO-3166 country code equivalent of the MCC (Mobile Country Code) of the current
2550      * registered operator or the cell nearby, if available.
2551      *
2552      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2553      * if on a CDMA network).
2554      * <p>
2555      * @return the lowercase 2 character ISO-3166 country code, or empty string if not available.
2556      */
getNetworkCountryIso()2557     public String getNetworkCountryIso() {
2558         return getNetworkCountryIso(getSlotIndex());
2559     }
2560 
2561     /**
2562      * Returns the ISO-3166 country code equivalent of the MCC (Mobile Country Code) of the current
2563      * registered operator or the cell nearby, if available. This is same as
2564      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
2565      * accessing network country info from the SIM slot that does not have SIM inserted.
2566      *
2567      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2568      * if on a CDMA network).
2569      * <p>
2570      *
2571      * @param slotIndex the SIM slot index to get network country ISO.
2572      *
2573      * @return the lowercase 2 character ISO-3166 country code, or empty string if not available.
2574      *
2575      * @throws IllegalArgumentException when the slotIndex is invalid.
2576      *
2577      */
2578     @NonNull
getNetworkCountryIso(int slotIndex)2579     public String getNetworkCountryIso(int slotIndex) {
2580         try {
2581             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
2582                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
2583                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
2584             }
2585 
2586             ITelephony telephony = getITelephony();
2587             if (telephony == null) return "";
2588             return telephony.getNetworkCountryIsoForPhone(slotIndex);
2589         } catch (RemoteException ex) {
2590             return "";
2591         }
2592     }
2593 
2594     /**
2595      * @hide
2596      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
2597      */
2598     @Deprecated
2599     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
2600             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)2601     public String getNetworkCountryIsoForPhone(int phoneId) {
2602         return getNetworkCountryIso(phoneId);
2603     }
2604 
2605     /*
2606      * When adding a network type to the list below, make sure to add the correct icon to
2607      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
2608      * Do not add negative types.
2609      */
2610     /** Network type is unknown */
2611     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
2612     /** Current network is GPRS */
2613     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
2614     /** Current network is EDGE */
2615     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
2616     /** Current network is UMTS */
2617     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
2618     /** Current network is CDMA: Either IS95A or IS95B*/
2619     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
2620     /** Current network is EVDO revision 0*/
2621     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
2622     /** Current network is EVDO revision A*/
2623     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
2624     /** Current network is 1xRTT*/
2625     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
2626     /** Current network is HSDPA */
2627     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
2628     /** Current network is HSUPA */
2629     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
2630     /** Current network is HSPA */
2631     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
2632     /** Current network is iDen */
2633     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
2634     /** Current network is EVDO revision B*/
2635     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
2636     /** Current network is LTE */
2637     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
2638     /** Current network is eHRPD */
2639     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
2640     /** Current network is HSPA+ */
2641     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
2642     /** Current network is GSM */
2643     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
2644     /** Current network is TD_SCDMA */
2645     public static final int NETWORK_TYPE_TD_SCDMA =
2646             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
2647     /** Current network is IWLAN */
2648     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
2649     /** Current network is LTE_CA {@hide} */
2650     @UnsupportedAppUsage
2651     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
2652     /** Current network is NR(New Radio) 5G. */
2653     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
2654 
2655     private static final @NetworkType int[] NETWORK_TYPES = {
2656             NETWORK_TYPE_GPRS,
2657             NETWORK_TYPE_EDGE,
2658             NETWORK_TYPE_UMTS,
2659             NETWORK_TYPE_CDMA,
2660             NETWORK_TYPE_EVDO_0,
2661             NETWORK_TYPE_EVDO_A,
2662             NETWORK_TYPE_1xRTT,
2663             NETWORK_TYPE_HSDPA,
2664             NETWORK_TYPE_HSUPA,
2665             NETWORK_TYPE_HSPA,
2666             NETWORK_TYPE_IDEN,
2667             NETWORK_TYPE_EVDO_B,
2668             NETWORK_TYPE_LTE,
2669             NETWORK_TYPE_EHRPD,
2670             NETWORK_TYPE_HSPAP,
2671             NETWORK_TYPE_GSM,
2672             NETWORK_TYPE_TD_SCDMA,
2673             NETWORK_TYPE_IWLAN,
2674             NETWORK_TYPE_LTE_CA,
2675             NETWORK_TYPE_NR
2676     };
2677 
2678     /**
2679      * Return a collection of all network types
2680      * @return network types
2681      */
getAllNetworkTypes()2682     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
2683         return NETWORK_TYPES;
2684     }
2685 
2686     /**
2687      * Return the current data network type.
2688      *
2689      * @deprecated use {@link #getDataNetworkType()}
2690      * @return the NETWORK_TYPE_xxxx for current data connection.
2691      */
2692     @Deprecated
2693     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNetworkType()2694     public @NetworkType int getNetworkType() {
2695         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
2696     }
2697 
2698     /**
2699      * Returns a constant indicating the radio technology (network type)
2700      * currently in use on the device for a subscription.
2701      * @return the network type
2702      *
2703      * @param subId for which network type is returned
2704      *
2705      * @see #NETWORK_TYPE_UNKNOWN
2706      * @see #NETWORK_TYPE_GPRS
2707      * @see #NETWORK_TYPE_EDGE
2708      * @see #NETWORK_TYPE_UMTS
2709      * @see #NETWORK_TYPE_HSDPA
2710      * @see #NETWORK_TYPE_HSUPA
2711      * @see #NETWORK_TYPE_HSPA
2712      * @see #NETWORK_TYPE_CDMA
2713      * @see #NETWORK_TYPE_EVDO_0
2714      * @see #NETWORK_TYPE_EVDO_A
2715      * @see #NETWORK_TYPE_EVDO_B
2716      * @see #NETWORK_TYPE_1xRTT
2717      * @see #NETWORK_TYPE_IDEN
2718      * @see #NETWORK_TYPE_LTE
2719      * @see #NETWORK_TYPE_EHRPD
2720      * @see #NETWORK_TYPE_HSPAP
2721      * @see #NETWORK_TYPE_NR
2722      *
2723      * @hide
2724      */
2725     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2726     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)2727     public int getNetworkType(int subId) {
2728         try {
2729             ITelephony telephony = getITelephony();
2730             if (telephony != null) {
2731                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
2732                         getFeatureId());
2733             } else {
2734                 // This can happen when the ITelephony interface is not up yet.
2735                 return NETWORK_TYPE_UNKNOWN;
2736             }
2737         } catch (RemoteException ex) {
2738             // This shouldn't happen in the normal case
2739             return NETWORK_TYPE_UNKNOWN;
2740         } catch (NullPointerException ex) {
2741             // This could happen before phone restarts due to crashing
2742             return NETWORK_TYPE_UNKNOWN;
2743         }
2744     }
2745 
2746     /**
2747      * Returns a constant indicating the radio technology (network type)
2748      * currently in use on the device for data transmission.
2749      *
2750      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
2751      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
2752      *
2753      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2754      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2755      *
2756      * @return the network type
2757      *
2758      * @see #NETWORK_TYPE_UNKNOWN
2759      * @see #NETWORK_TYPE_GPRS
2760      * @see #NETWORK_TYPE_EDGE
2761      * @see #NETWORK_TYPE_UMTS
2762      * @see #NETWORK_TYPE_HSDPA
2763      * @see #NETWORK_TYPE_HSUPA
2764      * @see #NETWORK_TYPE_HSPA
2765      * @see #NETWORK_TYPE_CDMA
2766      * @see #NETWORK_TYPE_EVDO_0
2767      * @see #NETWORK_TYPE_EVDO_A
2768      * @see #NETWORK_TYPE_EVDO_B
2769      * @see #NETWORK_TYPE_1xRTT
2770      * @see #NETWORK_TYPE_IDEN
2771      * @see #NETWORK_TYPE_LTE
2772      * @see #NETWORK_TYPE_EHRPD
2773      * @see #NETWORK_TYPE_HSPAP
2774      * @see #NETWORK_TYPE_NR
2775      */
2776     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2777     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getDataNetworkType()2778     public @NetworkType int getDataNetworkType() {
2779         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
2780     }
2781 
2782     /**
2783      * Returns a constant indicating the radio technology (network type)
2784      * currently in use on the device for data transmission for a subscription
2785      * @return the network type
2786      *
2787      * @param subId for which network type is returned
2788      * @hide
2789      */
2790     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2791     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)2792     public int getDataNetworkType(int subId) {
2793         try{
2794             ITelephony telephony = getITelephony();
2795             if (telephony != null) {
2796                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
2797                         getFeatureId());
2798             } else {
2799                 // This can happen when the ITelephony interface is not up yet.
2800                 return NETWORK_TYPE_UNKNOWN;
2801             }
2802         } catch(RemoteException ex) {
2803             // This shouldn't happen in the normal case
2804             return NETWORK_TYPE_UNKNOWN;
2805         } catch (NullPointerException ex) {
2806             // This could happen before phone restarts due to crashing
2807             return NETWORK_TYPE_UNKNOWN;
2808         }
2809     }
2810 
2811     /**
2812      * Returns the NETWORK_TYPE_xxxx for voice
2813      *
2814      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2815      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2816      */
2817     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2818     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceNetworkType()2819     public @NetworkType int getVoiceNetworkType() {
2820         return getVoiceNetworkType(getSubId());
2821     }
2822 
2823     /**
2824      * Returns the NETWORK_TYPE_xxxx for voice for a subId
2825      * @hide
2826      */
2827     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2828     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)2829     public int getVoiceNetworkType(int subId) {
2830         try{
2831             ITelephony telephony = getITelephony();
2832             if (telephony != null) {
2833                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
2834                         getFeatureId());
2835             } else {
2836                 // This can happen when the ITelephony interface is not up yet.
2837                 return NETWORK_TYPE_UNKNOWN;
2838             }
2839         } catch(RemoteException ex) {
2840             // This shouldn't happen in the normal case
2841             return NETWORK_TYPE_UNKNOWN;
2842         } catch (NullPointerException ex) {
2843             // This could happen before phone restarts due to crashing
2844             return NETWORK_TYPE_UNKNOWN;
2845         }
2846     }
2847 
2848     /**
2849      * Returns a string representation of the radio technology (network type)
2850      * currently in use on the device.
2851      * @return the name of the radio technology
2852      *
2853      * @hide pending API council review
2854      */
2855     @UnsupportedAppUsage
getNetworkTypeName()2856     public String getNetworkTypeName() {
2857         return getNetworkTypeName(getNetworkType());
2858     }
2859 
2860     /**
2861      * Returns a string representation of the radio technology (network type)
2862      * currently in use on the device.
2863      * @param subId for which network type is returned
2864      * @return the name of the radio technology
2865      *
2866      */
2867     /** {@hide} */
2868     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)2869     public static String getNetworkTypeName(@NetworkType int type) {
2870         switch (type) {
2871             case NETWORK_TYPE_GPRS:
2872                 return "GPRS";
2873             case NETWORK_TYPE_EDGE:
2874                 return "EDGE";
2875             case NETWORK_TYPE_UMTS:
2876                 return "UMTS";
2877             case NETWORK_TYPE_HSDPA:
2878                 return "HSDPA";
2879             case NETWORK_TYPE_HSUPA:
2880                 return "HSUPA";
2881             case NETWORK_TYPE_HSPA:
2882                 return "HSPA";
2883             case NETWORK_TYPE_CDMA:
2884                 return "CDMA";
2885             case NETWORK_TYPE_EVDO_0:
2886                 return "CDMA - EvDo rev. 0";
2887             case NETWORK_TYPE_EVDO_A:
2888                 return "CDMA - EvDo rev. A";
2889             case NETWORK_TYPE_EVDO_B:
2890                 return "CDMA - EvDo rev. B";
2891             case NETWORK_TYPE_1xRTT:
2892                 return "CDMA - 1xRTT";
2893             case NETWORK_TYPE_LTE:
2894                 return "LTE";
2895             case NETWORK_TYPE_EHRPD:
2896                 return "CDMA - eHRPD";
2897             case NETWORK_TYPE_IDEN:
2898                 return "iDEN";
2899             case NETWORK_TYPE_HSPAP:
2900                 return "HSPA+";
2901             case NETWORK_TYPE_GSM:
2902                 return "GSM";
2903             case NETWORK_TYPE_TD_SCDMA:
2904                 return "TD_SCDMA";
2905             case NETWORK_TYPE_IWLAN:
2906                 return "IWLAN";
2907             case NETWORK_TYPE_LTE_CA:
2908                 return "LTE_CA";
2909             case NETWORK_TYPE_NR:
2910                 return "NR";
2911             default:
2912                 return "UNKNOWN";
2913         }
2914     }
2915 
2916     /**
2917      * Returns the bitmask for a given technology (network type)
2918      * @param networkType for which bitmask is returned
2919      * @return the network type bitmask
2920      * {@hide}
2921      */
getBitMaskForNetworkType(@etworkType int networkType)2922     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
2923         switch(networkType) {
2924             case NETWORK_TYPE_GSM:
2925                 return NETWORK_TYPE_BITMASK_GSM;
2926             case NETWORK_TYPE_GPRS:
2927                 return NETWORK_TYPE_BITMASK_GPRS;
2928             case NETWORK_TYPE_EDGE:
2929                 return NETWORK_TYPE_BITMASK_EDGE;
2930             case NETWORK_TYPE_CDMA:
2931                 return NETWORK_TYPE_BITMASK_CDMA;
2932             case NETWORK_TYPE_1xRTT:
2933                 return NETWORK_TYPE_BITMASK_1xRTT;
2934             case NETWORK_TYPE_EVDO_0:
2935                 return NETWORK_TYPE_BITMASK_EVDO_0;
2936             case NETWORK_TYPE_EVDO_A:
2937                 return NETWORK_TYPE_BITMASK_EVDO_A;
2938             case NETWORK_TYPE_EVDO_B:
2939                 return NETWORK_TYPE_BITMASK_EVDO_B;
2940             case NETWORK_TYPE_EHRPD:
2941                 return NETWORK_TYPE_BITMASK_EHRPD;
2942             case NETWORK_TYPE_HSUPA:
2943                 return NETWORK_TYPE_BITMASK_HSUPA;
2944             case NETWORK_TYPE_HSDPA:
2945                 return NETWORK_TYPE_BITMASK_HSDPA;
2946             case NETWORK_TYPE_HSPA:
2947                 return NETWORK_TYPE_BITMASK_HSPA;
2948             case NETWORK_TYPE_HSPAP:
2949                 return NETWORK_TYPE_BITMASK_HSPAP;
2950             case NETWORK_TYPE_UMTS:
2951                 return NETWORK_TYPE_BITMASK_UMTS;
2952             case NETWORK_TYPE_TD_SCDMA:
2953                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
2954             case NETWORK_TYPE_LTE:
2955                 return NETWORK_TYPE_BITMASK_LTE;
2956             case NETWORK_TYPE_LTE_CA:
2957                 return NETWORK_TYPE_BITMASK_LTE_CA;
2958             case NETWORK_TYPE_NR:
2959                 return NETWORK_TYPE_BITMASK_NR;
2960             default:
2961                 return NETWORK_TYPE_BITMASK_UNKNOWN;
2962         }
2963     }
2964 
2965     //
2966     //
2967     // SIM Card
2968     //
2969     //
2970 
2971     /** @hide */
2972     @IntDef(prefix = {"SIM_STATE_"},
2973             value = {
2974                     SIM_STATE_UNKNOWN,
2975                     SIM_STATE_ABSENT,
2976                     SIM_STATE_PIN_REQUIRED,
2977                     SIM_STATE_PUK_REQUIRED,
2978                     SIM_STATE_NETWORK_LOCKED,
2979                     SIM_STATE_READY,
2980                     SIM_STATE_NOT_READY,
2981                     SIM_STATE_PERM_DISABLED,
2982                     SIM_STATE_CARD_IO_ERROR,
2983                     SIM_STATE_CARD_RESTRICTED,
2984                     SIM_STATE_LOADED,
2985                     SIM_STATE_PRESENT,
2986             })
2987     public @interface SimState {}
2988 
2989     /**
2990      * SIM card state: Unknown. Signifies that the SIM is in transition
2991      * between states. For example, when the user inputs the SIM pin
2992      * under PIN_REQUIRED state, a query for sim status returns
2993      * this state before turning to SIM_STATE_READY.
2994      *
2995      * These are the ordinal value of IccCardConstants.State.
2996      */
2997 
2998     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
2999     /** SIM card state: no SIM card is available in the device */
3000     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3001     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3002     public static final int SIM_STATE_PIN_REQUIRED =
3003             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3004     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3005     public static final int SIM_STATE_PUK_REQUIRED =
3006             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3007     /** SIM card state: Locked: requires a network PIN to unlock */
3008     public static final int SIM_STATE_NETWORK_LOCKED =
3009             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3010     /** SIM card state: Ready */
3011     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3012     /** SIM card state: SIM Card is NOT READY */
3013     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3014     /** SIM card state: SIM Card Error, permanently disabled */
3015     public static final int SIM_STATE_PERM_DISABLED =
3016             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3017     /** SIM card state: SIM Card Error, present but faulty */
3018     public static final int SIM_STATE_CARD_IO_ERROR =
3019             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3020     /** SIM card state: SIM Card restricted, present but not usable due to
3021      * carrier restrictions.
3022      */
3023     public static final int SIM_STATE_CARD_RESTRICTED =
3024             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3025     /**
3026      * SIM card state: Loaded: SIM card applications have been loaded
3027      * @hide
3028      */
3029     @SystemApi
3030     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3031     /**
3032      * SIM card state: SIM Card is present
3033      * @hide
3034      */
3035     @SystemApi
3036     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3037 
3038     /**
3039      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3040      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3041      *
3042      * @hide
3043      */
3044     @SystemApi
3045     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3046 
3047     /**
3048      * Broadcast Action: The sim card state has changed.
3049      * The intent will have the following extra values:</p>
3050      * <dl>
3051      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3052      *   <dd>The sim card state. One of:
3053      *     <dl>
3054      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3055      *       <dd>SIM card not found</dd>
3056      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3057      *       <dd>SIM card IO error</dd>
3058      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3059      *       <dd>SIM card is restricted</dd>
3060      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3061      *       <dd>SIM card is present</dd>
3062      *     </dl>
3063      *   </dd>
3064      * </dl>
3065      *
3066      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3067      *
3068      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3069      *
3070      * <p class="note">This is a protected intent that can only be sent by the system.
3071      * @hide
3072      */
3073     @SystemApi
3074     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3075     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3076             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3077 
3078     /**
3079      * Broadcast Action: The sim application state has changed.
3080      * The intent will have the following extra values:</p>
3081      * <dl>
3082      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3083      *   <dd>The sim application state. One of:
3084      *     <dl>
3085      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3086      *       <dd>SIM card applications not ready</dd>
3087      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3088      *       <dd>SIM card PIN locked</dd>
3089      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3090      *       <dd>SIM card PUK locked</dd>
3091      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3092      *       <dd>SIM card network locked</dd>
3093      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3094      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3095      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3096      *       <dd>SIM card data loaded</dd>
3097      *     </dl>
3098      *   </dd>
3099      * </dl>
3100      *
3101      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3102      *
3103      * <p class="note">The current state can also be queried using
3104      * {@link #getSimApplicationState()}.
3105      *
3106      * <p class="note">This is a protected intent that can only be sent by the system.
3107      * @hide
3108      */
3109     @SystemApi
3110     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3111     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3112             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3113 
3114     /**
3115      * Broadcast Action: Status of the SIM slots on the device has changed.
3116      *
3117      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3118      *
3119      * <p class="note">The status can be queried using
3120      * {@link #getUiccSlotsInfo()}
3121      *
3122      * <p class="note">This is a protected intent that can only be sent by the system.
3123      * @hide
3124      */
3125     @SystemApi
3126     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3127     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3128             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3129 
3130     /**
3131      * Broadcast Action: A debug code has been entered in the dialer.
3132      * <p>
3133      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3134      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3135      * (see {@link #hasCarrierPrivileges}).
3136      * <p>
3137      * These "secret codes" are used to activate developer menus by dialing certain codes.
3138      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3139      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3140      * receiver would be woken up even if it is not currently running.
3141      * <p>
3142      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3143      * in the next Android version.
3144      * Before that both of these two actions will be broadcast.
3145      */
3146     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3147     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3148 
3149     /**
3150      * @return true if a ICC card is present
3151      */
hasIccCard()3152     public boolean hasIccCard() {
3153         return hasIccCard(getSlotIndex());
3154     }
3155 
3156     /**
3157      * @return true if a ICC card is present for a subscription
3158      *
3159      * @param slotIndex for which icc card presence is checked
3160      */
3161     /** {@hide} */
3162     // FIXME Input argument slotIndex should be of type int
3163     @UnsupportedAppUsage
hasIccCard(int slotIndex)3164     public boolean hasIccCard(int slotIndex) {
3165 
3166         try {
3167             ITelephony telephony = getITelephony();
3168             if (telephony == null)
3169                 return false;
3170             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3171         } catch (RemoteException ex) {
3172             // Assume no ICC card if remote exception which shouldn't happen
3173             return false;
3174         } catch (NullPointerException ex) {
3175             // This could happen before phone restarts due to crashing
3176             return false;
3177         }
3178     }
3179 
3180     /**
3181      * Returns a constant indicating the state of the default SIM card.
3182      *
3183      * @see #SIM_STATE_UNKNOWN
3184      * @see #SIM_STATE_ABSENT
3185      * @see #SIM_STATE_PIN_REQUIRED
3186      * @see #SIM_STATE_PUK_REQUIRED
3187      * @see #SIM_STATE_NETWORK_LOCKED
3188      * @see #SIM_STATE_READY
3189      * @see #SIM_STATE_NOT_READY
3190      * @see #SIM_STATE_PERM_DISABLED
3191      * @see #SIM_STATE_CARD_IO_ERROR
3192      * @see #SIM_STATE_CARD_RESTRICTED
3193      */
getSimState()3194     public @SimState int getSimState() {
3195         int simState = getSimStateIncludingLoaded();
3196         if (simState == SIM_STATE_LOADED) {
3197             simState = SIM_STATE_READY;
3198         }
3199         return simState;
3200     }
3201 
getSimStateIncludingLoaded()3202     private @SimState int getSimStateIncludingLoaded() {
3203         int slotIndex = getSlotIndex();
3204         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3205         // sim state
3206         if (slotIndex < 0) {
3207             // query for all slots and return absent if all sim states are absent, otherwise
3208             // return unknown
3209             for (int i = 0; i < getPhoneCount(); i++) {
3210                 int simState = getSimState(i);
3211                 if (simState != SIM_STATE_ABSENT) {
3212                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3213                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3214                     return SIM_STATE_UNKNOWN;
3215                 }
3216             }
3217             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3218                     "state as absent");
3219             return SIM_STATE_ABSENT;
3220         }
3221         return SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3222     }
3223 
3224     /**
3225      * Returns a constant indicating the state of the default SIM card.
3226      *
3227      * @see #SIM_STATE_UNKNOWN
3228      * @see #SIM_STATE_ABSENT
3229      * @see #SIM_STATE_CARD_IO_ERROR
3230      * @see #SIM_STATE_CARD_RESTRICTED
3231      * @see #SIM_STATE_PRESENT
3232      *
3233      * @hide
3234      */
3235     @SystemApi
getSimCardState()3236     public @SimState int getSimCardState() {
3237         int simState = getSimState();
3238         return getSimCardStateFromSimState(simState);
3239     }
3240 
3241     /**
3242      * Returns a constant indicating the state of the device SIM card in a physical slot.
3243      *
3244      * @param physicalSlotIndex physical slot index
3245      *
3246      * @see #SIM_STATE_UNKNOWN
3247      * @see #SIM_STATE_ABSENT
3248      * @see #SIM_STATE_CARD_IO_ERROR
3249      * @see #SIM_STATE_CARD_RESTRICTED
3250      * @see #SIM_STATE_PRESENT
3251      *
3252      * @hide
3253      */
3254     @SystemApi
3255     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimCardState(int physicalSlotIndex)3256     public @SimState int getSimCardState(int physicalSlotIndex) {
3257         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex));
3258         return getSimCardStateFromSimState(simState);
3259     }
3260 
3261     /**
3262      * Converts SIM state to SIM card state.
3263      * @param simState
3264      * @return SIM card state
3265      */
getSimCardStateFromSimState(int simState)3266     private @SimState int getSimCardStateFromSimState(int simState) {
3267         switch (simState) {
3268             case SIM_STATE_UNKNOWN:
3269             case SIM_STATE_ABSENT:
3270             case SIM_STATE_CARD_IO_ERROR:
3271             case SIM_STATE_CARD_RESTRICTED:
3272                 return simState;
3273             default:
3274                 return SIM_STATE_PRESENT;
3275         }
3276     }
3277 
3278     /**
3279      * Converts a physical slot index to logical slot index.
3280      * @param physicalSlotIndex physical slot index
3281      * @return logical slot index
3282      */
getLogicalSlotIndex(int physicalSlotIndex)3283     private int getLogicalSlotIndex(int physicalSlotIndex) {
3284         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3285         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length) {
3286             return slotInfos[physicalSlotIndex].getLogicalSlotIdx();
3287         }
3288 
3289         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3290     }
3291 
3292     /**
3293      * Returns a constant indicating the state of the card applications on the default SIM card.
3294      *
3295      * @see #SIM_STATE_UNKNOWN
3296      * @see #SIM_STATE_PIN_REQUIRED
3297      * @see #SIM_STATE_PUK_REQUIRED
3298      * @see #SIM_STATE_NETWORK_LOCKED
3299      * @see #SIM_STATE_NOT_READY
3300      * @see #SIM_STATE_PERM_DISABLED
3301      * @see #SIM_STATE_LOADED
3302      *
3303      * @hide
3304      */
3305     @SystemApi
getSimApplicationState()3306     public @SimState int getSimApplicationState() {
3307         int simState = getSimStateIncludingLoaded();
3308         return getSimApplicationStateFromSimState(simState);
3309     }
3310 
3311     /**
3312      * Returns a constant indicating the state of the card applications on the device SIM card in
3313      * a physical slot.
3314      *
3315      * @param physicalSlotIndex physical slot index
3316      *
3317      * @see #SIM_STATE_UNKNOWN
3318      * @see #SIM_STATE_PIN_REQUIRED
3319      * @see #SIM_STATE_PUK_REQUIRED
3320      * @see #SIM_STATE_NETWORK_LOCKED
3321      * @see #SIM_STATE_NOT_READY
3322      * @see #SIM_STATE_PERM_DISABLED
3323      * @see #SIM_STATE_LOADED
3324      *
3325      * @hide
3326      */
3327     @SystemApi
3328     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimApplicationState(int physicalSlotIndex)3329     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3330         int simState =
3331                 SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex));
3332         return getSimApplicationStateFromSimState(simState);
3333     }
3334 
3335     /**
3336      * Converts SIM state to SIM application state.
3337      * @param simState
3338      * @return SIM application state
3339      */
getSimApplicationStateFromSimState(int simState)3340     private @SimState int getSimApplicationStateFromSimState(int simState) {
3341         switch (simState) {
3342             case SIM_STATE_UNKNOWN:
3343             case SIM_STATE_ABSENT:
3344             case SIM_STATE_CARD_IO_ERROR:
3345             case SIM_STATE_CARD_RESTRICTED:
3346                 return SIM_STATE_UNKNOWN;
3347             case SIM_STATE_READY:
3348                 // Ready is not a valid state anymore. The state that is broadcast goes from
3349                 // NOT_READY to either LOCKED or LOADED.
3350                 return SIM_STATE_NOT_READY;
3351             default:
3352                 return simState;
3353         }
3354     }
3355 
3356 
3357     /**
3358      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
3359      * on the UICC card.
3360      *
3361      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
3362      *
3363      * @param appType the uicc app type like {@link APPTYPE_CSIM}
3364      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
3365      * @hide
3366      */
3367     @SystemApi
3368     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApplicationOnUicc(@iccAppType int appType)3369     public boolean isApplicationOnUicc(@UiccAppType int appType) {
3370         try {
3371             ITelephony service = getITelephony();
3372             if (service != null) {
3373                 return service.isApplicationOnUicc(getSubId(), appType);
3374             }
3375         } catch (RemoteException e) {
3376             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
3377         }
3378         return false;
3379     }
3380 
3381     /**
3382      * Returns a constant indicating the state of the device SIM card in a logical slot.
3383      *
3384      * @param slotIndex logical slot index
3385      *
3386      * @see #SIM_STATE_UNKNOWN
3387      * @see #SIM_STATE_ABSENT
3388      * @see #SIM_STATE_PIN_REQUIRED
3389      * @see #SIM_STATE_PUK_REQUIRED
3390      * @see #SIM_STATE_NETWORK_LOCKED
3391      * @see #SIM_STATE_READY
3392      * @see #SIM_STATE_NOT_READY
3393      * @see #SIM_STATE_PERM_DISABLED
3394      * @see #SIM_STATE_CARD_IO_ERROR
3395      * @see #SIM_STATE_CARD_RESTRICTED
3396      */
getSimState(int slotIndex)3397     public @SimState int getSimState(int slotIndex) {
3398         int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3399         if (simState == SIM_STATE_LOADED) {
3400             simState = SIM_STATE_READY;
3401         }
3402         return simState;
3403     }
3404 
3405     /**
3406      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3407      * provider of the SIM. 5 or 6 decimal digits.
3408      * <p>
3409      * Availability: SIM state must be {@link #SIM_STATE_READY}
3410      *
3411      * @see #getSimState
3412      */
getSimOperator()3413     public String getSimOperator() {
3414         return getSimOperatorNumeric();
3415     }
3416 
3417     /**
3418      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3419      * provider of the SIM. 5 or 6 decimal digits.
3420      * <p>
3421      * Availability: SIM state must be {@link #SIM_STATE_READY}
3422      *
3423      * @see #getSimState
3424      *
3425      * @param subId for which SimOperator is returned
3426      * @hide
3427      */
3428     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)3429     public String getSimOperator(int subId) {
3430         return getSimOperatorNumeric(subId);
3431     }
3432 
3433     /**
3434      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3435      * provider of the SIM. 5 or 6 decimal digits.
3436      * <p>
3437      * Availability: SIM state must be {@link #SIM_STATE_READY}
3438      *
3439      * @see #getSimState
3440      * @hide
3441      */
3442     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()3443     public String getSimOperatorNumeric() {
3444         int subId = mSubId;
3445         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3446             subId = SubscriptionManager.getDefaultDataSubscriptionId();
3447             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3448                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
3449                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3450                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
3451                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3452                         subId = SubscriptionManager.getDefaultSubscriptionId();
3453                     }
3454                 }
3455             }
3456         }
3457         return getSimOperatorNumeric(subId);
3458     }
3459 
3460     /**
3461      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3462      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3463      * <p>
3464      * Availability: SIM state must be {@link #SIM_STATE_READY}
3465      *
3466      * @see #getSimState
3467      *
3468      * @param subId for which SimOperator is returned
3469      * @hide
3470      */
3471     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)3472     public String getSimOperatorNumeric(int subId) {
3473         int phoneId = SubscriptionManager.getPhoneId(subId);
3474         return getSimOperatorNumericForPhone(phoneId);
3475     }
3476 
3477     /**
3478      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3479      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3480      * <p>
3481      *
3482      * @param phoneId for which SimOperator is returned
3483      * @hide
3484      */
3485     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)3486     public String getSimOperatorNumericForPhone(int phoneId) {
3487         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
3488     }
3489 
3490     /**
3491      * Returns the Service Provider Name (SPN).
3492      * <p>
3493      * Availability: SIM state must be {@link #SIM_STATE_READY}
3494      *
3495      * @see #getSimState
3496      */
getSimOperatorName()3497     public String getSimOperatorName() {
3498         return getSimOperatorNameForPhone(getPhoneId());
3499     }
3500 
3501     /**
3502      * Returns the Service Provider Name (SPN).
3503      * <p>
3504      * Availability: SIM state must be {@link #SIM_STATE_READY}
3505      *
3506      * @see #getSimState
3507      *
3508      * @param subId for which SimOperatorName is returned
3509      * @hide
3510      */
3511     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)3512     public String getSimOperatorName(int subId) {
3513         int phoneId = SubscriptionManager.getPhoneId(subId);
3514         return getSimOperatorNameForPhone(phoneId);
3515     }
3516 
3517     /**
3518      * Returns the Service Provider Name (SPN).
3519      *
3520      * @hide
3521      */
3522     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)3523     public String getSimOperatorNameForPhone(int phoneId) {
3524         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
3525     }
3526 
3527     /**
3528      * Returns the ISO-3166 country code equivalent for the SIM provider's country code.
3529      * <p>
3530      * The ISO-3166 country code is provided in lowercase 2 character format.
3531      * @return the lowercase 2 character ISO-3166 country code, or empty string is not available.
3532      */
getSimCountryIso()3533     public String getSimCountryIso() {
3534         return getSimCountryIsoForPhone(getPhoneId());
3535     }
3536 
3537     /**
3538      * Returns the ISO country code equivalent for the SIM provider's country code.
3539      *
3540      * @param subId for which SimCountryIso is returned
3541      * @hide
3542      */
3543     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)3544     public String getSimCountryIso(int subId) {
3545         int phoneId = SubscriptionManager.getPhoneId(subId);
3546         return getSimCountryIsoForPhone(phoneId);
3547     }
3548 
3549     /**
3550      * Returns the ISO country code equivalent for the SIM provider's country code.
3551      *
3552      * @hide
3553      */
3554     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)3555     public String getSimCountryIsoForPhone(int phoneId) {
3556         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
3557     }
3558 
3559     /**
3560      * Returns the serial number of the SIM, if applicable. Return null if it is
3561      * unavailable.
3562      *
3563      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
3564      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
3565      * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
3566      * managed profile on the device; for more details see <a
3567      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
3568      * access is deprecated and will be removed in a future release.
3569      *
3570      * <p>If the calling app does not meet one of these requirements then this method will behave
3571      * as follows:
3572      *
3573      * <ul>
3574      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3575      *     READ_PHONE_STATE permission then null is returned.</li>
3576      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3577      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3578      *     higher, then a SecurityException is thrown.</li>
3579      * </ul>
3580      */
3581     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
3582     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimSerialNumber()3583     public String getSimSerialNumber() {
3584          return getSimSerialNumber(getSubId());
3585     }
3586 
3587     /**
3588      * Returns the serial number for the given subscription, if applicable. Return null if it is
3589      * unavailable.
3590      *
3591      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
3592      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
3593      * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
3594      * managed profile on the device; for more details see <a
3595      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
3596      * access is deprecated and will be removed in a future release.
3597      *
3598      * <p>If the calling app does not meet one of these requirements then this method will behave
3599      * as follows:
3600      *
3601      * <ul>
3602      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3603      *     READ_PHONE_STATE permission then null is returned.</li>
3604      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3605      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3606      *     higher, then a SecurityException is thrown.</li>
3607      * </ul>
3608      *
3609      * @param subId for which Sim Serial number is returned
3610      * @hide
3611      */
3612     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3613     @UnsupportedAppUsage
getSimSerialNumber(int subId)3614     public String getSimSerialNumber(int subId) {
3615         try {
3616             IPhoneSubInfo info = getSubscriberInfo();
3617             if (info == null)
3618                 return null;
3619             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
3620                     null);
3621         } catch (RemoteException ex) {
3622             return null;
3623         } catch (NullPointerException ex) {
3624             // This could happen before phone restarts due to crashing
3625             return null;
3626         }
3627     }
3628 
3629     /**
3630      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
3631      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
3632      *
3633      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
3634      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
3635      *
3636      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
3637      *         {@code false} if not supported or unknown
3638      * @hide
3639      */
3640     @SystemApi
3641     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isLteCdmaEvdoGsmWcdmaEnabled()3642     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
3643         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
3644     }
3645 
3646     /**
3647      * Return if the current radio is LTE on CDMA for Subscription. This
3648      * is a tri-state return value as for a period of time
3649      * the mode may be unknown.
3650      *
3651      * @param subId for which radio is LTE on CDMA is returned
3652      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
3653      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
3654      * @hide
3655      */
3656     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3657     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)3658     public int getLteOnCdmaMode(int subId) {
3659         try {
3660             ITelephony telephony = getITelephony();
3661             if (telephony == null)
3662                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3663             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
3664                     getFeatureId());
3665         } catch (RemoteException ex) {
3666             // Assume no ICC card if remote exception which shouldn't happen
3667             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3668         } catch (NullPointerException ex) {
3669             // This could happen before phone restarts due to crashing
3670             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3671         }
3672     }
3673 
3674     /**
3675      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
3676      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
3677      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
3678      *
3679      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
3680      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
3681      * through a factory reset.
3682      *
3683      * @return card ID of the default eUICC card, if loaded.
3684      */
getCardIdForDefaultEuicc()3685     public int getCardIdForDefaultEuicc() {
3686         try {
3687             ITelephony telephony = getITelephony();
3688             if (telephony == null) {
3689                 return UNINITIALIZED_CARD_ID;
3690             }
3691             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
3692         } catch (RemoteException e) {
3693             return UNINITIALIZED_CARD_ID;
3694         }
3695     }
3696 
3697     /**
3698      * Gets information about currently inserted UICCs and eUICCs.
3699      * <p>
3700      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3701      * <p>
3702      * If the caller has carrier priviliges on any active subscription, then they have permission to
3703      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
3704      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the slot index where the card is inserted
3705      * ({@link UiccCardInfo#getSlotIndex()}).
3706      * <p>
3707      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
3708      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
3709      * UICC or eUICC card.
3710      * <p>
3711      * See {@link UiccCardInfo} for more details on the kind of information available.
3712      *
3713      * @return a list of UiccCardInfo objects, representing information on the currently inserted
3714      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
3715      * the caller does not have adequate permissions for that card.
3716      */
3717     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3718     @NonNull
getUiccCardsInfo()3719     public List<UiccCardInfo> getUiccCardsInfo() {
3720         try {
3721             ITelephony telephony = getITelephony();
3722             if (telephony == null) {
3723                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
3724                 return new ArrayList<UiccCardInfo>();
3725             }
3726             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
3727         } catch (RemoteException e) {
3728             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
3729             return new ArrayList<UiccCardInfo>();
3730         }
3731     }
3732 
3733     /**
3734      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
3735      * available, which is possible between phone process starting and getting slot info from modem.
3736      *
3737      * @return UiccSlotInfo array.
3738      *
3739      * @hide
3740      */
3741     @SystemApi
3742     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getUiccSlotsInfo()3743     public UiccSlotInfo[] getUiccSlotsInfo() {
3744         try {
3745             ITelephony telephony = getITelephony();
3746             if (telephony == null) {
3747                 return null;
3748             }
3749             return telephony.getUiccSlotsInfo();
3750         } catch (RemoteException e) {
3751             return null;
3752         }
3753     }
3754 
3755     /**
3756      * Test method to reload the UICC profile.
3757      *
3758      * @hide
3759      */
3760     @TestApi
3761     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()3762     public void refreshUiccProfile() {
3763         try {
3764             ITelephony telephony = getITelephony();
3765             telephony.refreshUiccProfile(mSubId);
3766         } catch (RemoteException ex) {
3767             Rlog.w(TAG, "RemoteException", ex);
3768         }
3769     }
3770 
3771     /**
3772      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
3773      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
3774      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
3775      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
3776      * logical slots.
3777      *
3778      * @param physicalSlots The content of the array represents the physical slot index. The array
3779      *        size should be same as {@link #getUiccSlotsInfo()}.
3780      * @return boolean Return true if the switch succeeds, false if the switch fails.
3781      * @hide
3782      */
3783     @SystemApi
3784     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchSlots(int[] physicalSlots)3785     public boolean switchSlots(int[] physicalSlots) {
3786         try {
3787             ITelephony telephony = getITelephony();
3788             if (telephony == null) {
3789                 return false;
3790             }
3791             return telephony.switchSlots(physicalSlots);
3792         } catch (RemoteException e) {
3793             return false;
3794         }
3795     }
3796 
3797     /**
3798      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
3799      * id and the value is the physical slots id mapped to this logical slot id.
3800      *
3801      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
3802      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
3803      *
3804      * @hide
3805      */
3806     @SystemApi
3807     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3808     @NonNull
getLogicalToPhysicalSlotMapping()3809     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
3810         Map<Integer, Integer> slotMapping = new HashMap<>();
3811         try {
3812             ITelephony telephony = getITelephony();
3813             if (telephony != null) {
3814                 int[] slotMappingArray = telephony.getSlotsMapping();
3815                 for (int i = 0; i < slotMappingArray.length; i++) {
3816                     slotMapping.put(i, slotMappingArray[i]);
3817                 }
3818             }
3819         } catch (RemoteException e) {
3820             Log.e(TAG, "getSlotsMapping RemoteException", e);
3821         }
3822         return slotMapping;
3823     }
3824 
3825     //
3826     //
3827     // Subscriber Info
3828     //
3829     //
3830 
3831     /**
3832      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
3833      * Return null if it is unavailable.
3834      *
3835      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
3836      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
3837      * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
3838      * managed profile on the device; for more details see <a
3839      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
3840      * access is deprecated and will be removed in a future release.
3841      *
3842      * <p>If the calling app does not meet one of these requirements then this method will behave
3843      * as follows:
3844      *
3845      * <ul>
3846      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3847      *     READ_PHONE_STATE permission then null is returned.</li>
3848      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3849      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3850      *     higher, then a SecurityException is thrown.</li>
3851      * </ul>
3852      */
3853     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
3854     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSubscriberId()3855     public String getSubscriberId() {
3856         return getSubscriberId(getSubId());
3857     }
3858 
3859     /**
3860      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
3861      * for a subscription.
3862      * Return null if it is unavailable.
3863      *
3864      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
3865      * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
3866      * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
3867      * managed profile on the device; for more details see <a
3868      * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
3869      * access is deprecated and will be removed in a future release.
3870      *
3871      * <p>If the calling app does not meet one of these requirements then this method will behave
3872      * as follows:
3873      *
3874      * <ul>
3875      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3876      *     READ_PHONE_STATE permission then null is returned.</li>
3877      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3878      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3879      *     higher, then a SecurityException is thrown.</li>
3880      * </ul>
3881      *
3882      * @param subId whose subscriber id is returned
3883      * @hide
3884      */
3885     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3886     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)3887     public String getSubscriberId(int subId) {
3888         try {
3889             IPhoneSubInfo info = getSubscriberInfo();
3890             if (info == null)
3891                 return null;
3892             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
3893                     null);
3894         } catch (RemoteException ex) {
3895             return null;
3896         } catch (NullPointerException ex) {
3897             // This could happen before phone restarts due to crashing
3898             return null;
3899         }
3900     }
3901 
3902     /**
3903      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
3904      * including the public key and the key identifier; or {@code null} if not available.
3905      * <p>
3906      * For a multi-sim device, the dafault data sim is used if not specified.
3907      * <p>
3908      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
3909      *
3910      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
3911      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
3912      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
3913      *         IMSI and IMPI. This includes the public key and the key identifier. This information
3914      *         will be stored in the device keystore. {@code null} will be returned when no key is
3915      *         found, and the carrier does not require a key.
3916      * @throws IllegalArgumentException when an invalid key is found or when key is required but
3917      *         not found.
3918      * @hide
3919      */
3920     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3921     @SystemApi
3922     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)3923     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
3924         try {
3925             IPhoneSubInfo info = getSubscriberInfo();
3926             if (info == null) {
3927                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
3928                 return null;
3929             }
3930             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
3931             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
3932                 throw new IllegalArgumentException("IMSI error: Invalid key type");
3933             }
3934             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
3935                     subId, keyType, mContext.getOpPackageName());
3936             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
3937                 Rlog.e(TAG, "IMSI error: key is required but not found");
3938                 throw new IllegalArgumentException("IMSI error: key is required but not found");
3939             }
3940             return imsiEncryptionInfo;
3941         } catch (RemoteException ex) {
3942             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
3943         } catch (NullPointerException ex) {
3944             // This could happen before phone restarts due to crashing
3945             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
3946         }
3947         return null;
3948     }
3949 
3950     /**
3951      * Resets the carrier keys used to encrypt the IMSI and IMPI.
3952      * <p>
3953      * This involves 2 steps:
3954      *  1. Delete the keys from the database.
3955      *  2. Send an intent to download new Certificates.
3956      * <p>
3957      * For a multi-sim device, the dafault data sim is used if not specified.
3958      * <p>
3959      * Requires Permission: MODIFY_PHONE_STATE.
3960      *
3961      * @see #getCarrierInfoForImsiEncryption
3962      * @hide
3963      */
3964     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
3965     @SystemApi
resetCarrierKeysForImsiEncryption()3966     public void resetCarrierKeysForImsiEncryption() {
3967         try {
3968             IPhoneSubInfo info = getSubscriberInfo();
3969             if (info == null) {
3970                 Rlog.e(TAG, "IMSI error: Subscriber Info is null");
3971                 if (!isSystemProcess()) {
3972                     throw new RuntimeException("IMSI error: Subscriber Info is null");
3973                 }
3974                 return;
3975             }
3976             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
3977             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
3978         } catch (RemoteException ex) {
3979             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
3980             if (!isSystemProcess()) {
3981                 ex.rethrowAsRuntimeException();
3982             }
3983         }
3984     }
3985 
3986    /**
3987      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
3988      * @param keyType the key type which is being checked. (WLAN, EPDG)
3989      * @return true if the digit at position keyType is 1, else false.
3990      * @hide
3991      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)3992     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
3993         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
3994         return (returnValue == 1) ? true : false;
3995     }
3996 
3997     /**
3998      * If Carrier requires Imsi to be encrypted.
3999      * @hide
4000      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4001     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4002         CarrierConfigManager configManager =
4003                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4004         if (configManager == null) {
4005             return false;
4006         }
4007         PersistableBundle pb = configManager.getConfigForSubId(subId);
4008         if (pb == null) {
4009             return false;
4010         }
4011         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4012         return isKeyEnabled(keyAvailability, keyType);
4013     }
4014 
4015     /**
4016      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4017      * This includes the public key and the key identifier. This information will be stored in the
4018      * device keystore.
4019      * <p>
4020      * Requires Permission:
4021      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4022      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4023      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4024      *        The keyIdentifier Attribute value pair that helps a server locate
4025      *        the private key to decrypt the permanent identity. This field is
4026      *        optional and if it is present then it’s always separated from encrypted
4027      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4028      *        with “name=value” format.
4029      * @hide
4030      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4031     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4032         try {
4033             IPhoneSubInfo info = getSubscriberInfo();
4034             if (info == null) return;
4035             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4036                     imsiEncryptionInfo);
4037         } catch (NullPointerException ex) {
4038             // This could happen before phone restarts due to crashing
4039             return;
4040         } catch (RemoteException ex) {
4041             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4042             return;
4043         }
4044     }
4045 
4046     /**
4047      * Returns the Group Identifier Level1 for a GSM phone.
4048      * Return null if it is unavailable.
4049      *
4050      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4051      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4052      */
4053     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4054     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getGroupIdLevel1()4055     public String getGroupIdLevel1() {
4056         try {
4057             IPhoneSubInfo info = getSubscriberInfo();
4058             if (info == null)
4059                 return null;
4060             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
4061                     null);
4062         } catch (RemoteException ex) {
4063             return null;
4064         } catch (NullPointerException ex) {
4065             // This could happen before phone restarts due to crashing
4066             return null;
4067         }
4068     }
4069 
4070     /**
4071      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
4072      * Return null if it is unavailable.
4073      *
4074      * @param subId whose subscriber id is returned
4075      * @hide
4076      */
4077     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4078     @UnsupportedAppUsage
getGroupIdLevel1(int subId)4079     public String getGroupIdLevel1(int subId) {
4080         try {
4081             IPhoneSubInfo info = getSubscriberInfo();
4082             if (info == null)
4083                 return null;
4084             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
4085                     null);
4086         } catch (RemoteException ex) {
4087             return null;
4088         } catch (NullPointerException ex) {
4089             // This could happen before phone restarts due to crashing
4090             return null;
4091         }
4092     }
4093 
4094     /**
4095      * Returns the phone number string for line 1, for example, the MSISDN
4096      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4097      * <p>
4098      * The default SMS app can also use this.
4099      *
4100      * <p>Requires Permission:
4101      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4102      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4103      *     that the caller is the default SMS app,
4104      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4105      *     for any API level.
4106      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4107      *     for apps targeting SDK API level 29 and below.
4108      */
4109     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
4110     @RequiresPermission(anyOf = {
4111             android.Manifest.permission.READ_PHONE_STATE,
4112             android.Manifest.permission.READ_SMS,
4113             android.Manifest.permission.READ_PHONE_NUMBERS
4114     })
getLine1Number()4115     public String getLine1Number() {
4116         return getLine1Number(getSubId());
4117     }
4118 
4119     /**
4120      * Returns the phone number string for line 1, for example, the MSISDN
4121      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4122      * <p>
4123      * The default SMS app can also use this.
4124      *
4125      * <p>Requires Permission:
4126      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4127      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4128      *     that the caller is the default SMS app,
4129      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4130      *     for any API level.
4131      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4132      *     for apps targeting SDK API level 29 and below.
4133      *
4134      * @param subId whose phone number for line 1 is returned
4135      * @hide
4136      */
4137     @RequiresPermission(anyOf = {
4138             android.Manifest.permission.READ_PHONE_STATE,
4139             android.Manifest.permission.READ_SMS,
4140             android.Manifest.permission.READ_PHONE_NUMBERS
4141     })
4142     @UnsupportedAppUsage
getLine1Number(int subId)4143     public String getLine1Number(int subId) {
4144         String number = null;
4145         try {
4146             ITelephony telephony = getITelephony();
4147             if (telephony != null)
4148                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
4149                          null);
4150         } catch (RemoteException ex) {
4151         } catch (NullPointerException ex) {
4152         }
4153         if (number != null) {
4154             return number;
4155         }
4156         try {
4157             IPhoneSubInfo info = getSubscriberInfo();
4158             if (info == null)
4159                 return null;
4160             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
4161                     null);
4162         } catch (RemoteException ex) {
4163             return null;
4164         } catch (NullPointerException ex) {
4165             // This could happen before phone restarts due to crashing
4166             return null;
4167         }
4168     }
4169 
4170     /**
4171      * Set the line 1 phone number string and its alphatag for the current ICCID
4172      * for display purpose only, for example, displayed in Phone Status. It won't
4173      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4174      * value.
4175      *
4176      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4177      *
4178      * @param alphaTag alpha-tagging of the dailing nubmer
4179      * @param number The dialing number
4180      * @return true if the operation was executed correctly.
4181      */
setLine1NumberForDisplay(String alphaTag, String number)4182     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
4183         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
4184     }
4185 
4186     /**
4187      * Set the line 1 phone number string and its alphatag for the current ICCID
4188      * for display purpose only, for example, displayed in Phone Status. It won't
4189      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4190      * value.
4191      *
4192      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4193      *
4194      * @param subId the subscriber that the alphatag and dialing number belongs to.
4195      * @param alphaTag alpha-tagging of the dailing nubmer
4196      * @param number The dialing number
4197      * @return true if the operation was executed correctly.
4198      * @hide
4199      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)4200     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
4201         try {
4202             ITelephony telephony = getITelephony();
4203             if (telephony != null)
4204                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
4205         } catch (RemoteException ex) {
4206         } catch (NullPointerException ex) {
4207         }
4208         return false;
4209     }
4210 
4211     /**
4212      * Returns the alphabetic identifier associated with the line 1 number.
4213      * Return null if it is unavailable.
4214      * @hide
4215      * nobody seems to call this.
4216      */
4217     @UnsupportedAppUsage
4218     @TestApi
4219     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()4220     public String getLine1AlphaTag() {
4221         return getLine1AlphaTag(getSubId());
4222     }
4223 
4224     /**
4225      * Returns the alphabetic identifier associated with the line 1 number
4226      * for a subscription.
4227      * Return null if it is unavailable.
4228      * @param subId whose alphabetic identifier associated with line 1 is returned
4229      * nobody seems to call this.
4230      * @hide
4231      */
4232     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4233     @UnsupportedAppUsage
getLine1AlphaTag(int subId)4234     public String getLine1AlphaTag(int subId) {
4235         String alphaTag = null;
4236         try {
4237             ITelephony telephony = getITelephony();
4238             if (telephony != null)
4239                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
4240                         getOpPackageName(), getFeatureId());
4241         } catch (RemoteException ex) {
4242         } catch (NullPointerException ex) {
4243         }
4244         if (alphaTag != null) {
4245             return alphaTag;
4246         }
4247         try {
4248             IPhoneSubInfo info = getSubscriberInfo();
4249             if (info == null)
4250                 return null;
4251             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
4252                     getFeatureId());
4253         } catch (RemoteException ex) {
4254             return null;
4255         } catch (NullPointerException ex) {
4256             // This could happen before phone restarts due to crashing
4257             return null;
4258         }
4259     }
4260 
4261     /**
4262      * Return the set of subscriber IDs that should be considered "merged together" for data usage
4263      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
4264      * subscribers are sorted in a deterministic order.
4265      * <p>
4266      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
4267      * TelephonyManager's subId.
4268      *
4269      * This is deprecated and {@link #getMergedSubscriberIdsFromGroup()} should be used for data
4270      * usage merging purpose.
4271      * TODO: remove this API.
4272      *
4273      * @hide
4274      */
4275     @UnsupportedAppUsage
4276     @Deprecated
getMergedSubscriberIds()4277     public @Nullable String[] getMergedSubscriberIds() {
4278         try {
4279             ITelephony telephony = getITelephony();
4280             if (telephony != null)
4281                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
4282                         getFeatureId());
4283         } catch (RemoteException ex) {
4284         } catch (NullPointerException ex) {
4285         }
4286         return null;
4287     }
4288 
4289     /**
4290      * Return the set of subscriber IDs that should be considered "merged together" for data usage
4291      * purposes. Unlike {@link #getMergedSubscriberIds()} this API merge subscriberIds based on
4292      * subscription grouping: subscriberId of those in the same group will all be returned.
4293      *
4294      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
4295      *
4296      * @hide
4297      */
4298     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMergedSubscriberIdsFromGroup()4299     public @Nullable String[] getMergedSubscriberIdsFromGroup() {
4300         try {
4301             ITelephony telephony = getITelephony();
4302             if (telephony != null) {
4303                 return telephony.getMergedSubscriberIdsFromGroup(getSubId(), getOpPackageName());
4304             }
4305         } catch (RemoteException ex) {
4306         } catch (NullPointerException ex) {
4307         }
4308         return null;
4309     }
4310 
4311     /**
4312      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4313      *
4314      * <p>Requires Permission:
4315      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4316      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4317      *     that the caller is the default SMS app,
4318      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4319      *     for any API level.
4320      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4321      *     for apps targeting SDK API level 29 and below.
4322      *
4323      * @hide
4324      */
4325     @RequiresPermission(anyOf = {
4326             android.Manifest.permission.READ_PHONE_STATE,
4327             android.Manifest.permission.READ_SMS,
4328             android.Manifest.permission.READ_PHONE_NUMBERS
4329     })
4330     @UnsupportedAppUsage
getMsisdn()4331     public String getMsisdn() {
4332         return getMsisdn(getSubId());
4333     }
4334 
4335     /**
4336      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4337      *
4338      * @param subId for which msisdn is returned
4339      *
4340      * <p>Requires Permission:
4341      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4342      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4343      *     that the caller is the default SMS app,
4344      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4345      *     for any API level.
4346      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4347      *     for apps targeting SDK API level 29 and below.
4348      *
4349      * @hide
4350      */
4351     @RequiresPermission(anyOf = {
4352             android.Manifest.permission.READ_PHONE_STATE,
4353             android.Manifest.permission.READ_SMS,
4354             android.Manifest.permission.READ_PHONE_NUMBERS
4355     })
4356     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)4357     public String getMsisdn(int subId) {
4358         try {
4359             IPhoneSubInfo info = getSubscriberInfo();
4360             if (info == null)
4361                 return null;
4362             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getFeatureId());
4363         } catch (RemoteException ex) {
4364             return null;
4365         } catch (NullPointerException ex) {
4366             // This could happen before phone restarts due to crashing
4367             return null;
4368         }
4369     }
4370 
4371     /**
4372      * Returns the voice mail number. Return null if it is unavailable.
4373      *
4374      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4375      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4376      */
4377     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4378     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailNumber()4379     public String getVoiceMailNumber() {
4380         return getVoiceMailNumber(getSubId());
4381     }
4382 
4383     /**
4384      * Returns the voice mail number for a subscription.
4385      * Return null if it is unavailable.
4386      * @param subId whose voice mail number is returned
4387      * @hide
4388      */
4389     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4390     @UnsupportedAppUsage
getVoiceMailNumber(int subId)4391     public String getVoiceMailNumber(int subId) {
4392         try {
4393             IPhoneSubInfo info = getSubscriberInfo();
4394             if (info == null)
4395                 return null;
4396             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
4397                     getFeatureId());
4398         } catch (RemoteException ex) {
4399             return null;
4400         } catch (NullPointerException ex) {
4401             // This could happen before phone restarts due to crashing
4402             return null;
4403         }
4404     }
4405 
4406     /**
4407      * Sets the voice mail number.
4408      *
4409      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4410      *
4411      * @param alphaTag The alpha tag to display.
4412      * @param number The voicemail number.
4413      */
setVoiceMailNumber(String alphaTag, String number)4414     public boolean setVoiceMailNumber(String alphaTag, String number) {
4415         return setVoiceMailNumber(getSubId(), alphaTag, number);
4416     }
4417 
4418     /**
4419      * Sets the voicemail number for the given subscriber.
4420      *
4421      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4422      *
4423      * @param subId The subscription id.
4424      * @param alphaTag The alpha tag to display.
4425      * @param number The voicemail number.
4426      * @hide
4427      */
setVoiceMailNumber(int subId, String alphaTag, String number)4428     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
4429         try {
4430             ITelephony telephony = getITelephony();
4431             if (telephony != null)
4432                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
4433         } catch (RemoteException ex) {
4434         } catch (NullPointerException ex) {
4435         }
4436         return false;
4437     }
4438 
4439     /**
4440      * Enables or disables the visual voicemail client for a phone account.
4441      *
4442      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
4443      * {@link #hasCarrierPrivileges}), or has permission
4444      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
4445      *
4446      * @param phoneAccountHandle the phone account to change the client state
4447      * @param enabled the new state of the client
4448      * @hide
4449      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
4450      * be implemented instead.
4451      */
4452     @SystemApi
4453     @SuppressLint("Doclava125")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)4454     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
4455     }
4456 
4457     /**
4458      * Returns whether the visual voicemail client is enabled.
4459      *
4460      * @param phoneAccountHandle the phone account to check for.
4461      * @return {@code true} when the visual voicemail client is enabled for this client
4462      * @hide
4463      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
4464      * be implemented instead.
4465      */
4466     @SystemApi
4467     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4468     @SuppressLint("Doclava125")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)4469     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
4470         return false;
4471     }
4472 
4473     /**
4474      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
4475      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
4476      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
4477      * voicemail client in telephony.
4478      *
4479      * <p>Requires the caller to be the system dialer.
4480      *
4481      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
4482      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
4483      *
4484      * @hide
4485      */
4486     @SystemApi
4487     @SuppressLint("Doclava125")
4488     @Nullable
getVisualVoicemailSettings()4489     public Bundle getVisualVoicemailSettings(){
4490         try {
4491             ITelephony telephony = getITelephony();
4492             if (telephony != null) {
4493                 return telephony
4494                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
4495             }
4496         } catch (RemoteException ex) {
4497         } catch (NullPointerException ex) {
4498         }
4499         return null;
4500     }
4501 
4502     /**
4503      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
4504      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
4505      * processing visual voicemail for the subscription.
4506      *
4507      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4508      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4509      *
4510      * @see #createForSubscriptionId(int)
4511      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
4512      * @see VisualVoicemailService
4513      */
4514     @Nullable
4515     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4516     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVisualVoicemailPackageName()4517     public String getVisualVoicemailPackageName() {
4518         try {
4519             ITelephony telephony = getITelephony();
4520             if (telephony != null) {
4521                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
4522                         getFeatureId(), getSubId());
4523             }
4524         } catch (RemoteException ex) {
4525         } catch (NullPointerException ex) {
4526         }
4527         return null;
4528     }
4529 
4530     /**
4531      * Set the visual voicemail SMS filter settings for the subscription ID pinned
4532      * to the TelephonyManager.
4533      * When the filter is enabled, {@link
4534      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
4535      * called when a SMS matching the settings is received. Caller must be the default dialer,
4536      * system dialer, or carrier visual voicemail app.
4537      *
4538      * @param settings The settings for the filter, or {@code null} to disable the filter.
4539      *
4540      * @see TelecomManager#getDefaultDialerPackage()
4541      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
4542      */
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)4543     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
4544         if (settings == null) {
4545             disableVisualVoicemailSmsFilter(mSubId);
4546         } else {
4547             enableVisualVoicemailSmsFilter(mSubId, settings);
4548         }
4549     }
4550 
4551     /**
4552      * Send a visual voicemail SMS. The caller must be the current default dialer.
4553      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
4554      * visual voicemail server.  Some examples for carriers using the OMTP standard include
4555      * activating and deactivating visual voicemail, or requesting the current visual voicemail
4556      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
4557      * format of these SMS messages.
4558      *
4559      * <p>Requires Permission:
4560      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
4561      *
4562      * @param number The destination number.
4563      * @param port The destination port for data SMS, or 0 for text SMS.
4564      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
4565      * @param sentIntent The sent intent passed to the {@link SmsManager}
4566      *
4567      * @throws SecurityException if the caller is not the current default dialer
4568      *
4569      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
4570      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
4571      */
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)4572     public void sendVisualVoicemailSms(String number, int port, String text,
4573             PendingIntent sentIntent) {
4574         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
4575     }
4576 
4577     /**
4578      * Enables the visual voicemail SMS filter for a phone account. When the filter is
4579      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
4580      * visual voicemail client with
4581      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
4582      *
4583      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4584      * settings persist through default dialer changes, but the filter will only honor the setting
4585      * set by the current default dialer.
4586      *
4587      *
4588      * @param subId The subscription id of the phone account.
4589      * @param settings The settings for the filter.
4590      */
4591     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)4592     public void enableVisualVoicemailSmsFilter(int subId,
4593             VisualVoicemailSmsFilterSettings settings) {
4594         if(settings == null){
4595             throw new IllegalArgumentException("Settings cannot be null");
4596         }
4597         try {
4598             ITelephony telephony = getITelephony();
4599             if (telephony != null) {
4600                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
4601                         settings);
4602             }
4603         } catch (RemoteException ex) {
4604         } catch (NullPointerException ex) {
4605         }
4606     }
4607 
4608     /**
4609      * Disables the visual voicemail SMS filter for a phone account.
4610      *
4611      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4612      * settings persist through default dialer changes, but the filter will only honor the setting
4613      * set by the current default dialer.
4614      */
4615     /** @hide */
disableVisualVoicemailSmsFilter(int subId)4616     public void disableVisualVoicemailSmsFilter(int subId) {
4617         try {
4618             ITelephony telephony = getITelephony();
4619             if (telephony != null) {
4620                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
4621             }
4622         } catch (RemoteException ex) {
4623         } catch (NullPointerException ex) {
4624         }
4625     }
4626 
4627     /**
4628      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
4629      * if the filter is disabled.
4630      *
4631      * <p>This takes effect only when the caller is the default dialer. The enabled status and
4632      * settings persist through default dialer changes, but the filter will only honor the setting
4633      * set by the current default dialer.
4634      */
4635     /** @hide */
4636     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)4637     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
4638         try {
4639             ITelephony telephony = getITelephony();
4640             if (telephony != null) {
4641                 return telephony
4642                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
4643             }
4644         } catch (RemoteException ex) {
4645         } catch (NullPointerException ex) {
4646         }
4647 
4648         return null;
4649     }
4650 
4651     /**
4652      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
4653      * current active visual voicemail client, or {@code null} if the filter is disabled.
4654      *
4655      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
4656      */
4657     /** @hide */
4658     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)4659     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
4660         try {
4661             ITelephony telephony = getITelephony();
4662             if (telephony != null) {
4663                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
4664             }
4665         } catch (RemoteException ex) {
4666         } catch (NullPointerException ex) {
4667         }
4668 
4669         return null;
4670     }
4671 
4672     /**
4673      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
4674      *
4675      * @param phoneAccountHandle The account to send the SMS with.
4676      * @param number The destination number.
4677      * @param port The destination port for data SMS, or 0 for text SMS.
4678      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
4679      * @param sentIntent The sent intent passed to the {@link SmsManager}
4680      *
4681      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
4682      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
4683      *
4684      * @hide
4685      */
4686     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)4687     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
4688             String text, PendingIntent sentIntent) {
4689         try {
4690             ITelephony telephony = getITelephony();
4691             if (telephony != null) {
4692                 telephony.sendVisualVoicemailSmsForSubscriber(
4693                         mContext.getOpPackageName(), null, subId, number, port, text, sentIntent);
4694             }
4695         } catch (RemoteException ex) {
4696         }
4697     }
4698 
4699     /**
4700      * Initial SIM activation state, unknown. Not set by any carrier apps.
4701      * @hide
4702      */
4703     @SystemApi
4704     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
4705 
4706     /**
4707      * indicate SIM is under activation procedure now.
4708      * intermediate state followed by another state update with activation procedure result:
4709      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4710      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4711      * @see #SIM_ACTIVATION_STATE_RESTRICTED
4712      * @hide
4713      */
4714     @SystemApi
4715     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
4716 
4717     /**
4718      * Indicate SIM has been successfully activated with full service
4719      * @hide
4720      */
4721     @SystemApi
4722     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
4723 
4724     /**
4725      * Indicate SIM has been deactivated by the carrier so that service is not available
4726      * and requires activation service to enable services.
4727      * Carrier apps could be signalled to set activation state to deactivated if detected
4728      * deactivated sim state and set it back to activated after successfully run activation service.
4729      * @hide
4730      */
4731     @SystemApi
4732     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
4733 
4734     /**
4735      * Restricted state indicate SIM has been activated but service are restricted.
4736      * note this is currently available for data activation state. For example out of byte sim.
4737      * @hide
4738      */
4739     @SystemApi
4740     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
4741 
4742      /**
4743       * Sets the voice activation state
4744       *
4745       * <p>Requires Permission:
4746       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
4747       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4748       *
4749       * @param activationState The voice activation state
4750       * @see #SIM_ACTIVATION_STATE_UNKNOWN
4751       * @see #SIM_ACTIVATION_STATE_ACTIVATING
4752       * @see #SIM_ACTIVATION_STATE_ACTIVATED
4753       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4754       * @hide
4755       */
4756     @SystemApi
4757     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(@imActivationState int activationState)4758     public void setVoiceActivationState(@SimActivationState int activationState) {
4759         setVoiceActivationState(getSubId(), activationState);
4760     }
4761 
4762     /**
4763      * Sets the voice activation state for the given subscriber.
4764      *
4765      * <p>Requires Permission:
4766      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
4767      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4768      *
4769      * @param subId The subscription id.
4770      * @param activationState The voice activation state of the given subscriber.
4771      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4772      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4773      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4774      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4775      * @hide
4776      */
4777     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)4778     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
4779         try {
4780            ITelephony telephony = getITelephony();
4781            if (telephony != null)
4782                telephony.setVoiceActivationState(subId, activationState);
4783        } catch (RemoteException ex) {
4784        } catch (NullPointerException ex) {
4785        }
4786     }
4787 
4788     /**
4789      * Sets the data activation state
4790      *
4791      * <p>Requires Permission:
4792      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
4793      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4794      *
4795      * @param activationState The data activation state
4796      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4797      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4798      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4799      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4800      * @see #SIM_ACTIVATION_STATE_RESTRICTED
4801      * @hide
4802      */
4803     @SystemApi
4804     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(@imActivationState int activationState)4805     public void setDataActivationState(@SimActivationState int activationState) {
4806         setDataActivationState(getSubId(), activationState);
4807     }
4808 
4809     /**
4810      * Sets the data activation state for the given subscriber.
4811      *
4812      * <p>Requires Permission:
4813      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
4814      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4815      *
4816      * @param subId The subscription id.
4817      * @param activationState The data activation state of the given subscriber.
4818      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4819      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4820      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4821      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4822      * @see #SIM_ACTIVATION_STATE_RESTRICTED
4823      * @hide
4824      */
4825     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)4826     public void setDataActivationState(int subId, @SimActivationState int activationState) {
4827         try {
4828             ITelephony telephony = getITelephony();
4829             if (telephony != null)
4830                 telephony.setDataActivationState(subId, activationState);
4831         } catch (RemoteException ex) {
4832         } catch (NullPointerException ex) {
4833         }
4834     }
4835 
4836     /**
4837      * Returns the voice activation state
4838      *
4839      * <p>Requires Permission:
4840      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
4841      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4842      *
4843      * @return voiceActivationState
4844      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4845      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4846      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4847      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4848      * @hide
4849      */
4850     @SystemApi
4851     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState()4852     public @SimActivationState int getVoiceActivationState() {
4853         return getVoiceActivationState(getSubId());
4854     }
4855 
4856     /**
4857      * Returns the voice activation state for the given subscriber.
4858      *
4859      * <p>Requires Permission:
4860      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
4861      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4862      *
4863      * @param subId The subscription id.
4864      *
4865      * @return voiceActivationState for the given subscriber
4866      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4867      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4868      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4869      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4870      * @hide
4871      */
4872     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)4873     public @SimActivationState int getVoiceActivationState(int subId) {
4874         try {
4875             ITelephony telephony = getITelephony();
4876             if (telephony != null)
4877                 return telephony.getVoiceActivationState(subId, getOpPackageName());
4878         } catch (RemoteException ex) {
4879         } catch (NullPointerException ex) {
4880         }
4881         return SIM_ACTIVATION_STATE_UNKNOWN;
4882     }
4883 
4884     /**
4885      * Returns the data activation state
4886      *
4887      * <p>Requires Permission:
4888      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
4889      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4890      *
4891      * @return dataActivationState for the given subscriber
4892      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4893      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4894      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4895      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4896      * @see #SIM_ACTIVATION_STATE_RESTRICTED
4897      * @hide
4898      */
4899     @SystemApi
4900     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState()4901     public @SimActivationState int getDataActivationState() {
4902         return getDataActivationState(getSubId());
4903     }
4904 
4905     /**
4906      * Returns the data activation state for the given subscriber.
4907      *
4908      * <p>Requires Permission:
4909      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
4910      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4911      *
4912      * @param subId The subscription id.
4913      *
4914      * @return dataActivationState for the given subscriber
4915      * @see #SIM_ACTIVATION_STATE_UNKNOWN
4916      * @see #SIM_ACTIVATION_STATE_ACTIVATING
4917      * @see #SIM_ACTIVATION_STATE_ACTIVATED
4918      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
4919      * @see #SIM_ACTIVATION_STATE_RESTRICTED
4920      * @hide
4921      */
4922     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)4923     public @SimActivationState int getDataActivationState(int subId) {
4924         try {
4925             ITelephony telephony = getITelephony();
4926             if (telephony != null)
4927                 return telephony.getDataActivationState(subId, getOpPackageName());
4928         } catch (RemoteException ex) {
4929         } catch (NullPointerException ex) {
4930         }
4931         return SIM_ACTIVATION_STATE_UNKNOWN;
4932     }
4933 
4934     /**
4935      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
4936      * but the count is unknown.
4937      * @hide
4938      */
4939     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4940     @UnsupportedAppUsage
getVoiceMessageCount()4941     public int getVoiceMessageCount() {
4942         return getVoiceMessageCount(getSubId());
4943     }
4944 
4945     /**
4946      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
4947      * not have the READ_PHONE_STATE permission.
4948      * @param subId whose voice message count is returned
4949      * @hide
4950      */
4951     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4952     @UnsupportedAppUsage
getVoiceMessageCount(int subId)4953     public int getVoiceMessageCount(int subId) {
4954         try {
4955             ITelephony telephony = getITelephony();
4956             if (telephony == null)
4957                 return 0;
4958             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
4959                     getFeatureId());
4960         } catch (RemoteException ex) {
4961             return 0;
4962         } catch (NullPointerException ex) {
4963             // This could happen before phone restarts due to crashing
4964             return 0;
4965         }
4966     }
4967 
4968     /**
4969      * Retrieves the alphabetic identifier associated with the voice
4970      * mail number.
4971      *
4972      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4973      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4974      */
4975     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4976     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailAlphaTag()4977     public String getVoiceMailAlphaTag() {
4978         return getVoiceMailAlphaTag(getSubId());
4979     }
4980 
4981     /**
4982      * Retrieves the alphabetic identifier associated with the voice
4983      * mail number for a subscription.
4984      * @param subId whose alphabetic identifier associated with the
4985      * voice mail number is returned
4986      * @hide
4987      */
4988     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4989     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)4990     public String getVoiceMailAlphaTag(int subId) {
4991         try {
4992             IPhoneSubInfo info = getSubscriberInfo();
4993             if (info == null)
4994                 return null;
4995             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
4996                     getFeatureId());
4997         } catch (RemoteException ex) {
4998             return null;
4999         } catch (NullPointerException ex) {
5000             // This could happen before phone restarts due to crashing
5001             return null;
5002         }
5003     }
5004 
5005     /**
5006      * Send the special dialer code. The IPC caller must be the current default dialer or have
5007      * carrier privileges (see {@link #hasCarrierPrivileges}).
5008      *
5009      * @param inputCode The special dialer code to send
5010      *
5011      * @throws SecurityException if the caller does not have carrier privileges or is not the
5012      *         current default dialer
5013      */
sendDialerSpecialCode(String inputCode)5014     public void sendDialerSpecialCode(String inputCode) {
5015         try {
5016             final ITelephony telephony = getITelephony();
5017             if (telephony == null) {
5018                 if (!isSystemProcess()) {
5019                     throw new RuntimeException("Telephony service unavailable");
5020                 }
5021                 return;
5022             }
5023             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
5024         } catch (RemoteException ex) {
5025             // This could happen if binder process crashes.
5026             if (!isSystemProcess()) {
5027                 ex.rethrowAsRuntimeException();
5028             }
5029         }
5030     }
5031 
5032     /**
5033      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
5034      * @return the IMPI, or null if not present or not loaded
5035      * @hide
5036      */
5037     @UnsupportedAppUsage
getIsimImpi()5038     public String getIsimImpi() {
5039         try {
5040             IPhoneSubInfo info = getSubscriberInfo();
5041             if (info == null)
5042                 return null;
5043             //get the Isim Impi based on subId
5044             return info.getIsimImpi(getSubId());
5045         } catch (RemoteException ex) {
5046             return null;
5047         } catch (NullPointerException ex) {
5048             // This could happen before phone restarts due to crashing
5049             return null;
5050         }
5051     }
5052 
5053     /**
5054      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
5055      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
5056      * hasn't been loaded or isn't present on the ISIM.
5057      *
5058      * <p>Requires Permission:
5059      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5060      * @hide
5061      */
5062     @Nullable
5063     @SystemApi
5064     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimDomain()5065     public String getIsimDomain() {
5066         try {
5067             IPhoneSubInfo info = getSubscriberInfo();
5068             if (info == null)
5069                 return null;
5070             //get the Isim Domain based on subId
5071             return info.getIsimDomain(getSubId());
5072         } catch (RemoteException ex) {
5073             return null;
5074         } catch (NullPointerException ex) {
5075             // This could happen before phone restarts due to crashing
5076             return null;
5077         }
5078     }
5079 
5080     /**
5081      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
5082      * @return an array of IMPU strings, with one IMPU per string, or null if
5083      *      not present or not loaded
5084      * @hide
5085      */
5086     @UnsupportedAppUsage
5087     @Nullable
5088     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()5089     public String[] getIsimImpu() {
5090         try {
5091             IPhoneSubInfo info = getSubscriberInfo();
5092             if (info == null)
5093                 return null;
5094             //get the Isim Impu based on subId
5095             return info.getIsimImpu(getSubId());
5096         } catch (RemoteException ex) {
5097             return null;
5098         } catch (NullPointerException ex) {
5099             // This could happen before phone restarts due to crashing
5100             return null;
5101         }
5102     }
5103 
5104    /**
5105     * @hide
5106     */
5107     @UnsupportedAppUsage
getSubscriberInfo()5108     private IPhoneSubInfo getSubscriberInfo() {
5109         // get it each time because that process crashes a lot
5110         return IPhoneSubInfo.Stub.asInterface(ServiceManager.getService("iphonesubinfo"));
5111     }
5112 
5113     /**
5114      * Device call state: No activity.
5115      */
5116     public static final int CALL_STATE_IDLE = 0;
5117     /**
5118      * Device call state: Ringing. A new call arrived and is
5119      *  ringing or waiting. In the latter case, another call is
5120      *  already active.
5121      */
5122     public static final int CALL_STATE_RINGING = 1;
5123     /**
5124      * Device call state: Off-hook. At least one call exists
5125      * that is dialing, active, or on hold, and no calls are ringing
5126      * or waiting.
5127      */
5128     public static final int CALL_STATE_OFFHOOK = 2;
5129 
5130     /**
5131      * Returns the state of all calls on the device.
5132      * <p>
5133      * This method considers not only calls in the Telephony stack, but also calls via other
5134      * {@link android.telecom.ConnectionService} implementations.
5135      * <p>
5136      * Note: The call state returned via this method may differ from what is reported by
5137      * {@link PhoneStateListener#onCallStateChanged(int, String)}, as that callback only considers
5138      * Telephony (mobile) calls.
5139      *
5140      * @return the current call state.
5141      */
getCallState()5142     public @CallState int getCallState() {
5143         if (mContext != null) {
5144             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
5145             if (telecomManager != null) {
5146                 return telecomManager.getCallState();
5147             }
5148         }
5149         return CALL_STATE_IDLE;
5150     }
5151 
5152     /**
5153      * Returns the Telephony call state for calls on a specific subscription.
5154      * <p>
5155      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5156      * considers the state of calls from other {@link android.telecom.ConnectionService}
5157      * implementations.
5158      *
5159      * @param subId the subscription to check call state for.
5160      * @hide
5161      */
5162     @UnsupportedAppUsage
getCallState(int subId)5163     public @CallState int getCallState(int subId) {
5164         int phoneId = SubscriptionManager.getPhoneId(subId);
5165         return getCallStateForSlot(phoneId);
5166     }
5167 
5168     /**
5169      * Returns the Telephony call state for calls on a specific SIM slot.
5170      * <p>
5171      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5172      * considers the state of calls from other {@link android.telecom.ConnectionService}
5173      * implementations.
5174      *
5175      * @param slotIndex the SIM slot index to check call state for.
5176      * @hide
5177      */
getCallStateForSlot(int slotIndex)5178     public @CallState int getCallStateForSlot(int slotIndex) {
5179         try {
5180             ITelephony telephony = getITelephony();
5181             if (telephony == null)
5182                 return CALL_STATE_IDLE;
5183             return telephony.getCallStateForSlot(slotIndex);
5184         } catch (RemoteException ex) {
5185             // the phone process is restarting.
5186             return CALL_STATE_IDLE;
5187         } catch (NullPointerException ex) {
5188           // the phone process is restarting.
5189           return CALL_STATE_IDLE;
5190         }
5191     }
5192 
5193 
5194     /** Data connection activity: No traffic. */
5195     public static final int DATA_ACTIVITY_NONE = 0x00000000;
5196     /** Data connection activity: Currently receiving IP PPP traffic. */
5197     public static final int DATA_ACTIVITY_IN = 0x00000001;
5198     /** Data connection activity: Currently sending IP PPP traffic. */
5199     public static final int DATA_ACTIVITY_OUT = 0x00000002;
5200     /** Data connection activity: Currently both sending and receiving
5201      *  IP PPP traffic. */
5202     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
5203     /**
5204      * Data connection is active, but physical link is down
5205      */
5206     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
5207 
5208     /** @hide */
5209     @IntDef(prefix = {"DATA_"}, value = {
5210         DATA_ACTIVITY_NONE,
5211         DATA_ACTIVITY_IN,
5212         DATA_ACTIVITY_OUT,
5213         DATA_ACTIVITY_INOUT,
5214         DATA_ACTIVITY_DORMANT,
5215     })
5216     @Retention(RetentionPolicy.SOURCE)
5217     public @interface DataActivityType{}
5218 
5219     /**
5220      * Returns a constant indicating the type of activity on a data connection
5221      * (cellular).
5222      *
5223      * @see #DATA_ACTIVITY_NONE
5224      * @see #DATA_ACTIVITY_IN
5225      * @see #DATA_ACTIVITY_OUT
5226      * @see #DATA_ACTIVITY_INOUT
5227      * @see #DATA_ACTIVITY_DORMANT
5228      */
getDataActivity()5229     public int getDataActivity() {
5230         try {
5231             ITelephony telephony = getITelephony();
5232             if (telephony == null)
5233                 return DATA_ACTIVITY_NONE;
5234             return telephony.getDataActivityForSubId(
5235                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5236         } catch (RemoteException ex) {
5237             // the phone process is restarting.
5238             return DATA_ACTIVITY_NONE;
5239         } catch (NullPointerException ex) {
5240           // the phone process is restarting.
5241           return DATA_ACTIVITY_NONE;
5242       }
5243     }
5244 
5245     /** @hide */
5246     @IntDef(prefix = {"DATA_"}, value = {
5247             DATA_UNKNOWN,
5248             DATA_DISCONNECTED,
5249             DATA_CONNECTING,
5250             DATA_CONNECTED,
5251             DATA_SUSPENDED,
5252             DATA_DISCONNECTING,
5253     })
5254     @Retention(RetentionPolicy.SOURCE)
5255     public @interface DataState{}
5256 
5257     /** Data connection state: Unknown.  Used before we know the state. */
5258     public static final int DATA_UNKNOWN        = -1;
5259     /** Data connection state: Disconnected. IP traffic not available. */
5260     public static final int DATA_DISCONNECTED   = 0;
5261     /** Data connection state: Currently setting up a data connection. */
5262     public static final int DATA_CONNECTING     = 1;
5263     /** Data connection state: Connected. IP traffic should be available. */
5264     public static final int DATA_CONNECTED      = 2;
5265     /** Data connection state: Suspended. The connection is up, but IP
5266      * traffic is temporarily unavailable. For example, in a 2G network,
5267      * data activity may be suspended when a voice call arrives. */
5268     public static final int DATA_SUSPENDED      = 3;
5269     /**
5270      * Data connection state: Disconnecting.
5271      *
5272      * IP traffic may be available but will cease working imminently.
5273      */
5274     public static final int DATA_DISCONNECTING = 4;
5275 
5276     /**
5277      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
5278      */
5279     @ChangeId
5280     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
5281     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
5282 
5283     /**
5284      * Returns a constant indicating the current data connection state
5285      * (cellular).
5286      *
5287      * @see #DATA_DISCONNECTED
5288      * @see #DATA_CONNECTING
5289      * @see #DATA_CONNECTED
5290      * @see #DATA_SUSPENDED
5291      * @see #DATA_DISCONNECTING
5292      */
getDataState()5293     public int getDataState() {
5294         try {
5295             ITelephony telephony = getITelephony();
5296             if (telephony == null)
5297                 return DATA_DISCONNECTED;
5298             int state = telephony.getDataStateForSubId(
5299                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5300             if (state == TelephonyManager.DATA_DISCONNECTING
5301                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
5302                 return TelephonyManager.DATA_CONNECTED;
5303             }
5304 
5305             return state;
5306         } catch (RemoteException ex) {
5307             // the phone process is restarting.
5308             return DATA_DISCONNECTED;
5309         } catch (NullPointerException ex) {
5310             return DATA_DISCONNECTED;
5311         }
5312     }
5313 
5314     /**
5315      * Convert data state to string
5316      *
5317      * @return The data state in string format.
5318      * @hide
5319      */
dataStateToString(@ataState int state)5320     public static String dataStateToString(@DataState int state) {
5321         switch (state) {
5322             case DATA_DISCONNECTED: return "DISCONNECTED";
5323             case DATA_CONNECTING: return "CONNECTING";
5324             case DATA_CONNECTED: return "CONNECTED";
5325             case DATA_SUSPENDED: return "SUSPENDED";
5326             case DATA_DISCONNECTING: return "DISCONNECTING";
5327         }
5328         return "UNKNOWN(" + state + ")";
5329     }
5330 
5331    /**
5332     * @hide
5333     */
5334     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getITelephony()5335     private ITelephony getITelephony() {
5336         return ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
5337     }
5338 
getTelephonyRegistry()5339     private ITelephonyRegistry getTelephonyRegistry() {
5340         return ITelephonyRegistry.Stub.asInterface(ServiceManager.getService("telephony.registry"));
5341     }
5342 
getIOns()5343     private IOns getIOns() {
5344         return IOns.Stub.asInterface(ServiceManager.getService("ions"));
5345     }
5346 
5347     //
5348     //
5349     // PhoneStateListener
5350     //
5351     //
5352 
5353     /**
5354      * To check the SDK version for {@link TelephonyManager#listen}.
5355      */
5356     @ChangeId
5357     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.P)
5358     private static final long LISTEN_CODE_CHANGE = 147600208L;
5359 
5360     /**
5361      * Registers a listener object to receive notification of changes
5362      * in specified telephony states.
5363      * <p>
5364      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
5365      * state of interest in the events argument.
5366      *
5367      * At registration, and when a specified telephony state changes, the telephony manager invokes
5368      * the appropriate callback method on the listener object and passes the current (updated)
5369      * values.
5370      * <p>
5371      * To un-register a listener, pass the listener object and set the events argument to
5372      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
5373      *
5374      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
5375      * applies to the given subId. Otherwise, applies to
5376      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
5377      * pass a separate listener object to each TelephonyManager object created with
5378      * {@link #createForSubscriptionId}.
5379      *
5380      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
5381      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
5382      * {@link SecurityException} will be thrown otherwise.
5383      *
5384      * This API should be used sparingly -- large numbers of listeners will cause system
5385      * instability. If a process has registered too many listeners without unregistering them, it
5386      * may encounter an {@link IllegalStateException} when trying to register more listeners.
5387      *
5388      * @param listener The {@link PhoneStateListener} object to register
5389      *                 (or unregister)
5390      * @param events The telephony state(s) of interest to the listener,
5391      *               as a bitwise-OR combination of {@link PhoneStateListener}
5392      *               LISTEN_ flags.
5393      */
listen(PhoneStateListener listener, int events)5394     public void listen(PhoneStateListener listener, int events) {
5395         if (mContext == null) return;
5396         try {
5397             boolean notifyNow = (getITelephony() != null);
5398             ITelephonyRegistry registry = getTelephonyRegistry();
5399             if (registry != null) {
5400                 // subId from PhoneStateListener is deprecated Q on forward, use the subId from
5401                 // TelephonyManager instance. keep using subId from PhoneStateListener for pre-Q.
5402                 int subId = mSubId;
5403                 if (Compatibility.isChangeEnabled(LISTEN_CODE_CHANGE)) {
5404                     // since mSubId in PhoneStateListener is deprecated from Q on forward, this is
5405                     // the only place to set mSubId and its for "informational" only.
5406                     //  TODO: remove this once we completely get rid of mSubId in PhoneStateListener
5407                     listener.mSubId = (events == PhoneStateListener.LISTEN_NONE)
5408                             ? SubscriptionManager.INVALID_SUBSCRIPTION_ID : subId;
5409                 } else if (listener.mSubId != null) {
5410                     subId = listener.mSubId;
5411                 }
5412                 registry.listenForSubscriber(subId, getOpPackageName(), getFeatureId(),
5413                         listener.callback, events, notifyNow);
5414             } else {
5415                 Rlog.w(TAG, "telephony registry not ready.");
5416             }
5417         } catch (RemoteException ex) {
5418             // system process dead
5419         }
5420     }
5421 
5422     /**
5423      * Returns the CDMA ERI icon index to display
5424      * @hide
5425      */
5426     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriIconIndex()5427     public int getCdmaEriIconIndex() {
5428         return getCdmaEriIconIndex(getSubId());
5429     }
5430 
5431     /**
5432      * Returns the CDMA ERI icon index to display for a subscription
5433      * @hide
5434      */
5435     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5436     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)5437     public int getCdmaEriIconIndex(int subId) {
5438         try {
5439             ITelephony telephony = getITelephony();
5440             if (telephony == null)
5441                 return -1;
5442             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
5443                     getFeatureId());
5444         } catch (RemoteException ex) {
5445             // the phone process is restarting.
5446             return -1;
5447         } catch (NullPointerException ex) {
5448             return -1;
5449         }
5450     }
5451 
5452     /**
5453      * Returns the CDMA ERI icon mode,
5454      * 0 - ON
5455      * 1 - FLASHING
5456      *
5457      * @hide
5458      */
5459     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriIconMode()5460     public int getCdmaEriIconMode() {
5461         return getCdmaEriIconMode(getSubId());
5462     }
5463 
5464     /**
5465      * Returns the CDMA ERI icon mode for a subscription.
5466      * 0 - ON
5467      * 1 - FLASHING
5468      *
5469      * @hide
5470      */
5471     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5472     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)5473     public int getCdmaEriIconMode(int subId) {
5474         try {
5475             ITelephony telephony = getITelephony();
5476             if (telephony == null)
5477                 return -1;
5478             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
5479                     getFeatureId());
5480         } catch (RemoteException ex) {
5481             // the phone process is restarting.
5482             return -1;
5483         } catch (NullPointerException ex) {
5484             return -1;
5485         }
5486     }
5487 
5488     /**
5489      * Returns the CDMA ERI text,
5490      *
5491      * @hide
5492      */
5493     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()5494     public String getCdmaEriText() {
5495         return getCdmaEriText(getSubId());
5496     }
5497 
5498     /**
5499      * Returns the CDMA ERI text, of a subscription
5500      *
5501      * @hide
5502      */
5503     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5504     @UnsupportedAppUsage
getCdmaEriText(int subId)5505     public String getCdmaEriText(int subId) {
5506         try {
5507             ITelephony telephony = getITelephony();
5508             if (telephony == null)
5509                 return null;
5510             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
5511                     getFeatureId());
5512         } catch (RemoteException ex) {
5513             // the phone process is restarting.
5514             return null;
5515         } catch (NullPointerException ex) {
5516             return null;
5517         }
5518     }
5519 
5520     /**
5521      * @return true if the current device is "voice capable".
5522      * <p>
5523      * "Voice capable" means that this device supports circuit-switched
5524      * (i.e. voice) phone calls over the telephony network, and is allowed
5525      * to display the in-call UI while a cellular voice call is active.
5526      * This will be false on "data only" devices which can't make voice
5527      * calls and don't support any in-call UI.
5528      * <p>
5529      * Note: the meaning of this flag is subtly different from the
5530      * PackageManager.FEATURE_TELEPHONY system feature, which is available
5531      * on any device with a telephony radio, even if the device is
5532      * data-only.
5533      */
isVoiceCapable()5534     public boolean isVoiceCapable() {
5535         if (mContext == null) return true;
5536         return mContext.getResources().getBoolean(
5537                 com.android.internal.R.bool.config_voice_capable);
5538     }
5539 
5540     /**
5541      * @return true if the current device supports sms service.
5542      * <p>
5543      * If true, this means that the device supports both sending and
5544      * receiving sms via the telephony network.
5545      * <p>
5546      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
5547      *       disabled when device doesn't support sms.
5548      */
isSmsCapable()5549     public boolean isSmsCapable() {
5550         if (mContext == null) return true;
5551         return mContext.getResources().getBoolean(
5552                 com.android.internal.R.bool.config_sms_capable);
5553     }
5554 
5555     /**
5556      * Requests all available cell information from all radios on the device including the
5557      * camped/registered, serving, and neighboring cells.
5558      *
5559      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
5560      * {@link android.telephony.CellInfoCdma CellInfoCdma},
5561      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
5562      * {@link android.telephony.CellInfoLte CellInfoLte}, and
5563      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
5564      * It is typical to see instances of one or more of any these in the list. In addition, zero
5565      * or more of the returned objects may be considered registered; that is, their
5566      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
5567      * methods may return true, indicating that the cell is being used or would be used for
5568      * signaling communication if necessary.
5569      *
5570      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
5571      * if this API results in a change of the cached CellInfo, that change will be reported via
5572      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}.
5573      *
5574      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
5575      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
5576      * will receive the latest cached results, which may not be current. Apps targeting
5577      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
5578      * CellInfo should call
5579      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
5580      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
5581      * recency of CellInfo data, callers should check
5582      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
5583      *
5584      * <p>This method returns valid data for devices with
5585      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
5586      * where only partial information is available for a particular CellInfo entry, unavailable
5587      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
5588      * cells will include at least a valid set of technology-specific identification info and a
5589      * power level measurement.
5590      *
5591      * <p>This method is preferred over using {@link
5592      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
5593      *
5594      * @return List of {@link android.telephony.CellInfo}; null if cell
5595      * information is unavailable.
5596      */
5597     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getAllCellInfo()5598     public List<CellInfo> getAllCellInfo() {
5599         try {
5600             ITelephony telephony = getITelephony();
5601             if (telephony == null)
5602                 return null;
5603             return telephony.getAllCellInfo(getOpPackageName(), getFeatureId());
5604         } catch (RemoteException ex) {
5605         } catch (NullPointerException ex) {
5606         }
5607         return null;
5608     }
5609 
5610     /** Callback for providing asynchronous {@link CellInfo} on request */
5611     public abstract static class CellInfoCallback {
5612         /**
5613          * Success response to
5614          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
5615          *
5616          * Invoked when there is a response to
5617          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
5618          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
5619          * list will be provided. If an error occurs, null will be provided unless the onError
5620          * callback is overridden.
5621          *
5622          * @param cellInfo a list of {@link CellInfo}, an empty list, or null.
5623          *
5624          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
5625          */
onCellInfo(@onNull List<CellInfo> cellInfo)5626         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
5627 
5628         /** @hide */
5629         @Retention(RetentionPolicy.SOURCE)
5630         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
5631         public @interface CellInfoCallbackError {}
5632 
5633         /**
5634          * The system timed out waiting for a response from the Radio.
5635          */
5636         public static final int ERROR_TIMEOUT = 1;
5637 
5638         /**
5639          * The modem returned a failure.
5640          */
5641         public static final int ERROR_MODEM_ERROR = 2;
5642 
5643         /**
5644          * Error response to
5645          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
5646          *
5647          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
5648          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
5649          * function to receive detailed status information in the event of an error. By default,
5650          * this function will invoke onCellInfo() with null.
5651          *
5652          * @param errorCode an error code indicating the type of failure.
5653          * @param detail a Throwable object with additional detail regarding the failure if
5654          *     available, otherwise null.
5655          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)5656         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
5657             // By default, simply invoke the success callback with an empty list.
5658             onCellInfo(new ArrayList<CellInfo>());
5659         }
5660     };
5661 
5662     /**
5663      * Requests all available cell information from the current subscription for observed
5664      * camped/registered, serving, and neighboring cells.
5665      *
5666      * <p>Any available results from this request will be provided by calls to
5667      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
5668      * for each active subscription.
5669      *
5670      * @param executor the executor on which callback will be invoked.
5671      * @param callback a callback to receive CellInfo.
5672      */
5673     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)5674     public void requestCellInfoUpdate(
5675             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
5676         try {
5677             ITelephony telephony = getITelephony();
5678             if (telephony == null) return;
5679             telephony.requestCellInfoUpdate(
5680                     getSubId(),
5681                     new ICellInfoCallback.Stub() {
5682                         @Override
5683                         public void onCellInfo(List<CellInfo> cellInfo) {
5684                             final long identity = Binder.clearCallingIdentity();
5685                             try {
5686                                 executor.execute(() -> callback.onCellInfo(cellInfo));
5687                             } finally {
5688                                 Binder.restoreCallingIdentity(identity);
5689                             }
5690                         }
5691 
5692                         @Override
5693                         public void onError(int errorCode, String exceptionName, String message) {
5694                             final long identity = Binder.clearCallingIdentity();
5695                             try {
5696                                 executor.execute(() -> callback.onError(
5697                                         errorCode,
5698                                         createThrowableByClassName(exceptionName, message)));
5699                             } finally {
5700                                 Binder.restoreCallingIdentity(identity);
5701                             }
5702                         }
5703                     }, getOpPackageName(), getFeatureId());
5704         } catch (RemoteException ex) {
5705         }
5706     }
5707 
5708     /**
5709      * Requests all available cell information from the current subscription for observed
5710      * camped/registered, serving, and neighboring cells.
5711      *
5712      * <p>Any available results from this request will be provided by calls to
5713      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
5714      * for each active subscription.
5715      *
5716      * @param workSource the requestor to whom the power consumption for this should be attributed.
5717      * @param executor the executor on which callback will be invoked.
5718      * @param callback a callback to receive CellInfo.
5719      * @hide
5720      */
5721     @SystemApi
5722     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
5723             android.Manifest.permission.MODIFY_PHONE_STATE})
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)5724     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
5725             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
5726         try {
5727             ITelephony telephony = getITelephony();
5728             if (telephony == null) return;
5729             telephony.requestCellInfoUpdateWithWorkSource(
5730                     getSubId(),
5731                     new ICellInfoCallback.Stub() {
5732                         @Override
5733                         public void onCellInfo(List<CellInfo> cellInfo) {
5734                             final long identity = Binder.clearCallingIdentity();
5735                             try {
5736                                 executor.execute(() -> callback.onCellInfo(cellInfo));
5737                             } finally {
5738                                 Binder.restoreCallingIdentity(identity);
5739                             }
5740 
5741                         }
5742 
5743                         @Override
5744                         public void onError(int errorCode, String exceptionName, String message) {
5745                             final long identity = Binder.clearCallingIdentity();
5746                             try {
5747                                 executor.execute(() -> callback.onError(
5748                                         errorCode,
5749                                         createThrowableByClassName(exceptionName, message)));
5750                             } finally {
5751                                 Binder.restoreCallingIdentity(identity);
5752                             }
5753                         }
5754                     }, getOpPackageName(), getFeatureId(), workSource);
5755         } catch (RemoteException ex) {
5756         }
5757     }
5758 
createThrowableByClassName(String className, String message)5759     private static Throwable createThrowableByClassName(String className, String message) {
5760         if (className == null) {
5761             return null;
5762         }
5763         try {
5764             Class<?> c = Class.forName(className);
5765             return (Throwable) c.getConstructor(String.class).newInstance(message);
5766         } catch (ReflectiveOperationException | ClassCastException e) {
5767         }
5768         return new RuntimeException(className + ": " + message);
5769     }
5770 
5771     /**
5772      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
5773      * PhoneStateListener.onCellInfoChanged} will be invoked.
5774      *<p>
5775      * The default, 0, means invoke onCellInfoChanged when any of the reported
5776      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
5777      * A onCellInfoChanged.
5778      *<p>
5779      * @param rateInMillis the rate
5780      *
5781      * @hide
5782      */
setCellInfoListRate(int rateInMillis)5783     public void setCellInfoListRate(int rateInMillis) {
5784         try {
5785             ITelephony telephony = getITelephony();
5786             if (telephony != null)
5787                 telephony.setCellInfoListRate(rateInMillis);
5788         } catch (RemoteException ex) {
5789         } catch (NullPointerException ex) {
5790         }
5791     }
5792 
5793     /**
5794      * Returns the MMS user agent.
5795      */
getMmsUserAgent()5796     public String getMmsUserAgent() {
5797         try {
5798             ITelephony telephony = getITelephony();
5799             if (telephony != null) {
5800                 return telephony.getMmsUserAgent(getSubId());
5801             }
5802         } catch (RemoteException ex) {
5803         } catch (NullPointerException ex) {
5804         }
5805         return null;
5806     }
5807 
5808     /**
5809      * Returns the MMS user agent profile URL.
5810      */
getMmsUAProfUrl()5811     public String getMmsUAProfUrl() {
5812         try {
5813             ITelephony telephony = getITelephony();
5814             if (telephony != null) {
5815                 return telephony.getMmsUAProfUrl(getSubId());
5816             }
5817         } catch (RemoteException ex) {
5818         } catch (NullPointerException ex) {
5819         }
5820         return null;
5821     }
5822 
5823     /**
5824      * Opens a logical channel to the ICC card.
5825      *
5826      * Input parameters equivalent to TS 27.007 AT+CCHO command.
5827      *
5828      * <p>Requires Permission:
5829      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
5830      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
5831      *
5832      * @param AID Application id. See ETSI 102.221 and 101.220.
5833      * @return an IccOpenLogicalChannelResponse object.
5834      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
5835      */
5836     @Deprecated
iccOpenLogicalChannel(String AID)5837     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
5838         return iccOpenLogicalChannel(getSubId(), AID, -1);
5839     }
5840 
5841     /**
5842      * Opens a logical channel to the ICC card using the physical slot index.
5843      *
5844      * Use this method when no subscriptions are available on the SIM and the operation must be
5845      * performed using the physical slot index.
5846      *
5847      * This operation wraps two APDU instructions:
5848      * <ul>
5849      *     <li>MANAGE CHANNEL to open a logical channel</li>
5850      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
5851      * </ul>
5852      *
5853      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
5854      * and 0x0C are guaranteed to be supported.
5855      *
5856      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
5857      * considered an error and the channel shall not be opened.
5858      *
5859      * Input parameters equivalent to TS 27.007 AT+CCHO command.
5860      *
5861      * <p>Requires Permission:
5862      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
5863      *
5864      * @param slotIndex the physical slot index of the ICC card
5865      * @param aid Application id. See ETSI 102.221 and 101.220.
5866      * @param p2 P2 parameter (described in ISO 7816-4).
5867      * @return an IccOpenLogicalChannelResponse object.
5868      * @hide
5869      */
5870     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
5871     @SystemApi
5872     @Nullable
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)5873     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
5874             @Nullable String aid, int p2) {
5875         try {
5876             ITelephony telephony = getITelephony();
5877             if (telephony != null) {
5878                 return telephony.iccOpenLogicalChannelBySlot(slotIndex, getOpPackageName(), aid,
5879                         p2);
5880             }
5881         } catch (RemoteException ex) {
5882         } catch (NullPointerException ex) {
5883         }
5884         return null;
5885     }
5886 
5887     /**
5888      * Opens a logical channel to the ICC card.
5889      *
5890      * This operation wraps two APDU instructions:
5891      * <ul>
5892      *     <li>MANAGE CHANNEL to open a logical channel</li>
5893      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
5894      * </ul>
5895      *
5896      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
5897      * and 0x0C are guaranteed to be supported.
5898      *
5899      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
5900      * considered an error and the channel shall not be opened.
5901      *
5902      * Input parameters equivalent to TS 27.007 AT+CCHO command.
5903      *
5904      * <p>Requires Permission:
5905      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
5906      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
5907      *
5908      * @param AID Application id. See ETSI 102.221 and 101.220.
5909      * @param p2 P2 parameter (described in ISO 7816-4).
5910      * @return an IccOpenLogicalChannelResponse object.
5911      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
5912      *             {@link android.se.omapi.SEService#getUiccReader(int)},
5913      *             {@link android.se.omapi.Reader#openSession()},
5914      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
5915      */
5916     @Deprecated
iccOpenLogicalChannel(String AID, int p2)5917     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
5918         return iccOpenLogicalChannel(getSubId(), AID, p2);
5919     }
5920 
5921     /**
5922      * Opens a logical channel to the ICC card.
5923      *
5924      * This operation wraps two APDU instructions:
5925      * <ul>
5926      *     <li>MANAGE CHANNEL to open a logical channel</li>
5927      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
5928      * </ul>
5929      *
5930      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
5931      * and 0x0C are guaranteed to be supported.
5932      *
5933      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
5934      * considered an error and the channel shall not be opened.
5935      *
5936      * Input parameters equivalent to TS 27.007 AT+CCHO command.
5937      *
5938      * <p>Requires Permission:
5939      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
5940      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
5941      *
5942      * @param subId The subscription to use.
5943      * @param AID Application id. See ETSI 102.221 and 101.220.
5944      * @param p2 P2 parameter (described in ISO 7816-4).
5945      * @return an IccOpenLogicalChannelResponse object.
5946      * @hide
5947      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
5948      *             {@link android.se.omapi.SEService#getUiccReader(int)},
5949      *             {@link android.se.omapi.Reader#openSession()},
5950      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
5951      */
5952     @Deprecated
iccOpenLogicalChannel(int subId, String AID, int p2)5953     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
5954         try {
5955             ITelephony telephony = getITelephony();
5956             if (telephony != null)
5957                 return telephony.iccOpenLogicalChannel(subId, getOpPackageName(), AID, p2);
5958         } catch (RemoteException ex) {
5959         } catch (NullPointerException ex) {
5960         }
5961         return null;
5962     }
5963 
5964     /**
5965      * Closes a previously opened logical channel to the ICC card using the physical slot index.
5966      *
5967      * Use this method when no subscriptions are available on the SIM and the operation must be
5968      * performed using the physical slot index.
5969      *
5970      * Input parameters equivalent to TS 27.007 AT+CCHC command.
5971      *
5972      * <p>Requires Permission:
5973      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
5974      *
5975      * @param slotIndex the physical slot index of the ICC card
5976      * @param channel is the channel id to be closed as returned by a successful
5977      *            iccOpenLogicalChannel.
5978      * @return true if the channel was closed successfully.
5979      * @hide
5980      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
5981      *             {@link android.se.omapi.Channel#close()}.
5982      */
5983     @Deprecated
5984     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
5985     @SystemApi
iccCloseLogicalChannelBySlot(int slotIndex, int channel)5986     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
5987         try {
5988             ITelephony telephony = getITelephony();
5989             if (telephony != null) {
5990                 return telephony.iccCloseLogicalChannelBySlot(slotIndex, channel);
5991             }
5992         } catch (RemoteException ex) {
5993         } catch (NullPointerException ex) {
5994         }
5995         return false;
5996     }
5997 
5998     /**
5999      * Closes a previously opened logical channel to the ICC card.
6000      *
6001      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6002      *
6003      * <p>Requires Permission:
6004      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6005      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6006      *
6007      * @param channel is the channel id to be closed as returned by a successful
6008      *            iccOpenLogicalChannel.
6009      * @return true if the channel was closed successfully.
6010      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6011      *             {@link android.se.omapi.Channel#close()}.
6012      */
6013     @Deprecated
iccCloseLogicalChannel(int channel)6014     public boolean iccCloseLogicalChannel(int channel) {
6015         return iccCloseLogicalChannel(getSubId(), channel);
6016     }
6017 
6018     /**
6019      * Closes a previously opened logical channel to the ICC card.
6020      *
6021      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6022      *
6023      * <p>Requires Permission:
6024      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6025      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6026      *
6027      * @param subId The subscription to use.
6028      * @param channel is the channel id to be closed as returned by a successful
6029      *            iccOpenLogicalChannel.
6030      * @return true if the channel was closed successfully.
6031      * @hide
6032      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6033      *             {@link android.se.omapi.Channel#close()}.
6034      */
6035     @Deprecated
iccCloseLogicalChannel(int subId, int channel)6036     public boolean iccCloseLogicalChannel(int subId, int channel) {
6037         try {
6038             ITelephony telephony = getITelephony();
6039             if (telephony != null)
6040                 return telephony.iccCloseLogicalChannel(subId, channel);
6041         } catch (RemoteException ex) {
6042         } catch (NullPointerException ex) {
6043         }
6044         return false;
6045     }
6046 
6047     /**
6048      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
6049      *
6050      * Use this method when no subscriptions are available on the SIM and the operation must be
6051      * performed using the physical slot index.
6052      *
6053      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6054      *
6055      * <p>Requires Permission:
6056      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6057      *
6058      * @param slotIndex the physical slot index of the ICC card
6059      * @param channel is the channel id to be closed as returned by a successful
6060      *            iccOpenLogicalChannel.
6061      * @param cla Class of the APDU command.
6062      * @param instruction Instruction of the APDU command.
6063      * @param p1 P1 value of the APDU command.
6064      * @param p2 P2 value of the APDU command.
6065      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6066      *            is sent to the SIM.
6067      * @param data Data to be sent with the APDU.
6068      * @return The APDU response from the ICC card with the status appended at the end, or null if
6069      * there is an issue connecting to the Telephony service.
6070      * @hide
6071      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6072      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6073      */
6074     @Deprecated
6075     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6076     @SystemApi
6077     @Nullable
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6078     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
6079             int instruction, int p1, int p2, int p3, @Nullable String data) {
6080         try {
6081             ITelephony telephony = getITelephony();
6082             if (telephony != null) {
6083                 return telephony.iccTransmitApduLogicalChannelBySlot(slotIndex, channel, cla,
6084                         instruction, p1, p2, p3, data);
6085             }
6086         } catch (RemoteException ex) {
6087         } catch (NullPointerException ex) {
6088         }
6089         return null;
6090     }
6091 
6092     /**
6093      * Transmit an APDU to the ICC card over a logical channel.
6094      *
6095      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6096      *
6097      * <p>Requires Permission:
6098      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6099      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6100      *
6101      * @param channel is the channel id to be closed as returned by a successful
6102      *            iccOpenLogicalChannel.
6103      * @param cla Class of the APDU command.
6104      * @param instruction Instruction of the APDU command.
6105      * @param p1 P1 value of the APDU command.
6106      * @param p2 P2 value of the APDU command.
6107      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6108      *            is sent to the SIM.
6109      * @param data Data to be sent with the APDU.
6110      * @return The APDU response from the ICC card with the status appended at
6111      *            the end.
6112      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6113      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6114      */
6115     @Deprecated
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)6116     public String iccTransmitApduLogicalChannel(int channel, int cla,
6117             int instruction, int p1, int p2, int p3, String data) {
6118         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
6119                     instruction, p1, p2, p3, data);
6120     }
6121 
6122     /**
6123      * Transmit an APDU to the ICC card over a logical channel.
6124      *
6125      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6126      *
6127      * <p>Requires Permission:
6128      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6129      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6130      *
6131      * @param subId The subscription to use.
6132      * @param channel is the channel id to be closed as returned by a successful
6133      *            iccOpenLogicalChannel.
6134      * @param cla Class of the APDU command.
6135      * @param instruction Instruction of the APDU command.
6136      * @param p1 P1 value of the APDU command.
6137      * @param p2 P2 value of the APDU command.
6138      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6139      *            is sent to the SIM.
6140      * @param data Data to be sent with the APDU.
6141      * @return The APDU response from the ICC card with the status appended at
6142      *            the end.
6143      * @hide
6144      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6145      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6146      */
6147     @Deprecated
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)6148     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
6149             int instruction, int p1, int p2, int p3, String data) {
6150         try {
6151             ITelephony telephony = getITelephony();
6152             if (telephony != null)
6153                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
6154                     instruction, p1, p2, p3, data);
6155         } catch (RemoteException ex) {
6156         } catch (NullPointerException ex) {
6157         }
6158         return "";
6159     }
6160 
6161     /**
6162      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
6163      *
6164      * Use this method when no subscriptions are available on the SIM and the operation must be
6165      * performed using the physical slot index.
6166      *
6167      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6168      *
6169      * <p>Requires Permission:
6170      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6171      *
6172      * @param slotIndex the physical slot index of the ICC card to target
6173      * @param cla Class of the APDU command.
6174      * @param instruction Instruction of the APDU command.
6175      * @param p1 P1 value of the APDU command.
6176      * @param p2 P2 value of the APDU command.
6177      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6178      *            is sent to the SIM.
6179      * @param data Data to be sent with the APDU.
6180      * @return The APDU response from the ICC card with the status appended at
6181      *            the end.
6182      * @hide
6183      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6184      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6185      *             {@link android.se.omapi.Reader#openSession()},
6186      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6187      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6188      */
6189     @Deprecated
6190     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6191     @SystemApi
6192     @NonNull
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6193     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
6194             int p2, int p3, @Nullable String data) {
6195         try {
6196             ITelephony telephony = getITelephony();
6197             if (telephony != null) {
6198                 return telephony.iccTransmitApduBasicChannelBySlot(slotIndex, getOpPackageName(),
6199                         cla, instruction, p1, p2, p3, data);
6200             }
6201         } catch (RemoteException ex) {
6202         } catch (NullPointerException ex) {
6203         }
6204         return null;
6205     }
6206 
6207     /**
6208      * Transmit an APDU to the ICC card over the basic channel.
6209      *
6210      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6211      *
6212      * <p>Requires Permission:
6213      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6214      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6215      *
6216      * @param cla Class of the APDU command.
6217      * @param instruction Instruction of the APDU command.
6218      * @param p1 P1 value of the APDU command.
6219      * @param p2 P2 value of the APDU command.
6220      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6221      *            is sent to the SIM.
6222      * @param data Data to be sent with the APDU.
6223      * @return The APDU response from the ICC card with the status appended at
6224      *            the end.
6225      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6226      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6227      *             {@link android.se.omapi.Reader#openSession()},
6228      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6229      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6230      */
6231     @Deprecated
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)6232     public String iccTransmitApduBasicChannel(int cla,
6233             int instruction, int p1, int p2, int p3, String data) {
6234         return iccTransmitApduBasicChannel(getSubId(), cla,
6235                     instruction, p1, p2, p3, data);
6236     }
6237 
6238     /**
6239      * Transmit an APDU to the ICC card over the basic channel.
6240      *
6241      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6242      *
6243      * <p>Requires Permission:
6244      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6245      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6246      *
6247      * @param subId The subscription to use.
6248      * @param cla Class of the APDU command.
6249      * @param instruction Instruction of the APDU command.
6250      * @param p1 P1 value of the APDU command.
6251      * @param p2 P2 value of the APDU command.
6252      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6253      *            is sent to the SIM.
6254      * @param data Data to be sent with the APDU.
6255      * @return The APDU response from the ICC card with the status appended at
6256      *            the end.
6257      * @hide
6258      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6259      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6260      *             {@link android.se.omapi.Reader#openSession()},
6261      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6262      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6263      */
6264     @Deprecated
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)6265     public String iccTransmitApduBasicChannel(int subId, int cla,
6266             int instruction, int p1, int p2, int p3, String data) {
6267         try {
6268             ITelephony telephony = getITelephony();
6269             if (telephony != null)
6270                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
6271                     instruction, p1, p2, p3, data);
6272         } catch (RemoteException ex) {
6273         } catch (NullPointerException ex) {
6274         }
6275         return "";
6276     }
6277 
6278     /**
6279      * Returns the response APDU for a command APDU sent through SIM_IO.
6280      *
6281      * <p>Requires Permission:
6282      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6283      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6284      *
6285      * @param fileID
6286      * @param command
6287      * @param p1 P1 value of the APDU command.
6288      * @param p2 P2 value of the APDU command.
6289      * @param p3 P3 value of the APDU command.
6290      * @param filePath
6291      * @return The APDU response.
6292      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6293      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6294      *             {@link android.se.omapi.Reader#openSession()},
6295      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6296      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6297      */
6298     @Deprecated
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)6299     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
6300             String filePath) {
6301         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
6302     }
6303 
6304     /**
6305      * Returns the response APDU for a command APDU sent through SIM_IO.
6306      *
6307      * <p>Requires Permission:
6308      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6309      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6310      *
6311      * @param subId The subscription to use.
6312      * @param fileID
6313      * @param command
6314      * @param p1 P1 value of the APDU command.
6315      * @param p2 P2 value of the APDU command.
6316      * @param p3 P3 value of the APDU command.
6317      * @param filePath
6318      * @return The APDU response.
6319      * @hide
6320      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6321      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6322      *             {@link android.se.omapi.Reader#openSession()},
6323      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6324      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6325      */
6326     @Deprecated
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)6327     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
6328             int p3, String filePath) {
6329         try {
6330             ITelephony telephony = getITelephony();
6331             if (telephony != null)
6332                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
6333         } catch (RemoteException ex) {
6334         } catch (NullPointerException ex) {
6335         }
6336         return null;
6337     }
6338 
6339     /**
6340      * Send ENVELOPE to the SIM and return the response.
6341      *
6342      * <p>Requires Permission:
6343      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6344      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6345      *
6346      * @param content String containing SAT/USAT response in hexadecimal
6347      *                format starting with command tag. See TS 102 223 for
6348      *                details.
6349      * @return The APDU response from the ICC card in hexadecimal format
6350      *         with the last 4 bytes being the status word. If the command fails,
6351      *         returns an empty string.
6352      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6353      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6354      *             {@link android.se.omapi.Reader#openSession()},
6355      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6356      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6357      */
6358     @Deprecated
sendEnvelopeWithStatus(String content)6359     public String sendEnvelopeWithStatus(String content) {
6360         return sendEnvelopeWithStatus(getSubId(), content);
6361     }
6362 
6363     /**
6364      * Send ENVELOPE to the SIM and return the response.
6365      *
6366      * <p>Requires Permission:
6367      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6368      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6369      *
6370      * @param subId The subscription to use.
6371      * @param content String containing SAT/USAT response in hexadecimal
6372      *                format starting with command tag. See TS 102 223 for
6373      *                details.
6374      * @return The APDU response from the ICC card in hexadecimal format
6375      *         with the last 4 bytes being the status word. If the command fails,
6376      *         returns an empty string.
6377      * @hide
6378      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6379      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6380      *             {@link android.se.omapi.Reader#openSession()},
6381      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6382      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6383      */
6384     @Deprecated
sendEnvelopeWithStatus(int subId, String content)6385     public String sendEnvelopeWithStatus(int subId, String content) {
6386         try {
6387             ITelephony telephony = getITelephony();
6388             if (telephony != null)
6389                 return telephony.sendEnvelopeWithStatus(subId, content);
6390         } catch (RemoteException ex) {
6391         } catch (NullPointerException ex) {
6392         }
6393         return "";
6394     }
6395 
6396     /**
6397      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
6398      * Used for device configuration by some CDMA operators.
6399      *
6400      * <p>Requires Permission:
6401      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6402      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6403      *
6404      * @param itemID the ID of the item to read.
6405      * @return the NV item as a String, or null on any failure.
6406      *
6407      * @hide
6408      */
6409     @UnsupportedAppUsage
nvReadItem(int itemID)6410     public String nvReadItem(int itemID) {
6411         try {
6412             ITelephony telephony = getITelephony();
6413             if (telephony != null)
6414                 return telephony.nvReadItem(itemID);
6415         } catch (RemoteException ex) {
6416             Rlog.e(TAG, "nvReadItem RemoteException", ex);
6417         } catch (NullPointerException ex) {
6418             Rlog.e(TAG, "nvReadItem NPE", ex);
6419         }
6420         return "";
6421     }
6422 
6423     /**
6424      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
6425      * Used for device configuration by some CDMA operators.
6426      *
6427      * <p>Requires Permission:
6428      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6429      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6430      *
6431      * @param itemID the ID of the item to read.
6432      * @param itemValue the value to write, as a String.
6433      * @return true on success; false on any failure.
6434      *
6435      * @hide
6436      */
nvWriteItem(int itemID, String itemValue)6437     public boolean nvWriteItem(int itemID, String itemValue) {
6438         try {
6439             ITelephony telephony = getITelephony();
6440             if (telephony != null)
6441                 return telephony.nvWriteItem(itemID, itemValue);
6442         } catch (RemoteException ex) {
6443             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
6444         } catch (NullPointerException ex) {
6445             Rlog.e(TAG, "nvWriteItem NPE", ex);
6446         }
6447         return false;
6448     }
6449 
6450     /**
6451      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
6452      * Used for device configuration by some CDMA operators.
6453      *
6454      * <p>Requires Permission:
6455      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6456      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6457      *
6458      * @param preferredRoamingList byte array containing the new PRL.
6459      * @return true on success; false on any failure.
6460      *
6461      * @hide
6462      */
nvWriteCdmaPrl(byte[] preferredRoamingList)6463     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
6464         try {
6465             ITelephony telephony = getITelephony();
6466             if (telephony != null)
6467                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
6468         } catch (RemoteException ex) {
6469             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
6470         } catch (NullPointerException ex) {
6471             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
6472         }
6473         return false;
6474     }
6475 
6476     /**
6477      * Perform the specified type of NV config reset. The radio will be taken offline
6478      * and the device must be rebooted after the operation. Used for device
6479      * configuration by some CDMA operators.
6480      *
6481      * <p>Requires Permission:
6482      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6483      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6484      *
6485      * TODO: remove this one. use {@link #rebootRadio()} for reset type 1 and
6486      * {@link #resetRadioConfig()} for reset type 3
6487      *
6488      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
6489      * @return true on success; false on any failure.
6490      *
6491      * @hide
6492      */
6493     @UnsupportedAppUsage
nvResetConfig(int resetType)6494     public boolean nvResetConfig(int resetType) {
6495         try {
6496             ITelephony telephony = getITelephony();
6497             if (telephony != null) {
6498                 if (resetType == 1 /*1: reload NV reset */) {
6499                     return telephony.rebootModem(getSlotIndex());
6500                 } else if (resetType == 3 /*3: factory NV reset */) {
6501                     return telephony.resetModemConfig(getSlotIndex());
6502                 } else {
6503                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
6504                 }
6505             }
6506         } catch (RemoteException ex) {
6507             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
6508         } catch (NullPointerException ex) {
6509             Rlog.e(TAG, "nvResetConfig NPE", ex);
6510         }
6511         return false;
6512     }
6513 
6514     /**
6515      * Rollback modem configurations to factory default except some config which are in whitelist.
6516      * Used for device configuration by some carriers.
6517      *
6518      * <p>Requires Permission:
6519      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6520      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6521      *
6522      * @return {@code true} on success; {@code false} on any failure.
6523      *
6524      * @hide
6525      */
6526     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6527     @SystemApi
resetRadioConfig()6528     public boolean resetRadioConfig() {
6529         try {
6530             ITelephony telephony = getITelephony();
6531             if (telephony != null) {
6532                 return telephony.resetModemConfig(getSlotIndex());
6533             }
6534         } catch (RemoteException ex) {
6535             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
6536         } catch (NullPointerException ex) {
6537             Rlog.e(TAG, "resetRadioConfig NPE", ex);
6538         }
6539         return false;
6540     }
6541 
6542     /**
6543      * Generate a radio modem reset. Used for device configuration by some carriers.
6544      *
6545      * <p>Requires Permission:
6546      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6547      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6548      *
6549      * @return {@code true} on success; {@code false} on any failure.
6550      *
6551      * @hide
6552      */
6553     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6554     @SystemApi
rebootRadio()6555     public boolean rebootRadio() {
6556         try {
6557             ITelephony telephony = getITelephony();
6558             if (telephony != null) {
6559                 return telephony.rebootModem(getSlotIndex());
6560             }
6561         } catch (RemoteException ex) {
6562             Rlog.e(TAG, "rebootRadio RemoteException", ex);
6563         } catch (NullPointerException ex) {
6564             Rlog.e(TAG, "rebootRadio NPE", ex);
6565         }
6566         return false;
6567     }
6568 
6569     /**
6570      * Return an appropriate subscription ID for any situation.
6571      *
6572      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6573      * subId is returned. Otherwise, the default subId will be returned.
6574      */
getSubId()6575     private int getSubId() {
6576       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
6577         return mSubId;
6578       }
6579       return SubscriptionManager.getDefaultSubscriptionId();
6580     }
6581 
6582     /**
6583      * Return an appropriate subscription ID for any situation.
6584      *
6585      * If this object has been created with {@link #createForSubscriptionId}, then the provided
6586      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
6587      * returned.
6588      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
6589      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
6590      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
6591      */
6592     @UnsupportedAppUsage
getSubId(int preferredSubId)6593     private int getSubId(int preferredSubId) {
6594         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
6595             return mSubId;
6596         }
6597         return preferredSubId;
6598     }
6599 
6600     /**
6601      * Return an appropriate phone ID for any situation.
6602      *
6603      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
6604      * associated with the provided subId is returned. Otherwise, the default phoneId associated
6605      * with the default subId will be returned.
6606      */
getPhoneId()6607     private int getPhoneId() {
6608         return SubscriptionManager.getPhoneId(getSubId());
6609     }
6610 
6611     /**
6612      * Return an appropriate phone ID for any situation.
6613      *
6614      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
6615      * associated with the provided subId is returned. Otherwise, return the phoneId associated
6616      * with the preferred subId based on caller's context.
6617      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
6618      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
6619      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
6620      */
6621     @UnsupportedAppUsage
getPhoneId(int preferredSubId)6622     private int getPhoneId(int preferredSubId) {
6623         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
6624     }
6625 
6626     /**
6627      * Return an appropriate slot index for any situation.
6628      *
6629      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
6630      * associated with the provided subId is returned. Otherwise, return the slot index associated
6631      * with the default subId.
6632      * If SIM is not inserted, return default SIM slot index.
6633      *
6634      * {@hide}
6635      */
6636     @VisibleForTesting
6637     @UnsupportedAppUsage
getSlotIndex()6638     public int getSlotIndex() {
6639         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
6640         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
6641             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
6642         }
6643         return slotIndex;
6644     }
6645 
6646     /**
6647      * Request that the next incoming call from a number matching {@code range} be intercepted.
6648      *
6649      * This API is intended for OEMs to provide a service for apps to verify the device's phone
6650      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
6651      * intercept the next incoming call from a number that lies within the range, within a timeout
6652      * specified by {@code timeoutMillis}.
6653      *
6654      * If such a phone call is received, the caller will be notified via
6655      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
6656      * If verification fails for any reason, the caller will be notified via
6657      * {@link NumberVerificationCallback#onVerificationFailed(int)}
6658      * on the provided {@link Executor}.
6659      *
6660      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
6661      * API must also be listed in the device configuration as an authorized app in
6662      * {@code packages/services/Telephony/res/values/config.xml} under the
6663      * {@code config_number_verification_package_name} key.
6664      *
6665      * @hide
6666      * @param range The range of phone numbers the caller expects a phone call from.
6667      * @param timeoutMillis The amount of time to wait for such a call, or the value of
6668      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
6669      * @param executor The {@link Executor} that callbacks should be executed on.
6670      * @param callback The callback to use for delivering results.
6671      */
6672     @SystemApi
6673     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)6674     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
6675             @NonNull @CallbackExecutor Executor executor,
6676             @NonNull NumberVerificationCallback callback) {
6677         if (executor == null) {
6678             throw new NullPointerException("Executor must be non-null");
6679         }
6680         if (callback == null) {
6681             throw new NullPointerException("Callback must be non-null");
6682         }
6683 
6684         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
6685             @Override
6686             public void onCallReceived(String phoneNumber) {
6687                 final long identity = Binder.clearCallingIdentity();
6688                 try {
6689                     executor.execute(() ->
6690                             callback.onCallReceived(phoneNumber));
6691                 } finally {
6692                     Binder.restoreCallingIdentity(identity);
6693                 }
6694             }
6695 
6696             @Override
6697             public void onVerificationFailed(int reason) {
6698                 final long identity = Binder.clearCallingIdentity();
6699                 try {
6700                     executor.execute(() ->
6701                             callback.onVerificationFailed(reason));
6702                 } finally {
6703                     Binder.restoreCallingIdentity(identity);
6704                 }
6705             }
6706         };
6707 
6708         try {
6709             ITelephony telephony = getITelephony();
6710             if (telephony != null) {
6711                 telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
6712                         getOpPackageName());
6713             }
6714         } catch (RemoteException ex) {
6715             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
6716             executor.execute(() ->
6717                     callback.onVerificationFailed(NumberVerificationCallback.REASON_UNSPECIFIED));
6718         }
6719     }
6720 
6721     /**
6722      * Inserts or updates a list property. Expands the list if its length is not enough.
6723      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)6724     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
6725         List<T> ret = new ArrayList<>(prop);
6726         while (ret.size() <= phoneId) ret.add(null);
6727         ret.set(phoneId, value);
6728         return ret;
6729     }
6730     /**
6731      * Convenience function for retrieving a value from the secure settings
6732      * value list as an integer.  Note that internally setting values are
6733      * always stored as strings; this function converts the string to an
6734      * integer for you.
6735      * <p>
6736      * This version does not take a default value.  If the setting has not
6737      * been set, or the string value is not a number,
6738      * it throws {@link SettingNotFoundException}.
6739      *
6740      * @param cr The ContentResolver to access.
6741      * @param name The name of the setting to retrieve.
6742      * @param index The index of the list
6743      *
6744      * @throws SettingNotFoundException Thrown if a setting by the given
6745      * name can't be found or the setting value is not an integer.
6746      *
6747      * @return The value at the given index of settings.
6748      * @hide
6749      */
6750     @UnsupportedAppUsage
getIntAtIndex(android.content.ContentResolver cr, String name, int index)6751     public static int getIntAtIndex(android.content.ContentResolver cr,
6752             String name, int index)
6753             throws android.provider.Settings.SettingNotFoundException {
6754         String v = android.provider.Settings.Global.getString(cr, name);
6755         if (v != null) {
6756             String valArray[] = v.split(",");
6757             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
6758                 try {
6759                     return Integer.parseInt(valArray[index]);
6760                 } catch (NumberFormatException e) {
6761                     //Log.e(TAG, "Exception while parsing Integer: ", e);
6762                 }
6763             }
6764         }
6765         throw new android.provider.Settings.SettingNotFoundException(name);
6766     }
6767 
6768     /**
6769      * Convenience function for updating settings value as coma separated
6770      * integer values. This will either create a new entry in the table if the
6771      * given name does not exist, or modify the value of the existing row
6772      * with that name.  Note that internally setting values are always
6773      * stored as strings, so this function converts the given value to a
6774      * string before storing it.
6775      *
6776      * @param cr The ContentResolver to access.
6777      * @param name The name of the setting to modify.
6778      * @param index The index of the list
6779      * @param value The new value for the setting to be added to the list.
6780      * @return true if the value was set, false on database errors
6781      * @hide
6782      */
6783     @UnsupportedAppUsage
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)6784     public static boolean putIntAtIndex(android.content.ContentResolver cr,
6785             String name, int index, int value) {
6786         String data = "";
6787         String valArray[] = null;
6788         String v = android.provider.Settings.Global.getString(cr, name);
6789 
6790         if (index == Integer.MAX_VALUE) {
6791             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
6792         }
6793         if (index < 0) {
6794             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
6795         }
6796         if (v != null) {
6797             valArray = v.split(",");
6798         }
6799 
6800         // Copy the elements from valArray till index
6801         for (int i = 0; i < index; i++) {
6802             String str = "";
6803             if ((valArray != null) && (i < valArray.length)) {
6804                 str = valArray[i];
6805             }
6806             data = data + str + ",";
6807         }
6808 
6809         data = data + value;
6810 
6811         // Copy the remaining elements from valArray if any.
6812         if (valArray != null) {
6813             for (int i = index+1; i < valArray.length; i++) {
6814                 data = data + "," + valArray[i];
6815             }
6816         }
6817         return android.provider.Settings.Global.putString(cr, name, data);
6818     }
6819 
6820     /**
6821      * Gets a per-phone telephony property from a property name.
6822      *
6823      * @hide
6824      */
6825     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)6826     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
6827         String propVal = null;
6828         String prop = SystemProperties.get(property);
6829         if ((prop != null) && (prop.length() > 0)) {
6830             String values[] = prop.split(",");
6831             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
6832                 propVal = values[phoneId];
6833             }
6834         }
6835         return propVal == null ? defaultVal : propVal;
6836     }
6837 
6838     /**
6839      * Gets a typed per-phone telephony property from a schematized list property.
6840      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)6841     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
6842         T ret = null;
6843         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
6844         return ret != null ? ret : defaultValue;
6845     }
6846 
6847     /**
6848      * Gets a global telephony property.
6849      *
6850      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
6851      * per-phone.
6852      *
6853      * @hide
6854      */
6855     @UnsupportedAppUsage
getTelephonyProperty(String property, String defaultVal)6856     public static String getTelephonyProperty(String property, String defaultVal) {
6857         String propVal = SystemProperties.get(property);
6858         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
6859     }
6860 
6861     /** @hide */
6862     @UnsupportedAppUsage
getSimCount()6863     public int getSimCount() {
6864         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
6865         // and then this method shouldn't be used at all!
6866         return getPhoneCount();
6867     }
6868 
6869     /**
6870      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
6871      *
6872      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
6873      *
6874      * @return IMS Service Table or null if not present or not loaded
6875      * @hide
6876      */
6877     @Nullable
6878     @SystemApi
6879     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimIst()6880     public String getIsimIst() {
6881         try {
6882             IPhoneSubInfo info = getSubscriberInfo();
6883             if (info == null)
6884                 return null;
6885             //get the Isim Ist based on subId
6886             return info.getIsimIst(getSubId());
6887         } catch (RemoteException ex) {
6888             return null;
6889         } catch (NullPointerException ex) {
6890             // This could happen before phone restarts due to crashing
6891             return null;
6892         }
6893     }
6894 
6895     /**
6896      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
6897      * @return an array of PCSCF strings with one PCSCF per string, or null if
6898      *         not present or not loaded
6899      * @hide
6900      */
6901     @UnsupportedAppUsage
getIsimPcscf()6902     public String[] getIsimPcscf() {
6903         try {
6904             IPhoneSubInfo info = getSubscriberInfo();
6905             if (info == null)
6906                 return null;
6907             //get the Isim Pcscf based on subId
6908             return info.getIsimPcscf(getSubId());
6909         } catch (RemoteException ex) {
6910             return null;
6911         } catch (NullPointerException ex) {
6912             // This could happen before phone restarts due to crashing
6913             return null;
6914         }
6915     }
6916 
6917     /** UICC application type is SIM */
6918     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
6919     /** UICC application type is USIM */
6920     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
6921     /** UICC application type is RUIM */
6922     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
6923     /** UICC application type is CSIM */
6924     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
6925     /** UICC application type is ISIM */
6926     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
6927 
6928     // authContext (parameter P2) when doing UICC challenge,
6929     // per 3GPP TS 31.102 (Section 7.1.2)
6930     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
6931     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
6932     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
6933     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
6934 
6935     /**
6936      * Returns the response of authentication for the default subscription.
6937      * Returns null if the authentication hasn't been successful
6938      *
6939      * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE or that the calling
6940      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6941      *
6942      * @param appType the icc application type, like {@link #APPTYPE_USIM}
6943      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
6944      * {@link #AUTHTYPE_EAP_SIM}
6945      * @param data authentication challenge data, base64 encoded.
6946      * See 3GPP TS 31.102 7.1.2 for more details.
6947      * @return the response of authentication. This value will be null in the following cases:
6948      *   Authentication error, incorrect MAC
6949      *   Authentication error, security context not supported
6950      *   Key freshness failure
6951      *   Authentication error, no memory space available
6952      *   Authentication error, no memory space available in EFMUK
6953      */
6954     // TODO(b/73660190): This should probably require MODIFY_PHONE_STATE, not
6955     // READ_PRIVILEGED_PHONE_STATE. It certainly shouldn't reference the permission in Javadoc since
6956     // it's not public API.
getIccAuthentication(int appType, int authType, String data)6957     public String getIccAuthentication(int appType, int authType, String data) {
6958         return getIccAuthentication(getSubId(), appType, authType, data);
6959     }
6960 
6961     /**
6962      * Returns the response of USIM Authentication for specified subId.
6963      * Returns null if the authentication hasn't been successful
6964      *
6965      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6966      *
6967      * @param subId subscription ID used for authentication
6968      * @param appType the icc application type, like {@link #APPTYPE_USIM}
6969      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
6970      * {@link #AUTHTYPE_EAP_SIM}
6971      * @param data authentication challenge data, base64 encoded.
6972      * See 3GPP TS 31.102 7.1.2 for more details.
6973      * @return the response of authentication. This value will be null in the following cases only
6974      * (see 3GPP TS 31.102 7.3.1):
6975      *   Authentication error, incorrect MAC
6976      *   Authentication error, security context not supported
6977      *   Key freshness failure
6978      *   Authentication error, no memory space available
6979      *   Authentication error, no memory space available in EFMUK
6980      * @hide
6981      */
6982     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType, int authType, String data)6983     public String getIccAuthentication(int subId, int appType, int authType, String data) {
6984         try {
6985             IPhoneSubInfo info = getSubscriberInfo();
6986             if (info == null)
6987                 return null;
6988             return info.getIccSimChallengeResponse(subId, appType, authType, data);
6989         } catch (RemoteException ex) {
6990             return null;
6991         } catch (NullPointerException ex) {
6992             // This could happen before phone starts
6993             return null;
6994         }
6995     }
6996 
6997     /**
6998      * Returns an array of Forbidden PLMNs from the USIM App
6999      * Returns null if the query fails.
7000      *
7001      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
7002      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7003      *
7004      * @return an array of forbidden PLMNs or null if not available
7005      */
7006     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7007     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns()7008     public String[] getForbiddenPlmns() {
7009       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
7010     }
7011 
7012     /**
7013      * Returns an array of Forbidden PLMNs from the specified SIM App
7014      * Returns null if the query fails.
7015      *
7016      * @param subId subscription ID used for authentication
7017      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7018      * @return fplmns an array of forbidden PLMNs
7019      * @hide
7020      */
7021     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)7022     public String[] getForbiddenPlmns(int subId, int appType) {
7023         try {
7024             ITelephony telephony = getITelephony();
7025             if (telephony == null)
7026                 return null;
7027             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
7028                     getFeatureId());
7029         } catch (RemoteException ex) {
7030             return null;
7031         } catch (NullPointerException ex) {
7032             // This could happen before phone starts
7033             return null;
7034         }
7035     }
7036 
7037     /**
7038      * Replace the contents of the forbidden PLMN SIM file with the provided values.
7039      * Passing an empty list will clear the contents of the EFfplmn file.
7040      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
7041      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
7042      * If the list is longer than the size of EFfplmn, then the file will be written from the
7043      * beginning of the list up to the file size.
7044      *
7045      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
7046      * MODIFY_PHONE_STATE}
7047      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7048      *
7049      * @param fplmns a list of PLMNs to be forbidden.
7050      *
7051      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
7052      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
7053      * room for all of the values passed in. Return -1 in the event of an unexpected failure
7054      */
7055     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7056     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setForbiddenPlmns(@onNull List<String> fplmns)7057     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
7058         try {
7059             ITelephony telephony = getITelephony();
7060             if (telephony == null) return -1;
7061             return telephony.setForbiddenPlmns(
7062                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getFeatureId());
7063         } catch (RemoteException ex) {
7064             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
7065         } catch (NullPointerException ex) {
7066             // This could happen before phone starts
7067             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
7068         }
7069         return -1;
7070     }
7071 
7072     /**
7073      * Get P-CSCF address from PCO after data connection is established or modified.
7074      * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN
7075      * @return array of P-CSCF address
7076      * @hide
7077      */
getPcscfAddress(String apnType)7078     public String[] getPcscfAddress(String apnType) {
7079         try {
7080             ITelephony telephony = getITelephony();
7081             if (telephony == null)
7082                 return new String[0];
7083             return telephony.getPcscfAddress(apnType, getOpPackageName(), getFeatureId());
7084         } catch (RemoteException e) {
7085             return new String[0];
7086         }
7087     }
7088 
7089 
7090     /**
7091      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
7092      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
7093      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
7094      * state.
7095      *
7096      * @param slotIndex the sim slot to reset the IMS stack on.
7097      * @hide */
7098     @SystemApi
7099     @WorkerThread
7100     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetIms(int slotIndex)7101     public void resetIms(int slotIndex) {
7102         try {
7103             ITelephony telephony = getITelephony();
7104             if (telephony != null) {
7105                 telephony.resetIms(slotIndex);
7106             }
7107         } catch (RemoteException e) {
7108             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
7109                     + e.getMessage());
7110         }
7111     }
7112 
7113     /**
7114      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
7115      * status updates, if not already enabled.
7116      * @hide
7117      */
enableIms(int slotId)7118     public void enableIms(int slotId) {
7119         try {
7120             ITelephony telephony = getITelephony();
7121             if (telephony != null) {
7122                 telephony.enableIms(slotId);
7123             }
7124         } catch (RemoteException e) {
7125             Rlog.e(TAG, "enableIms, RemoteException: "
7126                     + e.getMessage());
7127         }
7128     }
7129 
7130     /**
7131      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
7132      * status updates to disabled.
7133      * @hide
7134      */
disableIms(int slotId)7135     public void disableIms(int slotId) {
7136         try {
7137             ITelephony telephony = getITelephony();
7138             if (telephony != null) {
7139                 telephony.disableIms(slotId);
7140             }
7141         } catch (RemoteException e) {
7142             Rlog.e(TAG, "disableIms, RemoteException: "
7143                     + e.getMessage());
7144         }
7145     }
7146 
7147     /**
7148      * Returns the {@link IImsMmTelFeature} that corresponds to the given slot Id and MMTel
7149      * feature or {@link null} if the service is not available. If an MMTelFeature is available, the
7150      * {@link IImsServiceFeatureCallback} callback is registered as a listener for feature updates.
7151      * @param slotIndex The SIM slot that we are requesting the {@link IImsMmTelFeature} for.
7152      * @param callback Listener that will send updates to ImsManager when there are updates to
7153      * ImsServiceController.
7154      * @return {@link IImsMmTelFeature} interface for the feature specified or {@code null} if
7155      * it is unavailable.
7156      * @hide
7157      */
getImsMmTelFeatureAndListen(int slotIndex, IImsServiceFeatureCallback callback)7158     public @Nullable IImsMmTelFeature getImsMmTelFeatureAndListen(int slotIndex,
7159             IImsServiceFeatureCallback callback) {
7160         try {
7161             ITelephony telephony = getITelephony();
7162             if (telephony != null) {
7163                 return telephony.getMmTelFeatureAndListen(slotIndex, callback);
7164             }
7165         } catch (RemoteException e) {
7166             Rlog.e(TAG, "getImsMmTelFeatureAndListen, RemoteException: "
7167                     + e.getMessage());
7168         }
7169         return null;
7170     }
7171 
7172     /**
7173      * Returns the {@link IImsRcsFeature} that corresponds to the given slot Id and RCS
7174      * feature for emergency calling or {@link null} if the service is not available. If an
7175      * RcsFeature is available, the {@link IImsServiceFeatureCallback} callback is registered as a
7176      * listener for feature updates.
7177      * @param slotIndex The SIM slot that we are requesting the {@link IImsRcsFeature} for.
7178      * @param callback Listener that will send updates to ImsManager when there are updates to
7179      * ImsServiceController.
7180      * @return {@link IImsRcsFeature} interface for the feature specified or {@code null} if
7181      * it is unavailable.
7182      * @hide
7183      */
getImsRcsFeatureAndListen(int slotIndex, IImsServiceFeatureCallback callback)7184     public @Nullable IImsRcsFeature getImsRcsFeatureAndListen(int slotIndex,
7185             IImsServiceFeatureCallback callback) {
7186         try {
7187             ITelephony telephony = getITelephony();
7188             if (telephony != null) {
7189                 return telephony.getRcsFeatureAndListen(slotIndex, callback);
7190             }
7191         } catch (RemoteException e) {
7192             Rlog.e(TAG, "getImsRcsFeatureAndListen, RemoteException: "
7193                     + e.getMessage());
7194         }
7195         return null;
7196     }
7197 
7198     /**
7199      * Unregister a IImsServiceFeatureCallback previously associated with an ImsFeature through
7200      * {@link #getImsMmTelFeatureAndListen(int, IImsServiceFeatureCallback)} or
7201      * {@link #getImsRcsFeatureAndListen(int, IImsServiceFeatureCallback)}.
7202      * @param slotIndex The SIM slot associated with the callback.
7203      * @param featureType The {@link android.telephony.ims.feature.ImsFeature.FeatureType}
7204      *                    associated with the callback.
7205      * @param callback The callback to be unregistered.
7206      * @hide
7207      */
unregisterImsFeatureCallback(int slotIndex, int featureType, IImsServiceFeatureCallback callback)7208     public void unregisterImsFeatureCallback(int slotIndex, int featureType,
7209             IImsServiceFeatureCallback callback) {
7210         try {
7211             ITelephony telephony = getITelephony();
7212             if (telephony != null) {
7213                 telephony.unregisterImsFeatureCallback(slotIndex, featureType, callback);
7214             }
7215         } catch (RemoteException e) {
7216             Rlog.e(TAG, "unregisterImsFeatureCallback, RemoteException: "
7217                     + e.getMessage());
7218         }
7219     }
7220 
7221     /**
7222      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
7223      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
7224      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
7225      * Corresponds to features defined in ImsFeature.
7226      * @hide
7227      */
7228     @UnsupportedAppUsage
getImsRegistration(int slotIndex, int feature)7229     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
7230         try {
7231             ITelephony telephony = getITelephony();
7232             if (telephony != null) {
7233                 return telephony.getImsRegistration(slotIndex, feature);
7234             }
7235         } catch (RemoteException e) {
7236             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7237         }
7238         return null;
7239     }
7240 
7241     /**
7242      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
7243      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
7244      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
7245      * Corresponds to features defined in ImsFeature.
7246      * @hide
7247      */
7248     @UnsupportedAppUsage
getImsConfig(int slotIndex, int feature)7249     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
7250         try {
7251             ITelephony telephony = getITelephony();
7252             if (telephony != null) {
7253                 return telephony.getImsConfig(slotIndex, feature);
7254             }
7255         } catch (RemoteException e) {
7256             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7257         }
7258         return null;
7259     }
7260 
7261     /**
7262      * Set IMS registration state
7263      *
7264      * @param Registration state
7265      * @hide
7266      */
7267     @UnsupportedAppUsage
setImsRegistrationState(boolean registered)7268     public void setImsRegistrationState(boolean registered) {
7269         try {
7270             ITelephony telephony = getITelephony();
7271             if (telephony != null)
7272                 telephony.setImsRegistrationState(registered);
7273         } catch (RemoteException e) {
7274         }
7275     }
7276 
7277     /** @hide */
7278     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
7279             NETWORK_MODE_WCDMA_PREF,
7280             NETWORK_MODE_GSM_ONLY,
7281             NETWORK_MODE_WCDMA_ONLY,
7282             NETWORK_MODE_GSM_UMTS,
7283             NETWORK_MODE_CDMA_EVDO,
7284             NETWORK_MODE_CDMA_NO_EVDO,
7285             NETWORK_MODE_EVDO_NO_CDMA,
7286             NETWORK_MODE_GLOBAL,
7287             NETWORK_MODE_LTE_CDMA_EVDO,
7288             NETWORK_MODE_LTE_GSM_WCDMA,
7289             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
7290             NETWORK_MODE_LTE_ONLY,
7291             NETWORK_MODE_LTE_WCDMA,
7292             NETWORK_MODE_TDSCDMA_ONLY,
7293             NETWORK_MODE_TDSCDMA_WCDMA,
7294             NETWORK_MODE_LTE_TDSCDMA,
7295             NETWORK_MODE_TDSCDMA_GSM,
7296             NETWORK_MODE_LTE_TDSCDMA_GSM,
7297             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
7298             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
7299             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
7300             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7301             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7302             NETWORK_MODE_NR_ONLY,
7303             NETWORK_MODE_NR_LTE,
7304             NETWORK_MODE_NR_LTE_CDMA_EVDO,
7305             NETWORK_MODE_NR_LTE_GSM_WCDMA,
7306             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
7307             NETWORK_MODE_NR_LTE_WCDMA,
7308             NETWORK_MODE_NR_LTE_TDSCDMA,
7309             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
7310             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
7311             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
7312             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
7313     })
7314     @Retention(RetentionPolicy.SOURCE)
7315     public @interface PrefNetworkMode{}
7316 
7317     /**
7318      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
7319      * @hide
7320      */
7321     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
7322 
7323     /**
7324      * Preferred network mode is GSM only.
7325      * @hide
7326      */
7327     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
7328 
7329     /**
7330      * Preferred network mode is WCDMA only.
7331      * @hide
7332      */
7333     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
7334 
7335     /**
7336      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
7337      * @hide
7338      */
7339     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
7340 
7341     /**
7342      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
7343      * @hide
7344      */
7345     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
7346 
7347     /**
7348      * Preferred network mode is CDMA only.
7349      * @hide
7350      */
7351     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
7352 
7353     /**
7354      * Preferred network mode is EvDo only.
7355      * @hide
7356      */
7357     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
7358 
7359     /**
7360      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
7361      * @hide
7362      */
7363     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
7364 
7365     /**
7366      * Preferred network mode is LTE, CDMA and EvDo.
7367      * @hide
7368      */
7369     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
7370 
7371     /**
7372      * Preferred network mode is LTE, GSM/WCDMA.
7373      * @hide
7374      */
7375     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
7376 
7377     /**
7378      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
7379      * @hide
7380      */
7381     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
7382             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
7383 
7384     /**
7385      * Preferred network mode is LTE Only.
7386      * @hide
7387      */
7388     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
7389 
7390     /**
7391      * Preferred network mode is LTE/WCDMA.
7392      * @hide
7393      */
7394     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
7395 
7396     /**
7397      * Preferred network mode is TD-SCDMA only.
7398      * @hide
7399      */
7400     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
7401 
7402     /**
7403      * Preferred network mode is TD-SCDMA and WCDMA.
7404      * @hide
7405      */
7406     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
7407 
7408     /**
7409      * Preferred network mode is TD-SCDMA and LTE.
7410      * @hide
7411      */
7412     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
7413 
7414     /**
7415      * Preferred network mode is TD-SCDMA and GSM.
7416      * @hide
7417      */
7418     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
7419 
7420     /**
7421      * Preferred network mode is TD-SCDMA,GSM and LTE.
7422      * @hide
7423      */
7424     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
7425             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
7426 
7427     /**
7428      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
7429      * @hide
7430      */
7431     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
7432             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
7433 
7434     /**
7435      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
7436      * @hide
7437      */
7438     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
7439             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
7440 
7441     /**
7442      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
7443      * @hide
7444      */
7445     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
7446             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
7447 
7448     /**
7449      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
7450      * @hide
7451      */
7452     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7453             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7454     /**
7455      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
7456      * @hide
7457      */
7458     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7459             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7460 
7461     /**
7462      * Preferred network mode is NR 5G only.
7463      * @hide
7464      */
7465     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
7466 
7467     /**
7468      * Preferred network mode is NR 5G, LTE.
7469      * @hide
7470      */
7471     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
7472 
7473     /**
7474      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
7475      * @hide
7476      */
7477     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
7478             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
7479 
7480     /**
7481      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
7482      * @hide
7483      */
7484     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
7485             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
7486 
7487     /**
7488      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
7489      * @hide
7490      */
7491     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
7492             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
7493 
7494     /**
7495      * Preferred network mode is NR 5G, LTE and WCDMA.
7496      * @hide
7497      */
7498     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
7499 
7500     /**
7501      * Preferred network mode is NR 5G, LTE and TDSCDMA.
7502      * @hide
7503      */
7504     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
7505 
7506     /**
7507      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
7508      * @hide
7509      */
7510     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
7511             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
7512 
7513     /**
7514      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
7515      * @hide
7516      */
7517     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
7518             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
7519 
7520     /**
7521      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
7522      * @hide
7523      */
7524     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
7525             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
7526 
7527     /**
7528      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
7529      * @hide
7530      */
7531     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
7532             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
7533 
7534     /**
7535      * The default preferred network mode constant.
7536      *
7537      * <p> This constant is used in case of nothing is set in
7538      * TelephonyProperties#default_network().
7539      *
7540      * @hide
7541      */
7542     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
7543             RILConstants.PREFERRED_NETWORK_MODE;
7544 
7545     /**
7546      * Get the preferred network type.
7547      * Used for device configuration by some CDMA operators.
7548      *
7549      * <p>Requires Permission:
7550      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7551      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7552      *
7553      * @return the preferred network type.
7554      * @hide
7555      * @deprecated Use {@link #getPreferredNetworkTypeBitmask} instead.
7556      */
7557     @Deprecated
7558     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
7559     @UnsupportedAppUsage
getPreferredNetworkType(int subId)7560     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
7561         try {
7562             ITelephony telephony = getITelephony();
7563             if (telephony != null) {
7564                 return telephony.getPreferredNetworkType(subId);
7565             }
7566         } catch (RemoteException ex) {
7567             Rlog.e(TAG, "getPreferredNetworkType RemoteException", ex);
7568         }
7569         return -1;
7570     }
7571 
7572     /**
7573      * Get the preferred network type bitmask.
7574      *
7575      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7576      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7577      *
7578      * <p>Requires Permission:
7579      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7580      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7581      *
7582      * @return The bitmask of preferred network types.
7583      *
7584      * @hide
7585      */
7586     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
7587     @SystemApi
getPreferredNetworkTypeBitmask()7588     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
7589         try {
7590             ITelephony telephony = getITelephony();
7591             if (telephony != null) {
7592                 return (long) RadioAccessFamily.getRafFromNetworkType(
7593                         telephony.getPreferredNetworkType(getSubId()));
7594             }
7595         } catch (RemoteException ex) {
7596             Rlog.e(TAG, "getPreferredNetworkTypeBitmask RemoteException", ex);
7597         }
7598         return 0;
7599     }
7600 
7601     /**
7602      * Get the allowed network types.
7603      *
7604      * <p>Requires Permission:
7605      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
7606      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7607      *
7608      * @return the allowed network type bitmask
7609      * @hide
7610      */
7611     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
7612     @SystemApi
getAllowedNetworkTypes()7613     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
7614         try {
7615             ITelephony telephony = getITelephony();
7616             if (telephony != null) {
7617                 return telephony.getAllowedNetworkTypes(getSubId());
7618             }
7619         } catch (RemoteException ex) {
7620             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
7621         }
7622         return -1;
7623     }
7624 
7625     /**
7626      * Sets the network selection mode to automatic.
7627      *
7628      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7629      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7630      *
7631      * <p>Requires Permission:
7632      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7633      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7634      */
7635     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7636     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeAutomatic()7637     public void setNetworkSelectionModeAutomatic() {
7638         try {
7639             ITelephony telephony = getITelephony();
7640             if (telephony != null) {
7641                 telephony.setNetworkSelectionModeAutomatic(getSubId());
7642             }
7643         } catch (RemoteException ex) {
7644             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
7645         } catch (NullPointerException ex) {
7646             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
7647         }
7648     }
7649 
7650     /**
7651      * Perform a radio scan and return the list of available networks.
7652      *
7653      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7654      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7655      *
7656      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
7657      *
7658      * <p>Requires Permissions:
7659      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
7660      * privileges (see {@link #hasCarrierPrivileges})
7661      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
7662      *
7663      * @return {@link CellNetworkScanResult} with the status
7664      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
7665      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
7666      * caused will be included in the result.
7667      *
7668      * @hide
7669      */
7670     @RequiresPermission(allOf = {
7671             android.Manifest.permission.MODIFY_PHONE_STATE,
7672             Manifest.permission.ACCESS_COARSE_LOCATION
7673     })
getAvailableNetworks()7674     public CellNetworkScanResult getAvailableNetworks() {
7675         try {
7676             ITelephony telephony = getITelephony();
7677             if (telephony != null) {
7678                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
7679                         getFeatureId());
7680             }
7681         } catch (RemoteException ex) {
7682             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
7683         } catch (NullPointerException ex) {
7684             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
7685         }
7686         return new CellNetworkScanResult(
7687                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
7688     }
7689 
7690     /**
7691      * Request a network scan.
7692      *
7693      * This method is asynchronous, so the network scan results will be returned by callback.
7694      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
7695      *
7696      * <p>Requires Permission:
7697      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7698      * app has carrier privileges (see {@link #hasCarrierPrivileges})
7699      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
7700      *
7701      * If the system-wide location switch is off, apps may still call this API, with the
7702      * following constraints:
7703      * <ol>
7704      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
7705      *     <li>The app must not supply any specific bands or channels to scan.</li>
7706      *     <li>The app must only specify MCC/MNC pairs that are
7707      *     associated to a SIM in the device.</li>
7708      *     <li>Returned results will have no meaningful info other than signal strength
7709      *     and MCC/MNC info.</li>
7710      * </ol>
7711      *
7712      * @param request Contains all the RAT with bands/channels that need to be scanned.
7713      * @param executor The executor through which the callback should be invoked. Since the scan
7714      *        request may trigger multiple callbacks and they must be invoked in the same order as
7715      *        they are received by the platform, the user should provide an executor which executes
7716      *        tasks one at a time in serial order. For example AsyncTask.SERIAL_EXECUTOR.
7717      * @param callback Returns network scan results or errors.
7718      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
7719      */
7720     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7721     @RequiresPermission(allOf = {
7722             android.Manifest.permission.MODIFY_PHONE_STATE,
7723             Manifest.permission.ACCESS_FINE_LOCATION
7724     })
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)7725     public NetworkScan requestNetworkScan(
7726             NetworkScanRequest request, Executor executor,
7727             TelephonyScanManager.NetworkScanCallback callback) {
7728         synchronized (this) {
7729             if (mTelephonyScanManager == null) {
7730                 mTelephonyScanManager = new TelephonyScanManager();
7731             }
7732         }
7733         return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback,
7734                 getOpPackageName(), getFeatureId());
7735     }
7736 
7737     /**
7738      * @deprecated
7739      * Use {@link
7740      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
7741      * @removed
7742      */
7743     @Deprecated
7744     @RequiresPermission(allOf = {
7745             android.Manifest.permission.MODIFY_PHONE_STATE,
7746             Manifest.permission.ACCESS_FINE_LOCATION
7747     })
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)7748     public NetworkScan requestNetworkScan(
7749         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
7750         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
7751     }
7752 
7753     /**
7754      * Ask the radio to connect to the input network and change selection mode to manual.
7755      *
7756      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7757      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7758      *
7759      * <p>Requires Permission:
7760      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7761      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7762      *
7763      * @param operatorNumeric the PLMN ID of the network to select.
7764      * @param persistSelection whether the selection will persist until reboot. If true, only allows
7765      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
7766      * normal network selection next time.
7767      * @return {@code true} on success; {@code false} on any failure.
7768      */
7769     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7770     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)7771     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
7772         return setNetworkSelectionModeManual(
7773                 new OperatorInfo(
7774                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
7775                 persistSelection);
7776     }
7777 
7778     /**
7779      * Ask the radio to connect to the input network and change selection mode to manual.
7780      *
7781      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7782      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7783      *
7784      * <p>Requires Permission:
7785      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7786      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7787      *
7788      * @param operatorNumeric the PLMN ID of the network to select.
7789      * @param persistSelection whether the selection will persist until reboot.
7790      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
7791      *         attach to the chosen PLMN and resume normal network selection next time.
7792      * @param ran the initial suggested radio access network type.
7793      *         If registration fails, the RAN is not available after, the RAN is not within the
7794      *         network types specified by the preferred network types, or the value is
7795      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
7796      *         the next best RAN for network registration.
7797      * @return {@code true} on success; {@code false} on any failure.
7798      */
7799     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)7800     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
7801             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
7802         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
7803                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
7804     }
7805 
7806     /**
7807      * Ask the radio to connect to the input network and change selection mode to manual.
7808      *
7809      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7810      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7811      *
7812      * <p>Requires Permission:
7813      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7814      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7815      *
7816      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
7817      * @param persistSelection whether the selection will persist until reboot. If true, only allows
7818      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
7819      * normal network selection next time.
7820      * @return {@code true} on success; {@code true} on any failure.
7821      *
7822      * @hide
7823      */
7824     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)7825     public boolean setNetworkSelectionModeManual(
7826             OperatorInfo operatorInfo, boolean persistSelection) {
7827         try {
7828             ITelephony telephony = getITelephony();
7829             if (telephony != null) {
7830                 return telephony.setNetworkSelectionModeManual(
7831                         getSubId(), operatorInfo, persistSelection);
7832             }
7833         } catch (RemoteException ex) {
7834             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
7835         }
7836         return false;
7837     }
7838 
7839    /**
7840      * Get the network selection mode.
7841      *
7842      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7843      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7844      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
7845      * READ_PRECISE_PHONE_STATE}
7846      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7847      *
7848      * @return the network selection mode.
7849      */
7850     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
7851     @RequiresPermission(anyOf = {
7852             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
7853             android.Manifest.permission.READ_PRECISE_PHONE_STATE
7854     })
getNetworkSelectionMode()7855     public @NetworkSelectionMode int getNetworkSelectionMode() {
7856         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
7857         try {
7858             ITelephony telephony = getITelephony();
7859             if (telephony != null) {
7860                 mode = telephony.getNetworkSelectionMode(getSubId());
7861             }
7862         } catch (RemoteException ex) {
7863             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
7864         }
7865         return mode;
7866     }
7867 
7868     /**
7869      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
7870      * user and we are still within the time interval after the emergency SMS was sent that we are
7871      * considered in Emergency SMS mode.
7872      *
7873      * <p>This mode is used by other applications to allow them to perform special functionality,
7874      * such as allow the GNSS service to provide user location to the carrier network for emergency
7875      * when an emergency SMS is sent. This interval is set by
7876      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
7877      * the carrier does not support this mode, this function will always return false.
7878      *
7879      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
7880      *
7881      * @hide
7882      */
7883     @SystemApi
7884     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isInEmergencySmsMode()7885     public boolean isInEmergencySmsMode() {
7886         try {
7887             ITelephony telephony = getITelephony();
7888             if (telephony != null) {
7889                 return telephony.isInEmergencySmsMode();
7890             }
7891         } catch (RemoteException ex) {
7892             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
7893         }
7894         return false;
7895     }
7896 
7897     /**
7898      * Set the preferred network type.
7899      *
7900      * <p>Requires Permission:
7901      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7902      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7903      *
7904      * @param subId the id of the subscription to set the preferred network type for.
7905      * @param networkType the preferred network type
7906      * @return true on success; false on any failure.
7907      * @hide
7908      * @deprecated Use {@link #setPreferredNetworkTypeBitmask} instead.
7909      */
7910     @Deprecated
7911     @UnsupportedAppUsage
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)7912     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
7913         try {
7914             ITelephony telephony = getITelephony();
7915             if (telephony != null) {
7916                 return telephony.setPreferredNetworkType(subId, networkType);
7917             }
7918         } catch (RemoteException ex) {
7919             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
7920         }
7921         return false;
7922     }
7923 
7924     /**
7925      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
7926      * only the allowed network type will set to the modem.
7927      *
7928      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
7929      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
7930      *
7931      * <p>Requires Permission:
7932      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7933      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7934      *
7935      * @param networkTypeBitmask The bitmask of preferred network types.
7936      * @return true on success; false on any failure.
7937      * @hide
7938      */
7939     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
7940     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)7941     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
7942         try {
7943             ITelephony telephony = getITelephony();
7944             if (telephony != null) {
7945                 return telephony.setPreferredNetworkType(
7946                         getSubId(), RadioAccessFamily.getNetworkTypeFromRaf(
7947                                 (int) networkTypeBitmask));
7948             }
7949         } catch (RemoteException ex) {
7950             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
7951         }
7952         return false;
7953     }
7954 
7955     /**
7956      * Set the allowed network types of the device. This is for carrier or privileged apps to
7957      * enable/disable certain network types on the device. The user preferred network types should
7958      * be set through {@link #setPreferredNetworkTypeBitmask}.
7959      *
7960      * @param allowedNetworkTypes The bitmask of allowed network types.
7961      * @return true on success; false on any failure.
7962      * @hide
7963      */
7964     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
7965     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)7966     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
7967         try {
7968             ITelephony telephony = getITelephony();
7969             if (telephony != null) {
7970                 return telephony.setAllowedNetworkTypes(getSubId(), allowedNetworkTypes);
7971             }
7972         } catch (RemoteException ex) {
7973             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
7974         }
7975         return false;
7976     }
7977 
7978     /** @hide */
7979     @IntDef({
7980             ALLOWED_NETWORK_TYPES_REASON_POWER
7981     })
7982     @Retention(RetentionPolicy.SOURCE)
7983     public @interface AllowedNetworkTypesReason{}
7984 
7985     /**
7986      * To indicate allowed network type change is requested by power manager.
7987      * Power Manger configuration won't affect the settings configured through
7988      * {@link setAllowedNetworkTypes} and will result in allowing network types that are in both
7989      * configurations (i.e intersection of both sets).
7990      * @hide
7991      */
7992     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 0;
7993 
7994     /**
7995      * Set the allowed network types of the device and
7996      * provide the reason triggering the allowed network change.
7997      * This can be called for following reasons
7998      * <ol>
7999      * <li>Allowed network types control by power manager
8000      * {@link #ALLOWED_NETWORK_TYPES_REASON_POWER}
8001      * </ol>
8002      * This API will result in allowing an intersection of allowed network types for all reasons,
8003      * including the configuration done through {@link setAllowedNetworkTypes}.
8004      * While this API and {@link setAllowedNetworkTypes} is controlling allowed network types
8005      * on device, user preference will still be set through {@link #setPreferredNetworkTypeBitmask}.
8006      * Thus resultant network type configured on modem will be an intersection of the network types
8007      * from setAllowedNetworkTypesForReason, {@link setAllowedNetworkTypes}
8008      * and {@link #setPreferredNetworkTypeBitmask}.
8009      *
8010      * @param reason the reason the allowed network type change is taking place
8011      * @param allowedNetworkTypes The bitmask of allowed network types.
8012      * @throws IllegalStateException if the Telephony process is not currently available.
8013      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8014      * @hide
8015      */
8016     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)8017     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
8018             @NetworkTypeBitMask long allowedNetworkTypes) {
8019         if (reason != ALLOWED_NETWORK_TYPES_REASON_POWER) {
8020             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8021         }
8022         try {
8023             ITelephony telephony = getITelephony();
8024             if (telephony != null) {
8025                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
8026                         allowedNetworkTypes);
8027             } else {
8028                 throw new IllegalStateException("telephony service is null.");
8029             }
8030         } catch (RemoteException ex) {
8031             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
8032             ex.rethrowFromSystemServer();
8033         }
8034     }
8035 
8036     /**
8037      * Get the allowed network types for certain reason.
8038      *
8039      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
8040      * specific reason. For effective allowed network types configured on device,
8041      * query {@link getEffectiveAllowedNetworkTypes}
8042      *
8043      * <p>Requires Permission:
8044      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8045      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8046      *s
8047      * @param reason the reason the allowed network type change is taking place
8048      * @return the allowed network type bitmask
8049      * @throws IllegalStateException if the Telephony process is not currently available.
8050      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8051      * @hide
8052      */
8053     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)8054     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
8055             @AllowedNetworkTypesReason int reason) {
8056         if (reason != ALLOWED_NETWORK_TYPES_REASON_POWER) {
8057             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8058         }
8059         try {
8060             ITelephony telephony = getITelephony();
8061             if (telephony != null) {
8062                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
8063             } else {
8064                 throw new IllegalStateException("telephony service is null.");
8065             }
8066         } catch (RemoteException ex) {
8067             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
8068             ex.rethrowFromSystemServer();
8069         }
8070         return -1;
8071     }
8072 
8073     /**
8074      * Get bit mask of all network types.
8075      *
8076      * @return bit mask of all network types
8077      * @hide
8078      */
getAllNetworkTypesBitmask()8079     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
8080         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
8081     }
8082 
8083     /**
8084      * Get the allowed network types configured on the device.
8085      * This API will return an intersection of allowed network types for all reasons,
8086      * including the configuration done through setAllowedNetworkTypes
8087      *
8088      * <p>Requires Permission:
8089      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8090      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8091      *
8092      * @return the allowed network type bitmask
8093      * @throws IllegalStateException if the Telephony process is not currently available.
8094      * @hide
8095      */
8096     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEffectiveAllowedNetworkTypes()8097     public @NetworkTypeBitMask long getEffectiveAllowedNetworkTypes() {
8098         try {
8099             ITelephony telephony = getITelephony();
8100             if (telephony != null) {
8101                 return telephony.getEffectiveAllowedNetworkTypes(getSubId());
8102             } else {
8103                 throw new IllegalStateException("telephony service is null.");
8104             }
8105         } catch (RemoteException ex) {
8106             Rlog.e(TAG, "getEffectiveAllowedNetworkTypes RemoteException", ex);
8107             ex.rethrowFromSystemServer();
8108         }
8109         return -1;
8110     }
8111 
8112     /**
8113      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8114      *
8115      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8116      *
8117      * @return true on success; false on any failure.
8118      */
setPreferredNetworkTypeToGlobal()8119     public boolean setPreferredNetworkTypeToGlobal() {
8120         return setPreferredNetworkTypeToGlobal(getSubId());
8121     }
8122 
8123     /**
8124      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8125      *
8126      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8127      *
8128      * @return true on success; false on any failure.
8129      * @hide
8130      */
setPreferredNetworkTypeToGlobal(int subId)8131     public boolean setPreferredNetworkTypeToGlobal(int subId) {
8132         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
8133     }
8134 
8135     /**
8136      * Check whether DUN APN is required for tethering.
8137      * <p>
8138      * Requires Permission: MODIFY_PHONE_STATE.
8139      *
8140      * @return {@code true} if DUN APN is required for tethering.
8141      * @hide
8142      */
8143     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8144     @SystemApi
isTetheringApnRequired()8145     public boolean isTetheringApnRequired() {
8146         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
8147     }
8148 
8149     /**
8150      * Check whether DUN APN is required for tethering with subId.
8151      *
8152      * @param subId the id of the subscription to require tethering.
8153      * @return {@code true} if DUN APN is required for tethering.
8154      * @hide
8155      */
isTetheringApnRequired(int subId)8156     public boolean isTetheringApnRequired(int subId) {
8157         try {
8158             ITelephony telephony = getITelephony();
8159             if (telephony != null)
8160                 return telephony.isTetheringApnRequiredForSubscriber(subId);
8161         } catch (RemoteException ex) {
8162             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
8163         } catch (NullPointerException ex) {
8164             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
8165         }
8166         return false;
8167     }
8168 
8169 
8170     /**
8171      * Values used to return status for hasCarrierPrivileges call.
8172      */
8173     /** @hide */ @SystemApi @TestApi
8174     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
8175     /** @hide */ @SystemApi @TestApi
8176     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
8177     /** @hide */ @SystemApi @TestApi
8178     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
8179     /** @hide */ @SystemApi @TestApi
8180     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
8181 
8182     /**
8183      * Has the calling application been granted carrier privileges by the carrier.
8184      *
8185      * If any of the packages in the calling UID has carrier privileges, the
8186      * call will return true. This access is granted by the owner of the UICC
8187      * card and does not depend on the registered carrier.
8188      *
8189      * @return true if the app has carrier privileges.
8190      */
hasCarrierPrivileges()8191     public boolean hasCarrierPrivileges() {
8192         return hasCarrierPrivileges(getSubId());
8193     }
8194 
8195     /**
8196      * Has the calling application been granted carrier privileges by the carrier.
8197      *
8198      * If any of the packages in the calling UID has carrier privileges, the
8199      * call will return true. This access is granted by the owner of the UICC
8200      * card and does not depend on the registered carrier.
8201      *
8202      * @param subId The subscription to use.
8203      * @return true if the app has carrier privileges.
8204      * @hide
8205      */
hasCarrierPrivileges(int subId)8206     public boolean hasCarrierPrivileges(int subId) {
8207         try {
8208             ITelephony telephony = getITelephony();
8209             if (telephony != null) {
8210                 return telephony.getCarrierPrivilegeStatus(subId)
8211                         == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
8212             }
8213         } catch (RemoteException ex) {
8214             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
8215         } catch (NullPointerException ex) {
8216             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
8217         }
8218         return false;
8219     }
8220 
8221     /**
8222      * Override the branding for the current ICCID.
8223      *
8224      * Once set, whenever the SIM is present in the device, the service
8225      * provider name (SPN) and the operator name will both be replaced by the
8226      * brand value input. To unset the value, the same function should be
8227      * called with a null brand value.
8228      *
8229      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8230      *
8231      * @param brand The brand name to display/set.
8232      * @return true if the operation was executed correctly.
8233      */
setOperatorBrandOverride(String brand)8234     public boolean setOperatorBrandOverride(String brand) {
8235         return setOperatorBrandOverride(getSubId(), brand);
8236     }
8237 
8238     /**
8239      * Override the branding for the current ICCID.
8240      *
8241      * Once set, whenever the SIM is present in the device, the service
8242      * provider name (SPN) and the operator name will both be replaced by the
8243      * brand value input. To unset the value, the same function should be
8244      * called with a null brand value.
8245      *
8246      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8247      *
8248      * @param subId The subscription to use.
8249      * @param brand The brand name to display/set.
8250      * @return true if the operation was executed correctly.
8251      * @hide
8252      */
setOperatorBrandOverride(int subId, String brand)8253     public boolean setOperatorBrandOverride(int subId, String brand) {
8254         try {
8255             ITelephony telephony = getITelephony();
8256             if (telephony != null)
8257                 return telephony.setOperatorBrandOverride(subId, brand);
8258         } catch (RemoteException ex) {
8259             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
8260         } catch (NullPointerException ex) {
8261             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
8262         }
8263         return false;
8264     }
8265 
8266     /**
8267      * Override the roaming preference for the current ICCID.
8268      *
8269      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
8270      * the platform's notion of a network operator being considered roaming or not.
8271      * The change only affects the ICCID that was active when this call was made.
8272      *
8273      * If null is passed as any of the input, the corresponding value is deleted.
8274      *
8275      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
8276      *
8277      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
8278      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
8279      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
8280      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
8281      * @return true if the operation was executed correctly.
8282      *
8283      * @hide
8284      */
8285     @UnsupportedAppUsage
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)8286     public boolean setRoamingOverride(List<String> gsmRoamingList,
8287             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
8288             List<String> cdmaNonRoamingList) {
8289         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
8290                 cdmaRoamingList, cdmaNonRoamingList);
8291     }
8292 
8293     /**
8294      * Override the roaming preference for the current ICCID.
8295      *
8296      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
8297      * the platform's notion of a network operator being considered roaming or not.
8298      * The change only affects the ICCID that was active when this call was made.
8299      *
8300      * If null is passed as any of the input, the corresponding value is deleted.
8301      *
8302      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
8303      *
8304      * @param subId for which the roaming overrides apply.
8305      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
8306      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
8307      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
8308      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
8309      * @return true if the operation was executed correctly.
8310      *
8311      * @hide
8312      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)8313     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
8314             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
8315             List<String> cdmaNonRoamingList) {
8316         try {
8317             ITelephony telephony = getITelephony();
8318             if (telephony != null)
8319                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
8320                         cdmaRoamingList, cdmaNonRoamingList);
8321         } catch (RemoteException ex) {
8322             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
8323         } catch (NullPointerException ex) {
8324             Rlog.e(TAG, "setRoamingOverride NPE", ex);
8325         }
8326         return false;
8327     }
8328 
8329     /**
8330      * Expose the rest of ITelephony to @SystemApi
8331      */
8332 
8333     /** @hide */
8334     @SystemApi
8335     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn()8336     public String getCdmaMdn() {
8337         return getCdmaMdn(getSubId());
8338     }
8339 
8340     /** @hide */
8341     @SystemApi
8342     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn(int subId)8343     public String getCdmaMdn(int subId) {
8344         try {
8345             ITelephony telephony = getITelephony();
8346             if (telephony == null)
8347                 return null;
8348             return telephony.getCdmaMdn(subId);
8349         } catch (RemoteException ex) {
8350             return null;
8351         } catch (NullPointerException ex) {
8352             return null;
8353         }
8354     }
8355 
8356     /** @hide */
8357     @SystemApi
8358     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin()8359     public String getCdmaMin() {
8360         return getCdmaMin(getSubId());
8361     }
8362 
8363     /** @hide */
8364     @SystemApi
8365     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin(int subId)8366     public String getCdmaMin(int subId) {
8367         try {
8368             ITelephony telephony = getITelephony();
8369             if (telephony == null)
8370                 return null;
8371             return telephony.getCdmaMin(subId);
8372         } catch (RemoteException ex) {
8373             return null;
8374         } catch (NullPointerException ex) {
8375             return null;
8376         }
8377     }
8378 
8379     /** @hide */
8380     @SystemApi
8381     @TestApi
8382     @SuppressLint("Doclava125")
checkCarrierPrivilegesForPackage(String pkgName)8383     public int checkCarrierPrivilegesForPackage(String pkgName) {
8384         try {
8385             ITelephony telephony = getITelephony();
8386             if (telephony != null)
8387                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
8388         } catch (RemoteException ex) {
8389             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
8390         } catch (NullPointerException ex) {
8391             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
8392         }
8393         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
8394     }
8395 
8396     /** @hide */
8397     @SystemApi
8398     @SuppressLint("Doclava125")
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)8399     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
8400         try {
8401             ITelephony telephony = getITelephony();
8402             if (telephony != null)
8403                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
8404         } catch (RemoteException ex) {
8405             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
8406         } catch (NullPointerException ex) {
8407             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
8408         }
8409         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
8410     }
8411 
8412     /** @hide */
8413     @SystemApi
8414     @TestApi
getCarrierPackageNamesForIntent(Intent intent)8415     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
8416         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
8417     }
8418 
8419     /** @hide */
8420     @SystemApi
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)8421     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
8422         try {
8423             ITelephony telephony = getITelephony();
8424             if (telephony != null)
8425                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
8426         } catch (RemoteException ex) {
8427             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
8428         } catch (NullPointerException ex) {
8429             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
8430         }
8431         return null;
8432     }
8433 
8434     /** @hide */
getPackagesWithCarrierPrivileges()8435     public List<String> getPackagesWithCarrierPrivileges() {
8436         try {
8437             ITelephony telephony = getITelephony();
8438             if (telephony != null) {
8439                 return telephony.getPackagesWithCarrierPrivileges(getPhoneId());
8440             }
8441         } catch (RemoteException ex) {
8442             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
8443         } catch (NullPointerException ex) {
8444             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
8445         }
8446         return Collections.EMPTY_LIST;
8447     }
8448 
8449     /**
8450      * Get the names of packages with carrier privileges for all the active subscriptions.
8451      *
8452      * @hide
8453      */
8454     @SystemApi
8455     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8456     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()8457     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
8458         try {
8459             ITelephony telephony = getITelephony();
8460             if (telephony != null) {
8461                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
8462             }
8463         } catch (RemoteException ex) {
8464             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
8465                     ex);
8466         } catch (NullPointerException ex) {
8467             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
8468         }
8469         return Collections.EMPTY_LIST;
8470     }
8471 
8472 
8473     /** @hide */
8474     @SystemApi
8475     @SuppressLint("Doclava125")
dial(String number)8476     public void dial(String number) {
8477         try {
8478             ITelephony telephony = getITelephony();
8479             if (telephony != null)
8480                 telephony.dial(number);
8481         } catch (RemoteException e) {
8482             Log.e(TAG, "Error calling ITelephony#dial", e);
8483         }
8484     }
8485 
8486     /**
8487      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
8488      * Bundle extras)} instead.
8489      * @hide
8490      */
8491     @Deprecated
8492     @SystemApi
8493     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
call(String callingPackage, String number)8494     public void call(String callingPackage, String number) {
8495         try {
8496             ITelephony telephony = getITelephony();
8497             if (telephony != null)
8498                 telephony.call(callingPackage, number);
8499         } catch (RemoteException e) {
8500             Log.e(TAG, "Error calling ITelephony#call", e);
8501         }
8502     }
8503 
8504     /**
8505      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
8506      * @hide
8507      * @removed
8508      */
8509     @Deprecated
8510     @SystemApi
8511     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()8512     public boolean endCall() {
8513         return false;
8514     }
8515 
8516     /**
8517      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
8518      * @hide
8519      * @removed
8520      */
8521     @Deprecated
8522     @SystemApi
8523     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()8524     public void answerRingingCall() {
8525         // No-op
8526     }
8527 
8528     /**
8529      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
8530      * @hide
8531      */
8532     @Deprecated
8533     @SystemApi
8534     @SuppressLint("Doclava125")
silenceRinger()8535     public void silenceRinger() {
8536         // No-op
8537     }
8538 
8539     /**
8540      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
8541      * @hide
8542      */
8543     @Deprecated
8544     @SystemApi
8545     @RequiresPermission(anyOf = {
8546             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8547             android.Manifest.permission.READ_PHONE_STATE
8548     })
isOffhook()8549     public boolean isOffhook() {
8550         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8551         return tm.isInCall();
8552     }
8553 
8554     /**
8555      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
8556      * @hide
8557      */
8558     @Deprecated
8559     @SystemApi
8560     @RequiresPermission(anyOf = {
8561             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8562             android.Manifest.permission.READ_PHONE_STATE
8563     })
isRinging()8564     public boolean isRinging() {
8565         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8566         return tm.isRinging();
8567     }
8568 
8569     /**
8570      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
8571      * @hide
8572      */
8573     @Deprecated
8574     @SystemApi
8575     @RequiresPermission(anyOf = {
8576             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8577             android.Manifest.permission.READ_PHONE_STATE
8578     })
isIdle()8579     public boolean isIdle() {
8580         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
8581         return !tm.isInCall();
8582     }
8583 
8584     /**
8585      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
8586      * @hide
8587      */
8588     @Deprecated
8589     @SystemApi
8590     @RequiresPermission(anyOf = {
8591             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8592             android.Manifest.permission.READ_PHONE_STATE
8593     })
isRadioOn()8594     public boolean isRadioOn() {
8595         try {
8596             ITelephony telephony = getITelephony();
8597             if (telephony != null)
8598                 return telephony.isRadioOnWithFeature(getOpPackageName(), getFeatureId());
8599         } catch (RemoteException e) {
8600             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
8601         }
8602         return false;
8603     }
8604 
8605     /** @hide */
8606     @SystemApi
8607     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPin(String pin)8608     public boolean supplyPin(String pin) {
8609         try {
8610             ITelephony telephony = getITelephony();
8611             if (telephony != null)
8612                 return telephony.supplyPinForSubscriber(getSubId(), pin);
8613         } catch (RemoteException e) {
8614             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
8615         }
8616         return false;
8617     }
8618 
8619     /** @hide */
8620     @SystemApi
8621     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPuk(String puk, String pin)8622     public boolean supplyPuk(String puk, String pin) {
8623         try {
8624             ITelephony telephony = getITelephony();
8625             if (telephony != null)
8626                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
8627         } catch (RemoteException e) {
8628             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
8629         }
8630         return false;
8631     }
8632 
8633     /** @hide */
8634     @SystemApi
8635     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPinReportResult(String pin)8636     public int[] supplyPinReportResult(String pin) {
8637         try {
8638             ITelephony telephony = getITelephony();
8639             if (telephony != null)
8640                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
8641         } catch (RemoteException e) {
8642             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
8643         }
8644         return new int[0];
8645     }
8646 
8647     /** @hide */
8648     @SystemApi
8649     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPukReportResult(String puk, String pin)8650     public int[] supplyPukReportResult(String puk, String pin) {
8651         try {
8652             ITelephony telephony = getITelephony();
8653             if (telephony != null)
8654                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
8655         } catch (RemoteException e) {
8656             Log.e(TAG, "Error calling ITelephony#]", e);
8657         }
8658         return new int[0];
8659     }
8660 
8661     /**
8662      * Used when the user attempts to enter their pin.
8663      *
8664      * @param pin The user entered pin.
8665      * @return The result of the pin.
8666      *
8667      * @hide
8668      */
8669     @Nullable
8670     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPinReportPinResult(@onNull String pin)8671     public PinResult supplyPinReportPinResult(@NonNull String pin) {
8672         try {
8673             ITelephony telephony = getITelephony();
8674             if (telephony != null) {
8675                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
8676                 return new PinResult(result[0], result[1]);
8677             }
8678         } catch (RemoteException e) {
8679             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
8680         }
8681         return null;
8682     }
8683 
8684     /**
8685      * Used when the user attempts to enter the puk or their pin.
8686      *
8687      * @param puk The product unblocking key.
8688      * @param pin The user entered pin.
8689      * @return The result of the pin.
8690      *
8691      * @hide
8692      */
8693     @Nullable
8694     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPukReportPinResult(@onNull String puk, @NonNull String pin)8695     public PinResult supplyPukReportPinResult(@NonNull String puk, @NonNull String pin) {
8696         try {
8697             ITelephony telephony = getITelephony();
8698             if (telephony != null) {
8699                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
8700                 return new PinResult(result[0], result[1]);
8701             }
8702         } catch (RemoteException e) {
8703             Log.e(TAG, "Error calling ITelephony#]", e);
8704         }
8705         return null;
8706     }
8707 
8708     /**
8709      * Used to notify callers of
8710      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
8711      * network either successfully executes a USSD request, or if there was a failure while
8712      * executing the request.
8713      * <p>
8714      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
8715      * USSD request has succeeded.
8716      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
8717      * USSD request has failed.
8718      */
8719     public static abstract class UssdResponseCallback {
8720        /**
8721         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
8722         * response received from the network.  The calling app can choose to either display the
8723         * response to the user or perform some operation based on the response.
8724         * <p>
8725         * USSD responses are unstructured text and their content is determined by the mobile network
8726         * operator.
8727         *
8728         * @param telephonyManager the TelephonyManager the callback is registered to.
8729         * @param request the USSD request sent to the mobile network.
8730         * @param response the response to the USSD request provided by the mobile network.
8731         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)8732        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
8733                                          String request, CharSequence response) {};
8734 
8735        /**
8736         * Called when a USSD request has failed to complete.
8737         *
8738         * @param telephonyManager the TelephonyManager the callback is registered to.
8739         * @param request the USSD request sent to the mobile network.
8740         * @param failureCode failure code indicating why the request failed.  Will be either
8741         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
8742         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
8743         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)8744        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
8745                                                String request, int failureCode) {};
8746     }
8747 
8748     /**
8749      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
8750      * informs the caller of the response via the supplied {@code callback}.
8751      * <p>Carriers define USSD codes which can be sent by the user to request information such as
8752      * the user's current data balance or minutes balance.
8753      * <p>Requires permission:
8754      * {@link android.Manifest.permission#CALL_PHONE}
8755      * @param ussdRequest the USSD command to be executed.
8756      * @param callback called by the framework to inform the caller of the result of executing the
8757      *                 USSD request (see {@link UssdResponseCallback}).
8758      * @param handler the {@link Handler} to run the request on.
8759      */
8760     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)8761     public void sendUssdRequest(String ussdRequest,
8762                                 final UssdResponseCallback callback, Handler handler) {
8763         checkNotNull(callback, "UssdResponseCallback cannot be null.");
8764         final TelephonyManager telephonyManager = this;
8765 
8766         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
8767             @Override
8768             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
8769                 Rlog.d(TAG, "USSD:" + resultCode);
8770                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
8771                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE);
8772 
8773                 if (resultCode == USSD_RETURN_SUCCESS) {
8774                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
8775                             response.getReturnMessage());
8776                 } else {
8777                     callback.onReceiveUssdResponseFailed(telephonyManager,
8778                             response.getUssdRequest(), resultCode);
8779                 }
8780             }
8781         };
8782 
8783         try {
8784             ITelephony telephony = getITelephony();
8785             if (telephony != null) {
8786                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
8787             }
8788         } catch (RemoteException e) {
8789             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
8790             UssdResponse response = new UssdResponse(ussdRequest, "");
8791             Bundle returnData = new Bundle();
8792             returnData.putParcelable(USSD_RESPONSE, response);
8793             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
8794         }
8795     }
8796 
8797     /**
8798      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
8799      * voice and data simultaneously. This can change based on location or network condition.
8800      *
8801      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
8802      */
isConcurrentVoiceAndDataSupported()8803     public boolean isConcurrentVoiceAndDataSupported() {
8804         try {
8805             ITelephony telephony = getITelephony();
8806             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
8807                     getSubId()));
8808         } catch (RemoteException e) {
8809             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
8810         }
8811         return false;
8812     }
8813 
8814     /** @hide */
8815     @SystemApi
8816     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmi(String dialString)8817     public boolean handlePinMmi(String dialString) {
8818         try {
8819             ITelephony telephony = getITelephony();
8820             if (telephony != null)
8821                 return telephony.handlePinMmi(dialString);
8822         } catch (RemoteException e) {
8823             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
8824         }
8825         return false;
8826     }
8827 
8828     /** @hide */
8829     @SystemApi
8830     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmiForSubscriber(int subId, String dialString)8831     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
8832         try {
8833             ITelephony telephony = getITelephony();
8834             if (telephony != null)
8835                 return telephony.handlePinMmiForSubscriber(subId, dialString);
8836         } catch (RemoteException e) {
8837             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
8838         }
8839         return false;
8840     }
8841 
8842     /** @hide */
8843     @SystemApi
8844     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
toggleRadioOnOff()8845     public void toggleRadioOnOff() {
8846         try {
8847             ITelephony telephony = getITelephony();
8848             if (telephony != null)
8849                 telephony.toggleRadioOnOff();
8850         } catch (RemoteException e) {
8851             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
8852         }
8853     }
8854 
8855     /** @hide */
8856     @SystemApi
8857     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadio(boolean turnOn)8858     public boolean setRadio(boolean turnOn) {
8859         try {
8860             ITelephony telephony = getITelephony();
8861             if (telephony != null)
8862                 return telephony.setRadio(turnOn);
8863         } catch (RemoteException e) {
8864             Log.e(TAG, "Error calling ITelephony#setRadio", e);
8865         }
8866         return false;
8867     }
8868 
8869     /** @hide */
8870     @SystemApi
8871     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioPower(boolean turnOn)8872     public boolean setRadioPower(boolean turnOn) {
8873         try {
8874             ITelephony telephony = getITelephony();
8875             if (telephony != null)
8876                 return telephony.setRadioPower(turnOn);
8877         } catch (RemoteException e) {
8878             Log.e(TAG, "Error calling ITelephony#setRadioPower", e);
8879         }
8880         return false;
8881     }
8882 
8883     /**
8884      * Shut down all the live radios over all the slot indexes.
8885      *
8886      * <p>To know when the radio has completed powering off, use
8887      * {@link PhoneStateListener#LISTEN_SERVICE_STATE LISTEN_SERVICE_STATE}.
8888      *
8889      * @hide
8890      */
8891     @SystemApi
8892     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
shutdownAllRadios()8893     public void shutdownAllRadios() {
8894         try {
8895             ITelephony telephony = getITelephony();
8896             if (telephony != null) {
8897                 telephony.shutdownMobileRadios();
8898             }
8899         } catch (RemoteException e) {
8900             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
8901             e.rethrowAsRuntimeException();
8902         }
8903     }
8904 
8905     /**
8906      * Check if any radio is on over all the slot indexes.
8907      *
8908      * @return {@code true} if any radio is on over any slot index.
8909      * @hide
8910      */
8911     @SystemApi
8912     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isAnyRadioPoweredOn()8913     public boolean isAnyRadioPoweredOn() {
8914         try {
8915             ITelephony telephony = getITelephony();
8916             if (telephony != null) {
8917                 return telephony.needMobileRadioShutdown();
8918             }
8919         } catch (RemoteException e) {
8920             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
8921             e.rethrowAsRuntimeException();
8922         }
8923         return false;
8924     }
8925 
8926     /**
8927      * Radio explicitly powered off (e.g, airplane mode).
8928      * @hide
8929      */
8930     @SystemApi
8931     public static final int RADIO_POWER_OFF = 0;
8932 
8933     /**
8934      * Radio power is on.
8935      * @hide
8936      */
8937     @SystemApi
8938     public static final int RADIO_POWER_ON = 1;
8939 
8940     /**
8941      * Radio power unavailable (eg, modem resetting or not booted).
8942      * @hide
8943      */
8944     @SystemApi
8945     public static final int RADIO_POWER_UNAVAILABLE = 2;
8946 
8947     /**
8948      * @return current modem radio state.
8949      *
8950      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
8951      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
8952      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8953      *
8954      * @hide
8955      */
8956     @SystemApi
8957     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8958             android.Manifest.permission.READ_PHONE_STATE})
getRadioPowerState()8959     public @RadioPowerState int getRadioPowerState() {
8960         try {
8961             ITelephony telephony = getITelephony();
8962             if (telephony != null) {
8963                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
8964                         null);
8965             }
8966         } catch (RemoteException ex) {
8967             // This could happen if binder process crashes.
8968         }
8969         return RADIO_POWER_UNAVAILABLE;
8970     }
8971 
8972     /**
8973      * This method should not be used due to privacy and stability concerns.
8974      *
8975      * @hide
8976      */
8977     @SystemApi
updateServiceLocation()8978     public void updateServiceLocation() {
8979         Log.e(TAG, "Do not call TelephonyManager#updateServiceLocation()");
8980     }
8981 
8982     /** @hide */
8983     @SystemApi
8984     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableDataConnectivity()8985     public boolean enableDataConnectivity() {
8986         try {
8987             ITelephony telephony = getITelephony();
8988             if (telephony != null)
8989                 return telephony.enableDataConnectivity();
8990         } catch (RemoteException e) {
8991             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
8992         }
8993         return false;
8994     }
8995 
8996     /** @hide */
8997     @SystemApi
8998     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
disableDataConnectivity()8999     public boolean disableDataConnectivity() {
9000         try {
9001             ITelephony telephony = getITelephony();
9002             if (telephony != null)
9003                 return telephony.disableDataConnectivity();
9004         } catch (RemoteException e) {
9005             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
9006         }
9007         return false;
9008     }
9009 
9010     /** @hide */
9011     @SystemApi
isDataConnectivityPossible()9012     public boolean isDataConnectivityPossible() {
9013         try {
9014             ITelephony telephony = getITelephony();
9015             if (telephony != null)
9016                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
9017                         .getActiveDataSubscriptionId()));
9018         } catch (RemoteException e) {
9019             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
9020         }
9021         return false;
9022     }
9023 
9024     /** @hide */
9025     @SystemApi
needsOtaServiceProvisioning()9026     public boolean needsOtaServiceProvisioning() {
9027         try {
9028             ITelephony telephony = getITelephony();
9029             if (telephony != null)
9030                 return telephony.needsOtaServiceProvisioning();
9031         } catch (RemoteException e) {
9032             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
9033         }
9034         return false;
9035     }
9036 
9037     /**
9038      * Turns mobile data on or off.
9039      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9040      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9041      *
9042      * <p>Requires Permission:
9043      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9044      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9045      *
9046      * @param enable Whether to enable mobile data.
9047      *
9048      */
9049     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9050     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(boolean enable)9051     public void setDataEnabled(boolean enable) {
9052         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
9053     }
9054 
9055     /**
9056      * @hide
9057      * @deprecated use {@link #setDataEnabled(boolean)} instead.
9058     */
9059     @SystemApi
9060     @Deprecated
9061     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(int subId, boolean enable)9062     public void setDataEnabled(int subId, boolean enable) {
9063         try {
9064             Log.d(TAG, "setDataEnabled: enabled=" + enable);
9065             ITelephony telephony = getITelephony();
9066             if (telephony != null)
9067                 telephony.setUserDataEnabled(subId, enable);
9068         } catch (RemoteException e) {
9069             Log.e(TAG, "Error calling ITelephony#setUserDataEnabled", e);
9070         }
9071     }
9072 
9073     /**
9074      * @deprecated use {@link #isDataEnabled()} instead.
9075      * @hide
9076      */
9077     @SystemApi
9078     @Deprecated
getDataEnabled()9079     public boolean getDataEnabled() {
9080         return isDataEnabled();
9081     }
9082 
9083     /**
9084      * Returns whether mobile data is enabled or not per user setting. There are other factors
9085      * that could disable mobile data, but they are not considered here.
9086      *
9087      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9088      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9089      *
9090      * <p>Requires one of the following permissions:
9091      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9092      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or that the calling app has carrier
9093      * privileges (see {@link #hasCarrierPrivileges}).
9094      *
9095      * <p>Note that this does not take into account any data restrictions that may be present on the
9096      * calling app. Such restrictions may be inspected with
9097      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
9098      *
9099      * @return true if mobile data is enabled.
9100      */
9101     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9102             android.Manifest.permission.MODIFY_PHONE_STATE})
isDataEnabled()9103     public boolean isDataEnabled() {
9104         return getDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
9105     }
9106 
9107     /**
9108      * Returns whether mobile data roaming is enabled on the subscription.
9109      *
9110      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9111      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9112      *
9113      * <p>Requires one of the following permissions:
9114      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9115      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling app
9116      * has carrier privileges (see {@link #hasCarrierPrivileges}).
9117      *
9118      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
9119      * {@code false}.
9120      */
9121     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9122             android.Manifest.permission.READ_PHONE_STATE})
isDataRoamingEnabled()9123     public boolean isDataRoamingEnabled() {
9124         boolean isDataRoamingEnabled = false;
9125         try {
9126             ITelephony telephony = getITelephony();
9127             if (telephony != null) {
9128                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
9129                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
9130             }
9131         } catch (RemoteException e) {
9132             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
9133         }
9134         return isDataRoamingEnabled;
9135     }
9136 
9137     /**
9138      * Gets the roaming mode for CDMA phone.
9139      *
9140      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9141      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9142      *
9143      * @return one of {@link #CDMA_ROAMING_MODE_RADIO_DEFAULT}, {@link #CDMA_ROAMING_MODE_HOME},
9144      * {@link #CDMA_ROAMING_MODE_AFFILIATED}, {@link #CDMA_ROAMING_MODE_ANY}.
9145      *
9146      * @hide
9147      */
9148     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaRoamingMode()9149     public @CdmaRoamingMode int getCdmaRoamingMode() {
9150         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
9151         try {
9152             ITelephony telephony = getITelephony();
9153             if (telephony != null) {
9154                 mode = telephony.getCdmaRoamingMode(getSubId());
9155             }
9156         } catch (RemoteException ex) {
9157             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
9158         }
9159         return mode;
9160     }
9161 
9162     /**
9163      * Sets the roaming mode for CDMA phone to the given mode {@code mode}.
9164      *
9165      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9166      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9167      *
9168      * @param mode should be one of {@link #CDMA_ROAMING_MODE_RADIO_DEFAULT},
9169      * {@link #CDMA_ROAMING_MODE_HOME}, {@link #CDMA_ROAMING_MODE_AFFILIATED},
9170      * {@link #CDMA_ROAMING_MODE_ANY}.
9171      *
9172      * @return {@code true} if successed.
9173      *
9174      * @hide
9175      */
9176     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaRoamingMode(@dmaRoamingMode int mode)9177     public boolean setCdmaRoamingMode(@CdmaRoamingMode int mode) {
9178         try {
9179             ITelephony telephony = getITelephony();
9180             if (telephony != null) {
9181                 return telephony.setCdmaRoamingMode(getSubId(), mode);
9182             }
9183         } catch (RemoteException ex) {
9184             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
9185         }
9186         return false;
9187     }
9188 
9189     /** @hide */
9190     @IntDef(flag = true, prefix = { "CDMA_SUBSCRIPTION_" }, value = {
9191             CDMA_SUBSCRIPTION_UNKNOWN,
9192             CDMA_SUBSCRIPTION_RUIM_SIM,
9193             CDMA_SUBSCRIPTION_NV
9194     })
9195     @Retention(RetentionPolicy.SOURCE)
9196     public @interface CdmaSubscription{}
9197 
9198     /** Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
9199      * @hide
9200      */
9201     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
9202 
9203     /** Used for CDMA subscription mode: RUIM/SIM (default)
9204      * @hide
9205      */
9206     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
9207 
9208     /** Used for CDMA subscription mode: NV -> non-volatile memory
9209      * @hide
9210      */
9211     public static final int CDMA_SUBSCRIPTION_NV       = 1;
9212 
9213     /** @hide */
9214     public static final int PREFERRED_CDMA_SUBSCRIPTION = CDMA_SUBSCRIPTION_RUIM_SIM;
9215 
9216     /**
9217      * Sets the subscription mode for CDMA phone to the given mode {@code mode}.
9218      *
9219      * @param mode CDMA subscription mode
9220      *
9221      * @return {@code true} if successed.
9222      *
9223      * @see #CDMA_SUBSCRIPTION_UNKNOWN
9224      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
9225      * @see #CDMA_SUBSCRIPTION_NV
9226      *
9227      * @hide
9228      */
9229     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaSubscriptionMode(@dmaSubscription int mode)9230     public boolean setCdmaSubscriptionMode(@CdmaSubscription int mode) {
9231         try {
9232             ITelephony telephony = getITelephony();
9233             if (telephony != null) {
9234                 return telephony.setCdmaSubscriptionMode(getSubId(), mode);
9235             }
9236         } catch (RemoteException ex) {
9237             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
9238         }
9239         return false;
9240     }
9241 
9242     /**
9243      * Enables/Disables the data roaming on the subscription.
9244      *
9245      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9246      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9247      *
9248      * <p> Requires permission:
9249      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
9250      * privileges (see {@link #hasCarrierPrivileges}).
9251      *
9252      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
9253      *
9254      * @hide
9255      */
9256     @SystemApi
9257     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataRoamingEnabled(boolean isEnabled)9258     public void setDataRoamingEnabled(boolean isEnabled) {
9259         try {
9260             ITelephony telephony = getITelephony();
9261             if (telephony != null) {
9262                 telephony.setDataRoamingEnabled(
9263                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
9264             }
9265         } catch (RemoteException e) {
9266             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
9267         }
9268     }
9269 
9270     /**
9271      * @deprecated use {@link #isDataEnabled()} instead.
9272      * @hide
9273      */
9274     @Deprecated
9275     @SystemApi
getDataEnabled(int subId)9276     public boolean getDataEnabled(int subId) {
9277         boolean retVal = false;
9278         try {
9279             ITelephony telephony = getITelephony();
9280             if (telephony != null)
9281                 retVal = telephony.isUserDataEnabled(subId);
9282         } catch (RemoteException | NullPointerException e) {
9283             Log.e(TAG, "Error calling ITelephony#isUserDataEnabled", e);
9284         }
9285         return retVal;
9286     }
9287 
9288     /**
9289      * Returns the result and response from RIL for oem request
9290      *
9291      * @param oemReq the data is sent to ril.
9292      * @param oemResp the respose data from RIL.
9293      * @return negative value request was not handled or get error
9294      *         0 request was handled succesfully, but no response data
9295      *         positive value success, data length of response
9296      * @hide
9297      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
9298      */
9299     @Deprecated
invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp)9300     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
9301         try {
9302             ITelephony telephony = getITelephony();
9303             if (telephony != null)
9304                 return telephony.invokeOemRilRequestRaw(oemReq, oemResp);
9305         } catch (RemoteException ex) {
9306         } catch (NullPointerException ex) {
9307         }
9308         return -1;
9309     }
9310 
9311     /**
9312      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
9313      * instead.
9314      * @hide
9315      */
9316     @Deprecated
9317     @SystemApi
9318     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableVideoCalling(boolean enable)9319     public void enableVideoCalling(boolean enable) {
9320         try {
9321             ITelephony telephony = getITelephony();
9322             if (telephony != null)
9323                 telephony.enableVideoCalling(enable);
9324         } catch (RemoteException e) {
9325             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
9326         }
9327     }
9328 
9329     /**
9330      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
9331      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
9332      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
9333      * determine if video calling is capable.
9334      * @hide
9335      */
9336     @Deprecated
9337     @SystemApi
9338     @RequiresPermission(anyOf = {
9339             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9340             android.Manifest.permission.READ_PHONE_STATE
9341     })
isVideoCallingEnabled()9342     public boolean isVideoCallingEnabled() {
9343         try {
9344             ITelephony telephony = getITelephony();
9345             if (telephony != null)
9346                 return telephony.isVideoCallingEnabled(getOpPackageName(), getFeatureId());
9347         } catch (RemoteException e) {
9348             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
9349         }
9350         return false;
9351     }
9352 
9353     /**
9354      * Whether the device supports configuring the DTMF tone length.
9355      *
9356      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
9357      */
canChangeDtmfToneLength()9358     public boolean canChangeDtmfToneLength() {
9359         try {
9360             ITelephony telephony = getITelephony();
9361             if (telephony != null) {
9362                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
9363                         getFeatureId());
9364             }
9365         } catch (RemoteException e) {
9366             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
9367         } catch (SecurityException e) {
9368             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
9369         }
9370         return false;
9371     }
9372 
9373     /**
9374      * Whether the device is a world phone.
9375      *
9376      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
9377      */
isWorldPhone()9378     public boolean isWorldPhone() {
9379         try {
9380             ITelephony telephony = getITelephony();
9381             if (telephony != null) {
9382                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getFeatureId());
9383             }
9384         } catch (RemoteException e) {
9385             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
9386         } catch (SecurityException e) {
9387             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
9388         }
9389         return false;
9390     }
9391 
9392     /**
9393      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
9394      * Whether the phone supports TTY mode.
9395      *
9396      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
9397      *
9398      */
9399     @Deprecated
isTtyModeSupported()9400     public boolean isTtyModeSupported() {
9401         try {
9402             TelecomManager telecomManager = null;
9403             if (mContext != null) {
9404                 telecomManager = mContext.getSystemService(TelecomManager.class);
9405             }
9406             if (telecomManager != null) {
9407                 return telecomManager.isTtySupported();
9408             }
9409         } catch (SecurityException e) {
9410             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
9411         }
9412         return false;
9413     }
9414 
9415     /**
9416      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
9417      * support for the feature and device firmware support.
9418      *
9419      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
9420      */
isRttSupported()9421     public boolean isRttSupported() {
9422         try {
9423             ITelephony telephony = getITelephony();
9424             if (telephony != null) {
9425                 return telephony.isRttSupported(mSubId);
9426             }
9427         } catch (RemoteException e) {
9428             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
9429         } catch (SecurityException e) {
9430             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
9431         }
9432         return false;
9433     }
9434     /**
9435      * Whether the phone supports hearing aid compatibility.
9436      *
9437      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
9438      * otherwise.
9439      */
isHearingAidCompatibilitySupported()9440     public boolean isHearingAidCompatibilitySupported() {
9441         try {
9442             ITelephony telephony = getITelephony();
9443             if (telephony != null) {
9444                 return telephony.isHearingAidCompatibilitySupported();
9445             }
9446         } catch (RemoteException e) {
9447             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
9448         } catch (SecurityException e) {
9449             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
9450         }
9451         return false;
9452     }
9453 
9454     /**
9455      * Returns the IMS Registration Status for a particular Subscription ID.
9456      *
9457      * @param subId Subscription ID
9458      * @return true if IMS status is registered, false if the IMS status is not registered or a
9459      * RemoteException occurred.
9460      * Use {@link ImsMmTelManager.RegistrationCallback} instead.
9461      * @hide
9462      */
isImsRegistered(int subId)9463     public boolean isImsRegistered(int subId) {
9464         try {
9465             return getITelephony().isImsRegistered(subId);
9466         } catch (RemoteException | NullPointerException ex) {
9467             return false;
9468         }
9469     }
9470 
9471     /**
9472      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
9473      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
9474      * invalid subscription ID is used during creation, will the default subscription ID will be
9475      * used.
9476      *
9477      * @return true if IMS status is registered, false if the IMS status is not registered or a
9478      * RemoteException occurred.
9479      * @see SubscriptionManager#getDefaultSubscriptionId()
9480      * @hide
9481      */
9482     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()9483     public boolean isImsRegistered() {
9484        try {
9485            return getITelephony().isImsRegistered(getSubId());
9486        } catch (RemoteException | NullPointerException ex) {
9487            return false;
9488        }
9489     }
9490 
9491     /**
9492      * The current status of Voice over LTE for the subscription associated with this instance when
9493      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
9494      * used during creation, the default subscription ID will be used.
9495      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
9496      * @see SubscriptionManager#getDefaultSubscriptionId()
9497      * <p>
9498      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9499      * @hide
9500      */
9501     @UnsupportedAppUsage
isVolteAvailable()9502     public boolean isVolteAvailable() {
9503         try {
9504             return getITelephony().isAvailable(getSubId(),
9505                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
9506                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
9507         } catch (RemoteException | NullPointerException ex) {
9508             return false;
9509         }
9510     }
9511 
9512     /**
9513      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
9514      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
9515      * used during creation, the default subscription ID will be used. To query the
9516      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
9517      * @return true if VT is available, or false if it is unavailable or unknown.
9518      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9519      * @hide
9520      */
9521     @UnsupportedAppUsage
isVideoTelephonyAvailable()9522     public boolean isVideoTelephonyAvailable() {
9523         try {
9524             return getITelephony().isVideoTelephonyAvailable(getSubId());
9525         } catch (RemoteException | NullPointerException ex) {
9526             return false;
9527         }
9528     }
9529 
9530     /**
9531      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
9532      * @param subId the subscription ID.
9533      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
9534      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
9535      * @hide
9536      */
9537     @UnsupportedAppUsage
isWifiCallingAvailable()9538     public boolean isWifiCallingAvailable() {
9539        try {
9540            return getITelephony().isWifiCallingAvailable(getSubId());
9541        } catch (RemoteException | NullPointerException ex) {
9542            return false;
9543        }
9544    }
9545 
9546     /**
9547      * The technology that IMS is registered for for the MMTEL feature.
9548      * @param subId subscription ID to get IMS registration technology for.
9549      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
9550      * Valid return results are:
9551      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
9552      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
9553      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
9554      *  result is unavailable.
9555      *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
9556      *  @hide
9557      */
getImsRegTechnologyForMmTel()9558     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
9559         try {
9560             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
9561         } catch (RemoteException ex) {
9562             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
9563         }
9564     }
9565 
9566    /**
9567     * Set TelephonyProperties.icc_operator_numeric for the default phone.
9568     *
9569     * @hide
9570     */
setSimOperatorNumeric(String numeric)9571     public void setSimOperatorNumeric(String numeric) {
9572         int phoneId = getPhoneId();
9573         setSimOperatorNumericForPhone(phoneId, numeric);
9574     }
9575 
9576    /**
9577     * Set TelephonyProperties.icc_operator_numeric for the given phone.
9578     *
9579     * @hide
9580     */
9581     @UnsupportedAppUsage
setSimOperatorNumericForPhone(int phoneId, String numeric)9582     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
9583         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9584             List<String> newList = updateTelephonyProperty(
9585                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
9586             TelephonyProperties.icc_operator_numeric(newList);
9587         }
9588     }
9589 
9590     /**
9591      * Set TelephonyProperties.icc_operator_alpha for the default phone.
9592      *
9593      * @hide
9594      */
setSimOperatorName(String name)9595     public void setSimOperatorName(String name) {
9596         int phoneId = getPhoneId();
9597         setSimOperatorNameForPhone(phoneId, name);
9598     }
9599 
9600     /**
9601      * Set TelephonyProperties.icc_operator_alpha for the given phone.
9602      *
9603      * @hide
9604      */
9605     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)9606     public void setSimOperatorNameForPhone(int phoneId, String name) {
9607         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9608             List<String> newList = updateTelephonyProperty(
9609                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
9610             TelephonyProperties.icc_operator_alpha(newList);
9611         }
9612     }
9613 
9614    /**
9615     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
9616     *
9617     * @hide
9618     */
setSimCountryIso(String iso)9619     public void setSimCountryIso(String iso) {
9620         int phoneId = getPhoneId();
9621         setSimCountryIsoForPhone(phoneId, iso);
9622     }
9623 
9624    /**
9625     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
9626     *
9627     * @hide
9628     */
9629     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)9630     public void setSimCountryIsoForPhone(int phoneId, String iso) {
9631         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9632             List<String> newList = updateTelephonyProperty(
9633                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
9634             TelephonyProperties.icc_operator_iso_country(newList);
9635         }
9636     }
9637 
9638     /**
9639      * Set TelephonyProperties.sim_state for the default phone.
9640      *
9641      * @hide
9642      */
setSimState(String state)9643     public void setSimState(String state) {
9644         int phoneId = getPhoneId();
9645         setSimStateForPhone(phoneId, state);
9646     }
9647 
9648     /**
9649      * Set TelephonyProperties.sim_state for the given phone.
9650      *
9651      * @hide
9652      */
9653     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)9654     public void setSimStateForPhone(int phoneId, String state) {
9655         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9656             List<String> newList = updateTelephonyProperty(
9657                     TelephonyProperties.sim_state(), phoneId, state);
9658             TelephonyProperties.sim_state(newList);
9659         }
9660     }
9661 
9662     /**
9663      * Powers down the SIM. SIM must be up prior.
9664      * @hide
9665      */
9666     public static final int CARD_POWER_DOWN = 0;
9667 
9668     /**
9669      * Powers up the SIM normally. SIM must be down prior.
9670      * @hide
9671      */
9672     public static final int CARD_POWER_UP = 1;
9673 
9674     /**
9675      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
9676      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
9677      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
9678      * and the SIM card is controlled completely by Telephony sending APDUs
9679      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
9680      * number of card apps will be 0.
9681      * No new error code is generated. Emergency calls are supported in the
9682      * same way as if the SIM card is absent.
9683      * The PASS_THROUGH mode is valid only for the specific card session where it
9684      * is activated, and normal behavior occurs at the next SIM initialization,
9685      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
9686      * is NOT persistent across boots. On reboot, SIM will power up normally.
9687      * @hide
9688      */
9689     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
9690 
9691     /**
9692      * Set SIM card power state.
9693      *
9694      * @param state  State of SIM (power down, power up, pass through)
9695      * @see #CARD_POWER_DOWN
9696      * @see #CARD_POWER_UP
9697      * @see #CARD_POWER_UP_PASS_THROUGH
9698      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
9699      * broadcasts to determine success or failure and timeout if needed.
9700      *
9701      * <p>Requires Permission:
9702      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
9703      *
9704      * {@hide}
9705      **/
9706     @SystemApi
9707     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerState(int state)9708     public void setSimPowerState(int state) {
9709         setSimPowerStateForSlot(getSlotIndex(), state);
9710     }
9711 
9712     /**
9713      * Set SIM card power state.
9714      *
9715      * @param slotIndex SIM slot id
9716      * @param state  State of SIM (power down, power up, pass through)
9717      * @see #CARD_POWER_DOWN
9718      * @see #CARD_POWER_UP
9719      * @see #CARD_POWER_UP_PASS_THROUGH
9720      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
9721      * broadcasts to determine success or failure and timeout if needed.
9722      *
9723      * <p>Requires Permission:
9724      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
9725      *
9726      * {@hide}
9727      **/
9728     @SystemApi
9729     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerStateForSlot(int slotIndex, int state)9730     public void setSimPowerStateForSlot(int slotIndex, int state) {
9731         try {
9732             ITelephony telephony = getITelephony();
9733             if (telephony != null) {
9734                 telephony.setSimPowerStateForSlot(slotIndex, state);
9735             }
9736         } catch (RemoteException e) {
9737             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
9738         } catch (SecurityException e) {
9739             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
9740         }
9741     }
9742 
9743     /**
9744      * Set baseband version for the default phone.
9745      *
9746      * @param version baseband version
9747      * @hide
9748      */
setBasebandVersion(String version)9749     public void setBasebandVersion(String version) {
9750         int phoneId = getPhoneId();
9751         setBasebandVersionForPhone(phoneId, version);
9752     }
9753 
9754     /**
9755      * Set baseband version by phone id.
9756      *
9757      * @param phoneId for which baseband version is set
9758      * @param version baseband version
9759      * @hide
9760      */
9761     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)9762     public void setBasebandVersionForPhone(int phoneId, String version) {
9763         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9764             List<String> newList = updateTelephonyProperty(
9765                     TelephonyProperties.baseband_version(), phoneId, version);
9766             TelephonyProperties.baseband_version(newList);
9767         }
9768     }
9769 
9770     /**
9771      * Get baseband version for the default phone.
9772      *
9773      * @return baseband version.
9774      * @hide
9775      */
getBasebandVersion()9776     public String getBasebandVersion() {
9777         int phoneId = getPhoneId();
9778         return getBasebandVersionForPhone(phoneId);
9779     }
9780 
9781     /**
9782      * Get baseband version by phone id.
9783      *
9784      * @return baseband version.
9785      * @hide
9786      */
getBasebandVersionForPhone(int phoneId)9787     public String getBasebandVersionForPhone(int phoneId) {
9788         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
9789     }
9790 
9791     /**
9792      * Set phone type for the default phone.
9793      *
9794      * @param type phone type
9795      *
9796      * @hide
9797      */
setPhoneType(int type)9798     public void setPhoneType(int type) {
9799         int phoneId = getPhoneId();
9800         setPhoneType(phoneId, type);
9801     }
9802 
9803     /**
9804      * Set phone type by phone id.
9805      *
9806      * @param phoneId for which phone type is set
9807      * @param type phone type
9808      *
9809      * @hide
9810      */
9811     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)9812     public void setPhoneType(int phoneId, int type) {
9813         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9814             List<Integer> newList = updateTelephonyProperty(
9815                     TelephonyProperties.current_active_phone(), phoneId, type);
9816             TelephonyProperties.current_active_phone(newList);
9817         }
9818     }
9819 
9820     /**
9821      * Get OTASP number schema for the default phone.
9822      *
9823      * @param defaultValue default value
9824      * @return OTA SP number schema
9825      *
9826      * @hide
9827      */
getOtaSpNumberSchema(String defaultValue)9828     public String getOtaSpNumberSchema(String defaultValue) {
9829         int phoneId = getPhoneId();
9830         return getOtaSpNumberSchemaForPhone(phoneId, defaultValue);
9831     }
9832 
9833     /**
9834      * Get OTASP number schema by phone id.
9835      *
9836      * @param phoneId for which OTA SP number schema is get
9837      * @param defaultValue default value
9838      * @return OTA SP number schema
9839      *
9840      * @hide
9841      */
9842     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)9843     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
9844         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9845             return getTelephonyProperty(
9846                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
9847         }
9848 
9849         return defaultValue;
9850     }
9851 
9852     /**
9853      * Get SMS receive capable from system property for the default phone.
9854      *
9855      * @param defaultValue default value
9856      * @return SMS receive capable
9857      *
9858      * @hide
9859      */
getSmsReceiveCapable(boolean defaultValue)9860     public boolean getSmsReceiveCapable(boolean defaultValue) {
9861         int phoneId = getPhoneId();
9862         return getSmsReceiveCapableForPhone(phoneId, defaultValue);
9863     }
9864 
9865     /**
9866      * Get SMS receive capable from system property by phone id.
9867      *
9868      * @param phoneId for which SMS receive capable is get
9869      * @param defaultValue default value
9870      * @return SMS receive capable
9871      *
9872      * @hide
9873      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)9874     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
9875         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9876             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
9877         }
9878 
9879         return defaultValue;
9880     }
9881 
9882     /**
9883      * Get SMS send capable from system property for the default phone.
9884      *
9885      * @param defaultValue default value
9886      * @return SMS send capable
9887      *
9888      * @hide
9889      */
getSmsSendCapable(boolean defaultValue)9890     public boolean getSmsSendCapable(boolean defaultValue) {
9891         int phoneId = getPhoneId();
9892         return getSmsSendCapableForPhone(phoneId, defaultValue);
9893     }
9894 
9895     /**
9896      * Get SMS send capable from system property by phone id.
9897      *
9898      * @param phoneId for which SMS send capable is get
9899      * @param defaultValue default value
9900      * @return SMS send capable
9901      *
9902      * @hide
9903      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)9904     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
9905         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9906             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
9907         }
9908 
9909         return defaultValue;
9910     }
9911 
9912     /**
9913      * Gets the default Respond Via Message application
9914      * @param context context from the calling app
9915      * @param updateIfNeeded update the default app if there is no valid default app configured.
9916      * @return component name of the app and class to direct Respond Via Message intent to, or
9917      * {@code null} if the functionality is not supported.
9918      * @hide
9919      */
9920     @SystemApi
9921     @TestApi
getDefaultRespondViaMessageApplication( @onNull Context context, boolean updateIfNeeded)9922     public static @Nullable ComponentName getDefaultRespondViaMessageApplication(
9923             @NonNull Context context, boolean updateIfNeeded) {
9924         return SmsApplication.getDefaultRespondViaMessageApplication(context, updateIfNeeded);
9925     }
9926 
9927     /**
9928      * Set the alphabetic name of current registered operator.
9929      * @param name the alphabetic name of current registered operator.
9930      * @hide
9931      */
setNetworkOperatorName(String name)9932     public void setNetworkOperatorName(String name) {
9933         int phoneId = getPhoneId();
9934         setNetworkOperatorNameForPhone(phoneId, name);
9935     }
9936 
9937     /**
9938      * Set the alphabetic name of current registered operator.
9939      * @param phoneId which phone you want to set
9940      * @param name the alphabetic name of current registered operator.
9941      * @hide
9942      */
9943     @UnsupportedAppUsage
setNetworkOperatorNameForPhone(int phoneId, String name)9944     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
9945         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9946             List<String> newList = updateTelephonyProperty(
9947                     TelephonyProperties.operator_alpha(), phoneId, name);
9948             TelephonyProperties.operator_alpha(newList);
9949         }
9950     }
9951 
9952     /**
9953      * Set the numeric name (MCC+MNC) of current registered operator.
9954      * @param operator the numeric name (MCC+MNC) of current registered operator
9955      * @hide
9956      */
setNetworkOperatorNumeric(String numeric)9957     public void setNetworkOperatorNumeric(String numeric) {
9958         int phoneId = getPhoneId();
9959         setNetworkOperatorNumericForPhone(phoneId, numeric);
9960     }
9961 
9962     /**
9963      * Set the numeric name (MCC+MNC) of current registered operator.
9964      * @param phoneId for which phone type is set
9965      * @param operator the numeric name (MCC+MNC) of current registered operator
9966      * @hide
9967      */
9968     @UnsupportedAppUsage
setNetworkOperatorNumericForPhone(int phoneId, String numeric)9969     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
9970         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9971             List<String> newList = updateTelephonyProperty(
9972                     TelephonyProperties.operator_numeric(), phoneId, numeric);
9973             TelephonyProperties.operator_numeric(newList);
9974         }
9975     }
9976 
9977     /**
9978      * Set roaming state of the current network, for GSM purposes.
9979      * @param isRoaming is network in romaing state or not
9980      * @hide
9981      */
setNetworkRoaming(boolean isRoaming)9982     public void setNetworkRoaming(boolean isRoaming) {
9983         int phoneId = getPhoneId();
9984         setNetworkRoamingForPhone(phoneId, isRoaming);
9985     }
9986 
9987     /**
9988      * Set roaming state of the current network, for GSM purposes.
9989      * @param phoneId which phone you want to set
9990      * @param isRoaming is network in romaing state or not
9991      * @hide
9992      */
9993     @UnsupportedAppUsage
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)9994     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
9995         if (SubscriptionManager.isValidPhoneId(phoneId)) {
9996             List<Boolean> newList = updateTelephonyProperty(
9997                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
9998             TelephonyProperties.operator_is_roaming(newList);
9999         }
10000     }
10001 
10002     /**
10003      * Set the network type currently in use on the device for data transmission.
10004      *
10005      * If this object has been created with {@link #createForSubscriptionId}, applies to the
10006      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
10007      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10008      * @param type the network type currently in use on the device for data transmission
10009      * @hide
10010      */
setDataNetworkType(int type)10011     public void setDataNetworkType(int type) {
10012         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
10013         setDataNetworkTypeForPhone(phoneId, type);
10014     }
10015 
10016     /**
10017      * Set the network type currently in use on the device for data transmission.
10018      * @param phoneId which phone you want to set
10019      * @param type the network type currently in use on the device for data transmission
10020      * @hide
10021      */
10022     @UnsupportedAppUsage
setDataNetworkTypeForPhone(int phoneId, int type)10023     public void setDataNetworkTypeForPhone(int phoneId, int type) {
10024         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10025             List<String> newList = updateTelephonyProperty(
10026                     TelephonyProperties.data_network_type(), phoneId,
10027                     ServiceState.rilRadioTechnologyToString(type));
10028             TelephonyProperties.data_network_type(newList);
10029         }
10030     }
10031 
10032     /**
10033      * Returns the subscription ID for the given phone account.
10034      * @hide
10035      */
10036     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)10037     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
10038         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
10039         try {
10040             ITelephony service = getITelephony();
10041             if (service != null) {
10042                 retval = service.getSubIdForPhoneAccount(phoneAccount);
10043             }
10044         } catch (RemoteException e) {
10045         }
10046 
10047         return retval;
10048     }
10049 
10050     /**
10051      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
10052      *
10053      * @param subscriptionId The subscription Id to check.
10054      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
10055      * there is no associated {@link PhoneAccountHandle}.
10056      * @hide
10057      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)10058     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
10059         PhoneAccountHandle returnValue = null;
10060         try {
10061             ITelephony service = getITelephony();
10062             if (service != null) {
10063                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
10064             }
10065         } catch (RemoteException e) {
10066         }
10067 
10068         return returnValue;
10069     }
10070 
10071     /**
10072      * Returns the subscription ID for the given phone account handle.
10073      *
10074      * @param phoneAccountHandle the phone account handle for outgoing calls
10075      * @return subscription ID for the given phone account handle; or
10076      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
10077      *         if not available; or throw a SecurityException if the caller doesn't have the
10078      *         permission.
10079      */
10080     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)10081     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
10082         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
10083         try {
10084             ITelephony service = getITelephony();
10085             if (service != null) {
10086                 retval = service.getSubIdForPhoneAccountHandle(
10087                         phoneAccountHandle, mContext.getOpPackageName(), null);
10088             }
10089         } catch (RemoteException ex) {
10090             Log.e(TAG, "getSubscriptionId RemoteException", ex);
10091             ex.rethrowAsRuntimeException();
10092         }
10093         return retval;
10094     }
10095 
10096     /**
10097      * Resets telephony manager settings back to factory defaults.
10098      *
10099      * @hide
10100      */
factoryReset(int subId)10101     public void factoryReset(int subId) {
10102         try {
10103             Log.d(TAG, "factoryReset: subId=" + subId);
10104             ITelephony telephony = getITelephony();
10105             if (telephony != null) {
10106                 telephony.factoryReset(subId);
10107             }
10108         } catch (RemoteException e) {
10109         }
10110     }
10111 
10112 
10113     /**
10114      * Resets Telephony and IMS settings back to factory defaults only for the subscription
10115      * associated with this instance.
10116      * @see #createForSubscriptionId(int)
10117      * @hide
10118      */
10119     @SystemApi
10120     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
resetSettings()10121     public void resetSettings() {
10122         try {
10123             Log.d(TAG, "resetSettings: subId=" + getSubId());
10124             ITelephony telephony = getITelephony();
10125             if (telephony != null) {
10126                 telephony.factoryReset(getSubId());
10127             }
10128         } catch (RemoteException e) {
10129         }
10130     }
10131 
10132 
10133     /**
10134      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
10135      * no locale could be derived from subscriptions.
10136      *
10137      * <p>Requires Permission:
10138      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
10139      *
10140      * @see Locale#toLanguageTag()
10141      *
10142      * @hide
10143      */
10144     @SystemApi
10145     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimLocale()10146     @Nullable public Locale getSimLocale() {
10147         try {
10148             final ITelephony telephony = getITelephony();
10149             if (telephony != null) {
10150                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
10151                 if (!TextUtils.isEmpty(languageTag)) {
10152                     return Locale.forLanguageTag(languageTag);
10153                 }
10154             }
10155         } catch (RemoteException ex) {
10156         }
10157         return null;
10158     }
10159 
10160     /**
10161      * TODO delete after SuW migrates to new API.
10162      * @hide
10163      */
getLocaleFromDefaultSim()10164     public String getLocaleFromDefaultSim() {
10165         try {
10166             final ITelephony telephony = getITelephony();
10167             if (telephony != null) {
10168                 return telephony.getSimLocaleForSubscriber(getSubId());
10169             }
10170         } catch (RemoteException ex) {
10171         }
10172         return null;
10173     }
10174 
10175 
10176     /**
10177      * Requests the modem activity info. The recipient will place the result
10178      * in `result`.
10179      * @param result The object on which the recipient will send the resulting
10180      * {@link android.telephony.ModemActivityInfo} object with key of
10181      * {@link #MODEM_ACTIVITY_RESULT_KEY}.
10182      * @hide
10183      */
requestModemActivityInfo(@onNull ResultReceiver result)10184     public void requestModemActivityInfo(@NonNull ResultReceiver result) {
10185         try {
10186             ITelephony service = getITelephony();
10187             if (service != null) {
10188                 service.requestModemActivityInfo(result);
10189                 return;
10190             }
10191         } catch (RemoteException e) {
10192             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
10193         }
10194         result.send(0, null);
10195     }
10196 
10197     /**
10198      * Returns the current {@link ServiceState} information.
10199      *
10200      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10201      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10202      *
10203      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
10204      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
10205      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
10206      */
10207     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
10208     @RequiresPermission(allOf = {
10209             Manifest.permission.READ_PHONE_STATE,
10210             Manifest.permission.ACCESS_COARSE_LOCATION
10211     })
getServiceState()10212     public ServiceState getServiceState() {
10213         return getServiceStateForSubscriber(getSubId());
10214     }
10215 
10216     /**
10217      * Returns the service state information on specified subscription. Callers require
10218      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
10219      * @hide
10220      */
10221     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)10222     public ServiceState getServiceStateForSubscriber(int subId) {
10223         try {
10224             ITelephony service = getITelephony();
10225             if (service != null) {
10226                 return service.getServiceStateForSubscriber(subId, getOpPackageName(),
10227                         getFeatureId());
10228             }
10229         } catch (RemoteException e) {
10230             Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
10231         } catch (NullPointerException e) {
10232             AnomalyReporter.reportAnomaly(
10233                     UUID.fromString("a3ab0b9d-f2aa-4baf-911d-7096c0d4645a"),
10234                     "getServiceStateForSubscriber " + subId + " NPE");
10235         }
10236         return null;
10237     }
10238 
10239     /**
10240      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
10241      *
10242      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
10243      * voicemail ringtone.
10244      * @return The URI for the ringtone to play when receiving a voicemail from a specific
10245      * PhoneAccount.
10246      */
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)10247     public Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
10248         try {
10249             ITelephony service = getITelephony();
10250             if (service != null) {
10251                 return service.getVoicemailRingtoneUri(accountHandle);
10252             }
10253         } catch (RemoteException e) {
10254             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
10255         }
10256         return null;
10257     }
10258 
10259     /**
10260      * Sets the per-account voicemail ringtone.
10261      *
10262      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
10263      * {@link #hasCarrierPrivileges}, or has permission
10264      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10265      *
10266      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
10267      * voicemail ringtone.
10268      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
10269      * PhoneAccount.
10270      *
10271      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
10272      * instead.
10273      */
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)10274     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
10275         try {
10276             ITelephony service = getITelephony();
10277             if (service != null) {
10278                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
10279             }
10280         } catch (RemoteException e) {
10281             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
10282         }
10283     }
10284 
10285     /**
10286      * Returns whether vibration is set for voicemail notification in Phone settings.
10287      *
10288      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
10289      * voicemail vibration setting.
10290      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
10291      */
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)10292     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
10293         try {
10294             ITelephony service = getITelephony();
10295             if (service != null) {
10296                 return service.isVoicemailVibrationEnabled(accountHandle);
10297             }
10298         } catch (RemoteException e) {
10299             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
10300         }
10301         return false;
10302     }
10303 
10304     /**
10305      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
10306      *
10307      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
10308      * {@link #hasCarrierPrivileges}, or has permission
10309      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10310      *
10311      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
10312      * voicemail vibration setting.
10313      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
10314      * specific PhoneAccount.
10315      *
10316      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
10317      * instead.
10318      */
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)10319     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
10320             boolean enabled) {
10321         try {
10322             ITelephony service = getITelephony();
10323             if (service != null) {
10324                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
10325                         enabled);
10326             }
10327         } catch (RemoteException e) {
10328             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
10329         }
10330     }
10331 
10332     /**
10333      * Returns carrier id of the current subscription.
10334      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
10335      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
10336      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
10337      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10338      *
10339      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
10340      * as an Android platform-wide identifier for carriers.
10341      *
10342      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
10343      * subscription is unavailable or the carrier cannot be identified.
10344      */
getSimCarrierId()10345     public int getSimCarrierId() {
10346         try {
10347             ITelephony service = getITelephony();
10348             if (service != null) {
10349                 return service.getSubscriptionCarrierId(getSubId());
10350             }
10351         } catch (RemoteException ex) {
10352             // This could happen if binder process crashes.
10353         }
10354         return UNKNOWN_CARRIER_ID;
10355     }
10356 
10357     /**
10358      * Returns carrier id name of the current subscription.
10359      * <p>Carrier id name is a user-facing name of carrier id returned by
10360      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
10361      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
10362      * should have a single carrier name. Carrier name is not a canonical identity,
10363      * use {@link #getSimCarrierId()} instead.
10364      * <p>The returned carrier name is unlocalized.
10365      *
10366      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
10367      * unavailable or the carrier cannot be identified.
10368      */
getSimCarrierIdName()10369     public @Nullable CharSequence getSimCarrierIdName() {
10370         try {
10371             ITelephony service = getITelephony();
10372             if (service != null) {
10373                 return service.getSubscriptionCarrierName(getSubId());
10374             }
10375         } catch (RemoteException ex) {
10376             // This could happen if binder process crashes.
10377         }
10378         return null;
10379     }
10380 
10381     /**
10382      * Returns fine-grained carrier ID of the current subscription.
10383      *
10384      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
10385      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
10386      * are used to make up the actual carrier service may have different carrier configurations.
10387      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
10388      * different carrier configuration for different service offering such as a prepaid plan.
10389      *
10390      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
10391      * about the carrier itself should use the regular carrier ID returned by
10392      * {@link #getSimCarrierId()}.
10393      *
10394      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
10395      * subscription while carrier ID remains the same.
10396      *
10397      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
10398      * <p>Specific carrier ids are defined in the same way as carrier id
10399      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10400      * except each with a "parent" id linking to its top-level carrier id.
10401      *
10402      * @return Returns fine-grained carrier id of the current subscription.
10403      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
10404      * be identified.
10405      */
getSimSpecificCarrierId()10406     public int getSimSpecificCarrierId() {
10407         try {
10408             ITelephony service = getITelephony();
10409             if (service != null) {
10410                 return service.getSubscriptionSpecificCarrierId(getSubId());
10411             }
10412         } catch (RemoteException ex) {
10413             // This could happen if binder process crashes.
10414         }
10415         return UNKNOWN_CARRIER_ID;
10416     }
10417 
10418     /**
10419      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
10420      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
10421      *
10422      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
10423      * about the carrier itself should use the regular carrier ID returned by
10424      * {@link #getSimCarrierIdName()}.
10425      *
10426      * <p>The returned name is unlocalized.
10427      *
10428      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
10429      * subscription is unavailable or the carrier cannot be identified.
10430      */
getSimSpecificCarrierIdName()10431     public @Nullable CharSequence getSimSpecificCarrierIdName() {
10432         try {
10433             ITelephony service = getITelephony();
10434             if (service != null) {
10435                 return service.getSubscriptionSpecificCarrierName(getSubId());
10436             }
10437         } catch (RemoteException ex) {
10438             // This could happen if binder process crashes.
10439         }
10440         return null;
10441     }
10442 
10443     /**
10444      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
10445      * This is used for fallback when configurations/logic for exact carrier id
10446      * {@link #getSimCarrierId()} are not found.
10447      *
10448      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10449      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
10450      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
10451      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
10452      * take the update with the new id, it might be helpful to always fallback by using carrier
10453      * id based on MCCMNC if there is no match.
10454      *
10455      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
10456      * subscription is unavailable or the carrier cannot be identified.
10457      */
getCarrierIdFromSimMccMnc()10458     public int getCarrierIdFromSimMccMnc() {
10459         try {
10460             ITelephony service = getITelephony();
10461             if (service != null) {
10462                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
10463             }
10464         } catch (RemoteException ex) {
10465             // This could happen if binder process crashes.
10466         }
10467         return UNKNOWN_CARRIER_ID;
10468     }
10469 
10470      /**
10471       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
10472       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
10473       * are not found.
10474       *
10475       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
10476       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
10477       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
10478       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
10479       * take the update with the new id, it might be helpful to always fallback by using carrier
10480       * id based on MCCMNC if there is no match.
10481       *
10482       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
10483       * subscription is unavailable or the carrier cannot be identified.
10484       * @hide
10485       */
10486      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)10487      public int getCarrierIdFromMccMnc(String mccmnc) {
10488         try {
10489             ITelephony service = getITelephony();
10490             if (service != null) {
10491                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
10492             }
10493         } catch (RemoteException ex) {
10494             // This could happen if binder process crashes.
10495         }
10496         return UNKNOWN_CARRIER_ID;
10497     }
10498 
10499     /**
10500      * Return a list of certs in hex string from loaded carrier privileges access rules.
10501      *
10502      * @return a list of certificate in hex string. return {@code null} if there is no certs
10503      * or privilege rules are not loaded yet.
10504      *
10505      * <p>Requires Permission:
10506      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
10507      * @hide
10508      */
10509     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCertsFromCarrierPrivilegeAccessRules()10510     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
10511         try {
10512             ITelephony service = getITelephony();
10513             if (service != null) {
10514                 return service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
10515             }
10516         } catch (RemoteException ex) {
10517             // This could happen if binder process crashes.
10518         }
10519         return null;
10520     }
10521 
10522     /**
10523      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
10524      * All uicc applications are uniquely identified by application ID, represented by the hex
10525      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
10526      * <p>Requires Permission:
10527      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
10528      *
10529      * @param appType the uicc app type.
10530      * @return Application ID for specified app type or {@code null} if no uicc or error.
10531      * @hide
10532      */
10533     @Nullable
10534     @SystemApi
10535     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAidForAppType(@iccAppType int appType)10536     public String getAidForAppType(@UiccAppType int appType) {
10537         return getAidForAppType(getSubId(), appType);
10538     }
10539 
10540     /**
10541      * same as {@link #getAidForAppType(int)}
10542      * @hide
10543      */
getAidForAppType(int subId, int appType)10544     public String getAidForAppType(int subId, int appType) {
10545         try {
10546             ITelephony service = getITelephony();
10547             if (service != null) {
10548                 return service.getAidForAppType(subId, appType);
10549             }
10550         } catch (RemoteException e) {
10551             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
10552         }
10553         return null;
10554     }
10555 
10556     /**
10557      * Return the Electronic Serial Number.
10558      *
10559      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10560      *
10561      * @return ESN or null if error.
10562      * @hide
10563      */
getEsn()10564     public String getEsn() {
10565         return getEsn(getSubId());
10566     }
10567 
10568     /**
10569      * Return the Electronic Serial Number.
10570      *
10571      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10572      *
10573      * @param subId the subscription ID that this request applies to.
10574      * @return ESN or null if error.
10575      * @hide
10576      */
getEsn(int subId)10577     public String getEsn(int subId) {
10578         try {
10579             ITelephony service = getITelephony();
10580             if (service != null) {
10581                 return service.getEsn(subId);
10582             }
10583         } catch (RemoteException e) {
10584             Log.e(TAG, "Error calling ITelephony#getEsn", e);
10585         }
10586         return null;
10587     }
10588 
10589     /**
10590      * Return the Preferred Roaming List Version
10591      *
10592      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10593      *
10594      * @return PRLVersion or null if error.
10595      * @hide
10596      */
10597     @SystemApi
getCdmaPrlVersion()10598     public String getCdmaPrlVersion() {
10599         return getCdmaPrlVersion(getSubId());
10600     }
10601 
10602     /**
10603      * Return the Preferred Roaming List Version
10604      *
10605      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
10606      *
10607      * @param subId the subscription ID that this request applies to.
10608      * @return PRLVersion or null if error.
10609      * @hide
10610      */
getCdmaPrlVersion(int subId)10611     public String getCdmaPrlVersion(int subId) {
10612         try {
10613             ITelephony service = getITelephony();
10614             if (service != null) {
10615                 return service.getCdmaPrlVersion(subId);
10616             }
10617         } catch (RemoteException e) {
10618             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
10619         }
10620         return null;
10621     }
10622 
10623     /**
10624      * Get snapshot of Telephony histograms
10625      * @return List of Telephony histograms
10626      * Requires Permission:
10627      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10628      * Or the calling app has carrier privileges.
10629      * @hide
10630      */
10631     @SystemApi
10632     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()10633     public List<TelephonyHistogram> getTelephonyHistograms() {
10634         try {
10635             ITelephony service = getITelephony();
10636             if (service != null) {
10637                 return service.getTelephonyHistograms();
10638             }
10639         } catch (RemoteException e) {
10640             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
10641         }
10642         return null;
10643     }
10644 
10645     /**
10646      * Set the allowed carrier list for slotIndex
10647      * Require system privileges. In the future we may add this to carrier APIs.
10648      *
10649      * <p>Requires Permission:
10650      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
10651      *
10652      * <p>This method works only on devices with {@link
10653      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
10654      *
10655      * @deprecated use setCarrierRestrictionRules instead
10656      *
10657      * @return The number of carriers set successfully. Should be length of
10658      * carrierList on success; -1 if carrierList null or on error.
10659      * @hide
10660      */
10661     @SystemApi
10662     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)10663     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
10664         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
10665             return -1;
10666         }
10667         // Execute the method setCarrierRestrictionRules with an empty excluded list and
10668         // indicating priority for the allowed list.
10669         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
10670                 .setAllowedCarriers(carriers)
10671                 .setDefaultCarrierRestriction(
10672                     CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
10673                 .build();
10674 
10675         int result = setCarrierRestrictionRules(carrierRestrictionRules);
10676 
10677         // Convert result into int, as required by this method.
10678         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
10679             return carriers.size();
10680         } else {
10681             return -1;
10682         }
10683     }
10684 
10685     /**
10686      * The carrier restrictions were successfully set.
10687      * @hide
10688      */
10689     @SystemApi
10690     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
10691 
10692     /**
10693      * The carrier restrictions were not set due to lack of support in the modem. This can happen
10694      * if the modem does not support setting the carrier restrictions or if the configuration
10695      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
10696      * @hide
10697      */
10698     @SystemApi
10699     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
10700 
10701     /**
10702      * The setting of carrier restrictions failed.
10703      * @hide
10704      */
10705     @SystemApi
10706     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
10707 
10708     /** @hide */
10709     @Retention(RetentionPolicy.SOURCE)
10710     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
10711             value = {
10712                     SET_CARRIER_RESTRICTION_SUCCESS,
10713                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
10714                     SET_CARRIER_RESTRICTION_ERROR
10715             })
10716     public @interface SetCarrierRestrictionResult {}
10717 
10718     /**
10719      * Set the allowed carrier list and the excluded carrier list indicating the priority between
10720      * the two lists.
10721      * Requires system privileges.
10722      *
10723      * <p>Requires Permission:
10724      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
10725      *
10726      * <p>This method works only on devices with {@link
10727      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
10728      *
10729      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
10730      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
10731      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
10732      * @hide
10733      */
10734     @SystemApi
10735     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10736     @SetCarrierRestrictionResult
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)10737     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
10738         try {
10739             ITelephony service = getITelephony();
10740             if (service != null) {
10741                 return service.setAllowedCarriers(rules);
10742             }
10743         } catch (RemoteException e) {
10744             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
10745         } catch (NullPointerException e) {
10746             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
10747         }
10748         return SET_CARRIER_RESTRICTION_ERROR;
10749     }
10750 
10751     /**
10752      * Get the allowed carrier list for slotIndex.
10753      * Requires system privileges.
10754      *
10755      * <p>This method returns valid data on devices with {@link
10756      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
10757      *
10758      * @deprecated Apps should use {@link getCarriersRestrictionRules} to retrieve the list of
10759      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
10760      * list is empty. This API could return an empty list, even if some restrictions are present.
10761      *
10762      * @return List of {@link android.telephony.CarrierIdentifier}; empty list
10763      * means all carriers are allowed.
10764      * @hide
10765      */
10766     @Deprecated
10767     @SystemApi
10768     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedCarriers(int slotIndex)10769     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
10770         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
10771             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
10772             if (carrierRestrictionRule != null) {
10773                 return carrierRestrictionRule.getAllowedCarriers();
10774             }
10775         }
10776         return new ArrayList<CarrierIdentifier>(0);
10777     }
10778 
10779     /**
10780      * Get the allowed carrier list and the excluded carrier list indicating the priority between
10781      * the two lists.
10782      * Require system privileges. In the future we may add this to carrier APIs.
10783      *
10784      * <p>This method returns valid data on devices with {@link
10785      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
10786      *
10787      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
10788      * excluded carrier list with the priority between the two lists. Returns {@code null}
10789      * in case of error.
10790      * @hide
10791      */
10792     @SystemApi
10793     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10794     @Nullable
getCarrierRestrictionRules()10795     public CarrierRestrictionRules getCarrierRestrictionRules() {
10796         try {
10797             ITelephony service = getITelephony();
10798             if (service != null) {
10799                 return service.getAllowedCarriers();
10800             }
10801         } catch (RemoteException e) {
10802             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
10803         } catch (NullPointerException e) {
10804             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
10805         }
10806         return null;
10807     }
10808 
10809     /**
10810      * Used to enable or disable carrier data by the system based on carrier signalling or
10811      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
10812      * user settings, carrier data on/off won't affect user settings but will bypass the
10813      * settings and turns off data internally if set to {@code false}.
10814      *
10815      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10816      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10817      *
10818      * <p>Requires Permission:
10819      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10820      *
10821      * @param enabled control enable or disable carrier data.
10822      * @see #resetAllCarrierActions()
10823      * @hide
10824      */
10825     @SystemApi
10826     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCarrierDataEnabled(boolean enabled)10827     public void setCarrierDataEnabled(boolean enabled) {
10828         try {
10829             ITelephony service = getITelephony();
10830             if (service != null) {
10831                 service.carrierActionSetMeteredApnsEnabled(
10832                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
10833             }
10834         } catch (RemoteException e) {
10835             Log.e(TAG, "Error calling ITelephony#setCarrierDataEnabled", e);
10836         }
10837     }
10838 
10839     /**
10840      * Carrier action to enable or disable the radio.
10841      *
10842      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10843      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10844      *
10845      * <p>Requires Permission:
10846      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10847      *
10848      * @param enabled control enable or disable radio.
10849      * @see #resetAllCarrierActions()
10850      * @hide
10851      */
10852     @SystemApi
10853     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioEnabled(boolean enabled)10854     public void setRadioEnabled(boolean enabled) {
10855         try {
10856             ITelephony service = getITelephony();
10857             if (service != null) {
10858                 service.carrierActionSetRadioEnabled(
10859                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
10860             }
10861         } catch (RemoteException e) {
10862             Log.e(TAG, "Error calling ITelephony#carrierActionSetRadioEnabled", e);
10863         }
10864     }
10865 
10866     /**
10867      * Carrier action to start or stop reporting default network available events.
10868      *
10869      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10870      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10871      *
10872      * <p>Requires Permission:
10873      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10874      *
10875      * @param report control start/stop reporting network status.
10876      * @see #resetAllCarrierActions()
10877      * @hide
10878      */
10879     @SystemApi
10880     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
reportDefaultNetworkStatus(boolean report)10881     public void reportDefaultNetworkStatus(boolean report) {
10882         try {
10883             ITelephony service = getITelephony();
10884             if (service != null) {
10885                 service.carrierActionReportDefaultNetworkStatus(
10886                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
10887             }
10888         } catch (RemoteException e) {
10889             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
10890         }
10891     }
10892 
10893     /**
10894      * Reset all carrier actions previously set by {@link #setRadioEnabled},
10895      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
10896      *
10897      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10898      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10899      *
10900      * <p>Requires Permission:
10901      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
10902      * @hide
10903      */
10904     @SystemApi
10905     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetAllCarrierActions()10906     public void resetAllCarrierActions() {
10907         try {
10908             ITelephony service = getITelephony();
10909             if (service != null) {
10910                 service.carrierActionResetAll(
10911                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
10912             }
10913         } catch (RemoteException e) {
10914             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
10915         }
10916     }
10917 
10918     /**
10919      * Policy control of data connection. Usually used when data limit is passed.
10920      * @param enabled True if enabling the data, otherwise disabling.
10921      * @param subId sub id
10922      * @hide
10923      */
setPolicyDataEnabled(boolean enabled, int subId)10924     public void setPolicyDataEnabled(boolean enabled, int subId) {
10925         try {
10926             ITelephony service = getITelephony();
10927             if (service != null) {
10928                 service.setPolicyDataEnabled(enabled, subId);
10929             }
10930         } catch (RemoteException e) {
10931             Log.e(TAG, "Error calling ITelephony#setPolicyDataEnabled", e);
10932         }
10933     }
10934 
10935     /**
10936      * Get Client request stats which will contain statistical information
10937      * on each request made by client.
10938      * Callers require either READ_PRIVILEGED_PHONE_STATE or
10939      * READ_PHONE_STATE to retrieve the information.
10940      * @param subId sub id
10941      * @return List of Client Request Stats
10942      * @hide
10943      */
getClientRequestStats(int subId)10944     public List<ClientRequestStats> getClientRequestStats(int subId) {
10945         try {
10946             ITelephony service = getITelephony();
10947             if (service != null) {
10948                 return service.getClientRequestStats(getOpPackageName(), getFeatureId(), subId);
10949             }
10950         } catch (RemoteException e) {
10951             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
10952         }
10953 
10954         return null;
10955     }
10956 
10957     /**
10958      * Checks if phone is in emergency callback mode.
10959      *
10960      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10961      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10962      *
10963      * @return true if phone is in emergency callback mode.
10964      * @hide
10965      */
10966     @SystemApi
10967     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyCallbackMode()10968     public boolean getEmergencyCallbackMode() {
10969         return getEmergencyCallbackMode(getSubId());
10970     }
10971 
10972     /**
10973      * Check if phone is in emergency callback mode
10974      * @return true if phone is in emergency callback mode
10975      * @param subId the subscription ID that this action applies to.
10976      * @hide
10977      */
getEmergencyCallbackMode(int subId)10978     public boolean getEmergencyCallbackMode(int subId) {
10979         try {
10980             ITelephony telephony = getITelephony();
10981             if (telephony == null) {
10982                 return false;
10983             }
10984             return telephony.getEmergencyCallbackMode(subId);
10985         } catch (RemoteException e) {
10986             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
10987         }
10988         return false;
10989     }
10990 
10991     /**
10992      * Checks if manual network selection is allowed.
10993      *
10994      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10995      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
10996      *
10997      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
10998      *
10999      * @hide
11000      */
11001     @SystemApi
11002     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isManualNetworkSelectionAllowed()11003     public boolean isManualNetworkSelectionAllowed() {
11004         try {
11005             ITelephony telephony = getITelephony();
11006             if (telephony != null) {
11007                 return telephony.isManualNetworkSelectionAllowed(getSubId());
11008             }
11009         } catch (RemoteException e) {
11010             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
11011         }
11012         return true;
11013     }
11014 
11015     /**
11016      * Enable or disable signal strength changes from radio will always be reported in any
11017      * condition (e.g. screen is off). This is only allowed for System caller.
11018      *
11019      * @param isEnabled {@code true} for enabling; {@code false} for disabling.
11020      * @hide
11021      */
11022     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysReportSignalStrength(boolean isEnabled)11023     public void setAlwaysReportSignalStrength(boolean isEnabled) {
11024         try {
11025             ITelephony telephony = getITelephony();
11026             if (telephony != null) {
11027                 telephony.setAlwaysReportSignalStrength(getSubId(), isEnabled);
11028             }
11029         } catch (RemoteException ex) {
11030             Log.e(TAG, "setAlwaysReportSignalStrength RemoteException", ex);
11031             ex.rethrowAsRuntimeException();
11032         }
11033     }
11034 
11035     /**
11036      * Get the most recently available signal strength information.
11037      *
11038      * Get the most recent SignalStrength information reported by the modem. Due
11039      * to power saving this information may not always be current.
11040      * @return the most recent cached signal strength info from the modem
11041      */
11042     @Nullable
getSignalStrength()11043     public SignalStrength getSignalStrength() {
11044         try {
11045             ITelephony service = getITelephony();
11046             if (service != null) {
11047                 return service.getSignalStrength(getSubId());
11048             }
11049         } catch (RemoteException e) {
11050             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
11051         }
11052         return null;
11053     }
11054 
11055     /**
11056      * Checks whether cellular data connection is allowed in the device.
11057      *
11058      * <p>Whether cellular data connection is allowed considers all factors below:
11059      * <UL>
11060      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
11061      *   <LI>Carrier allows data to be on.</LI>
11062      *   <LI>Network policy.</LI>
11063      *   <LI>And possibly others.</LI>
11064      * </UL>
11065      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
11066      * @hide
11067      */
11068     @SystemApi
11069     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataConnectionAllowed()11070     public boolean isDataConnectionAllowed() {
11071         boolean retVal = false;
11072         try {
11073             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
11074             ITelephony telephony = getITelephony();
11075             if (telephony != null)
11076                 retVal = telephony.isDataEnabled(subId);
11077         } catch (RemoteException e) {
11078             Log.e(TAG, "Error isDataConnectionAllowed", e);
11079         }
11080         return retVal;
11081     }
11082 
11083     /**
11084      * @return true if the current device is "data capable" over a radio on the device.
11085      * <p>
11086      * "Data capable" means that this device supports packet-switched
11087      * data connections over the telephony network.
11088      * <p>
11089      * Note: the meaning of this flag is subtly different from the
11090      * PackageManager.FEATURE_TELEPHONY system feature, which is available
11091      * on any device with a telephony radio, even if the device is
11092      * voice-only.
11093      *
11094      * @hide
11095      */
isDataCapable()11096     public boolean isDataCapable() {
11097         if (mContext == null) return true;
11098         return mContext.getResources().getBoolean(
11099                 com.android.internal.R.bool.config_mobile_data_capable);
11100     }
11101 
11102     /**
11103      * In this mode, modem will not send specified indications when screen is off.
11104      * @hide
11105      */
11106     public static final int INDICATION_UPDATE_MODE_NORMAL                   = 1;
11107 
11108     /**
11109      * In this mode, modem will still send specified indications when screen is off.
11110      * @hide
11111      */
11112     public static final int INDICATION_UPDATE_MODE_IGNORE_SCREEN_OFF        = 2;
11113 
11114     /**
11115      * The indication for signal strength update.
11116      * @hide
11117      */
11118     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
11119 
11120     /**
11121      * The indication for full network state update.
11122      * @hide
11123      */
11124     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
11125 
11126     /**
11127      * The indication for data call dormancy changed update.
11128      * @hide
11129      */
11130     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
11131 
11132     /**
11133      * The indication for link capacity estimate update.
11134      * @hide
11135      */
11136     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
11137 
11138     /**
11139      * The indication for physical channel config update.
11140      * @hide
11141      */
11142     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
11143 
11144     /**
11145      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
11146      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
11147      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
11148      *
11149      * <p>Requires Permission:
11150      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11151      *
11152      *
11153      * @deprecated
11154      * @hide
11155      */
11156     @Deprecated
11157     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)11158     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
11159             String gid2, String plmn, String spn) {
11160         try {
11161             ITelephony telephony = getITelephony();
11162             if (telephony != null) {
11163                 telephony.setCarrierTestOverride(
11164                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
11165                         null, null);
11166             }
11167         } catch (RemoteException ex) {
11168             // This could happen if binder process crashes.
11169         }
11170     }
11171 
11172     /**
11173      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
11174      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
11175      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
11176      * a test SIM with a call box.
11177      *
11178      * <p>Requires Permission:
11179      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11180      *
11181      * @hide
11182      */
11183     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)11184     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
11185                                        String gid2, String plmn, String spn,
11186                                        String carrierPriviledgeRules, String apn) {
11187         try {
11188             ITelephony telephony = getITelephony();
11189             if (telephony != null) {
11190                 telephony.setCarrierTestOverride(
11191                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
11192                         carrierPriviledgeRules, apn);
11193             }
11194         } catch (RemoteException ex) {
11195             // This could happen if binder process crashes.
11196         }
11197     }
11198 
11199     /**
11200      * A test API to return installed carrier id list version
11201      *
11202      * <p>Requires Permission:
11203      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11204      *
11205      * @hide
11206      */
11207     @UnsupportedAppUsage
11208     @TestApi
getCarrierIdListVersion()11209     public int getCarrierIdListVersion() {
11210         try {
11211             ITelephony telephony = getITelephony();
11212             if (telephony != null) {
11213                 return telephony.getCarrierIdListVersion(getSubId());
11214             }
11215         } catch (RemoteException ex) {
11216             // This could happen if binder process crashes.
11217         }
11218         return UNKNOWN_CARRIER_ID_LIST_VERSION;
11219     }
11220 
11221     /**
11222      * How many modems can have simultaneous data connections.
11223      * @hide
11224      */
11225     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()11226     public int getNumberOfModemsWithSimultaneousDataConnections() {
11227         try {
11228             ITelephony telephony = getITelephony();
11229             if (telephony != null) {
11230                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
11231                         getSubId(), getOpPackageName(), getFeatureId());
11232             }
11233         } catch (RemoteException ex) {
11234             // This could happen if binder process crashes.
11235         }
11236         return 0;
11237     }
11238 
11239     /**
11240      * Enable or disable OpportunisticNetworkService.
11241      *
11242      * This method should be called to enable or disable
11243      * OpportunisticNetwork service on the device.
11244      *
11245      * <p>
11246      * Requires Permission:
11247      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11248      *
11249      * @param enable enable(True) or disable(False)
11250      * @return returns true if successfully set.
11251      * @hide
11252      */
11253     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11254     @SystemApi
setOpportunisticNetworkState(boolean enable)11255     public boolean setOpportunisticNetworkState(boolean enable) {
11256         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11257         boolean ret = false;
11258         try {
11259             IOns iOpportunisticNetworkService = getIOns();
11260             if (iOpportunisticNetworkService != null) {
11261                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
11262             }
11263         } catch (RemoteException ex) {
11264             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
11265         }
11266 
11267         return ret;
11268     }
11269 
11270     /**
11271      * is OpportunisticNetworkService enabled
11272      *
11273      * This method should be called to determine if the OpportunisticNetworkService is
11274      * enabled
11275      *
11276      * <p>
11277      * Requires Permission:
11278      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11279      * @hide
11280      */
11281     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11282     @SystemApi
isOpportunisticNetworkEnabled()11283     public boolean isOpportunisticNetworkEnabled() {
11284         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11285         boolean isEnabled = false;
11286 
11287         try {
11288             IOns iOpportunisticNetworkService = getIOns();
11289             if (iOpportunisticNetworkService != null) {
11290                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
11291             }
11292         } catch (RemoteException ex) {
11293             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
11294         }
11295 
11296         return isEnabled;
11297     }
11298 
11299     /** @hide */
11300     @Retention(RetentionPolicy.SOURCE)
11301     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
11302             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
11303                     NETWORK_TYPE_BITMASK_GSM,
11304                     NETWORK_TYPE_BITMASK_GPRS,
11305                     NETWORK_TYPE_BITMASK_EDGE,
11306                     NETWORK_TYPE_BITMASK_CDMA,
11307                     NETWORK_TYPE_BITMASK_1xRTT,
11308                     NETWORK_TYPE_BITMASK_EVDO_0,
11309                     NETWORK_TYPE_BITMASK_EVDO_A,
11310                     NETWORK_TYPE_BITMASK_EVDO_B,
11311                     NETWORK_TYPE_BITMASK_EHRPD,
11312                     NETWORK_TYPE_BITMASK_HSUPA,
11313                     NETWORK_TYPE_BITMASK_HSDPA,
11314                     NETWORK_TYPE_BITMASK_HSPA,
11315                     NETWORK_TYPE_BITMASK_HSPAP,
11316                     NETWORK_TYPE_BITMASK_UMTS,
11317                     NETWORK_TYPE_BITMASK_TD_SCDMA,
11318                     NETWORK_TYPE_BITMASK_LTE,
11319                     NETWORK_TYPE_BITMASK_LTE_CA,
11320                     NETWORK_TYPE_BITMASK_NR,
11321             })
11322     public @interface NetworkTypeBitMask {}
11323 
11324     // 2G
11325     /**
11326      * network type bitmask unknown.
11327      * @hide
11328      */
11329     @SystemApi
11330     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
11331     /**
11332      * network type bitmask indicating the support of radio tech GSM.
11333      * @hide
11334      */
11335     @SystemApi
11336     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
11337     /**
11338      * network type bitmask indicating the support of radio tech GPRS.
11339      * @hide
11340      */
11341     @SystemApi
11342     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
11343     /**
11344      * network type bitmask indicating the support of radio tech EDGE.
11345      * @hide
11346      */
11347     @SystemApi
11348     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
11349     /**
11350      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
11351      * @hide
11352      */
11353     @SystemApi
11354     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
11355     /**
11356      * network type bitmask indicating the support of radio tech 1xRTT.
11357      * @hide
11358      */
11359     @SystemApi
11360     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
11361     // 3G
11362     /**
11363      * network type bitmask indicating the support of radio tech EVDO 0.
11364      * @hide
11365      */
11366     @SystemApi
11367     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
11368     /**
11369      * network type bitmask indicating the support of radio tech EVDO A.
11370      * @hide
11371      */
11372     @SystemApi
11373     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
11374     /**
11375      * network type bitmask indicating the support of radio tech EVDO B.
11376      * @hide
11377      */
11378     @SystemApi
11379     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
11380     /**
11381      * network type bitmask indicating the support of radio tech EHRPD.
11382      * @hide
11383      */
11384     @SystemApi
11385     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
11386     /**
11387      * network type bitmask indicating the support of radio tech HSUPA.
11388      * @hide
11389      */
11390     @SystemApi
11391     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
11392     /**
11393      * network type bitmask indicating the support of radio tech HSDPA.
11394      * @hide
11395      */
11396     @SystemApi
11397     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
11398     /**
11399      * network type bitmask indicating the support of radio tech HSPA.
11400      * @hide
11401      */
11402     @SystemApi
11403     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
11404     /**
11405      * network type bitmask indicating the support of radio tech HSPAP.
11406      * @hide
11407      */
11408     @SystemApi
11409     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
11410     /**
11411      * network type bitmask indicating the support of radio tech UMTS.
11412      * @hide
11413      */
11414     @SystemApi
11415     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
11416     /**
11417      * network type bitmask indicating the support of radio tech TD_SCDMA.
11418      * @hide
11419      */
11420     @SystemApi
11421     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
11422     // 4G
11423     /**
11424      * network type bitmask indicating the support of radio tech LTE.
11425      * @hide
11426      */
11427     @SystemApi
11428     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
11429     /**
11430      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
11431      * @hide
11432      */
11433     @SystemApi
11434     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
11435 
11436     /**
11437      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
11438      * @hide
11439      */
11440     @SystemApi
11441     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
11442 
11443     /**
11444      * network type bitmask indicating the support of radio tech IWLAN.
11445      * @hide
11446      */
11447     @SystemApi
11448     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
11449 
11450     /** @hide */
11451     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
11452                 | NETWORK_TYPE_BITMASK_GPRS
11453                 | NETWORK_TYPE_BITMASK_EDGE
11454                 | NETWORK_TYPE_BITMASK_CDMA
11455                 | NETWORK_TYPE_BITMASK_1xRTT;
11456 
11457     /** @hide */
11458     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
11459             | NETWORK_TYPE_BITMASK_EVDO_A
11460             | NETWORK_TYPE_BITMASK_EVDO_B
11461             | NETWORK_TYPE_BITMASK_EHRPD
11462             | NETWORK_TYPE_BITMASK_HSUPA
11463             | NETWORK_TYPE_BITMASK_HSDPA
11464             | NETWORK_TYPE_BITMASK_HSPA
11465             | NETWORK_TYPE_BITMASK_HSPAP
11466             | NETWORK_TYPE_BITMASK_UMTS
11467             | NETWORK_TYPE_BITMASK_TD_SCDMA;
11468 
11469     /** @hide */
11470     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
11471             | NETWORK_TYPE_BITMASK_LTE_CA
11472             | NETWORK_TYPE_BITMASK_IWLAN;
11473 
11474     /** @hide */
11475     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
11476 
11477     /** @hide */
11478     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
11479             | NETWORK_TYPE_BITMASK_GPRS
11480             | NETWORK_TYPE_BITMASK_EDGE
11481             | NETWORK_TYPE_BITMASK_HSUPA
11482             | NETWORK_TYPE_BITMASK_HSDPA
11483             | NETWORK_TYPE_BITMASK_HSPA
11484             | NETWORK_TYPE_BITMASK_HSPAP
11485             | NETWORK_TYPE_BITMASK_UMTS
11486             | NETWORK_TYPE_BITMASK_TD_SCDMA
11487             | NETWORK_TYPE_BITMASK_LTE
11488             | NETWORK_TYPE_BITMASK_LTE_CA
11489             | NETWORK_TYPE_BITMASK_NR;
11490 
11491     /** @hide */
11492     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
11493             | NETWORK_TYPE_BITMASK_1xRTT
11494             | NETWORK_TYPE_BITMASK_EVDO_0
11495             | NETWORK_TYPE_BITMASK_EVDO_A
11496             | NETWORK_TYPE_BITMASK_EVDO_B
11497             | NETWORK_TYPE_BITMASK_EHRPD;
11498 
11499     /**
11500      * @return Modem supported radio access family bitmask
11501      *
11502      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
11503      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11504      * @hide
11505      */
11506     @SystemApi
11507     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSupportedRadioAccessFamily()11508     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
11509         try {
11510             ITelephony telephony = getITelephony();
11511             if (telephony != null) {
11512                 return (long) telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
11513             } else {
11514                 // This can happen when the ITelephony interface is not up yet.
11515                 return NETWORK_TYPE_BITMASK_UNKNOWN;
11516             }
11517         } catch (RemoteException ex) {
11518             // This shouldn't happen in the normal case
11519             return NETWORK_TYPE_BITMASK_UNKNOWN;
11520         } catch (NullPointerException ex) {
11521             // This could happen before phone restarts due to crashing
11522             return NETWORK_TYPE_BITMASK_UNKNOWN;
11523         }
11524     }
11525 
11526     /**
11527      * Indicates Emergency number database version is invalid.
11528      *
11529      * @hide
11530      */
11531     @TestApi
11532     @SystemApi
11533     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
11534 
11535     /**
11536      * Notify Telephony for OTA emergency number database installation complete.
11537      *
11538      * <p> Requires permission:
11539      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11540      *
11541      * @hide
11542      */
11543     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11544     @SystemApi
notifyOtaEmergencyNumberDbInstalled()11545     public void notifyOtaEmergencyNumberDbInstalled() {
11546         try {
11547             ITelephony telephony = getITelephony();
11548             if (telephony != null) {
11549                 telephony.notifyOtaEmergencyNumberDbInstalled();
11550             } else {
11551                 throw new IllegalStateException("telephony service is null.");
11552             }
11553         } catch (RemoteException ex) {
11554             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
11555             ex.rethrowAsRuntimeException();
11556         }
11557     }
11558 
11559     /**
11560      * Override the file path for OTA emergency number database in a file partition.
11561      *
11562      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
11563      *
11564      * <p> Requires permission:
11565      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
11566      *
11567      * @hide
11568      */
11569     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
11570     @SystemApi
11571     @TestApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)11572     public void updateOtaEmergencyNumberDbFilePath(
11573             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
11574         try {
11575             ITelephony telephony = getITelephony();
11576             if (telephony != null) {
11577                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
11578             } else {
11579                 throw new IllegalStateException("telephony service is null.");
11580             }
11581         } catch (RemoteException ex) {
11582             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
11583             ex.rethrowAsRuntimeException();
11584         }
11585     }
11586 
11587     /**
11588      * Reset the file path to default for OTA emergency number database in a file partition.
11589      *
11590      * <p> Requires permission:
11591      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
11592      *
11593      * @hide
11594      */
11595     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
11596     @SystemApi
11597     @TestApi
resetOtaEmergencyNumberDbFilePath()11598     public void resetOtaEmergencyNumberDbFilePath() {
11599         try {
11600             ITelephony telephony = getITelephony();
11601             if (telephony != null) {
11602                 telephony.resetOtaEmergencyNumberDbFilePath();
11603             } else {
11604                 throw new IllegalStateException("telephony service is null.");
11605             }
11606         } catch (RemoteException ex) {
11607             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
11608             ex.rethrowAsRuntimeException();
11609         }
11610     }
11611 
11612     /**
11613      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
11614      * available on the device.
11615      * <p>
11616      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
11617      *
11618      * @return {@code true} if emergency assistance is available, {@code false} otherwise
11619      *
11620      * @hide
11621      */
11622     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11623     @SystemApi
isEmergencyAssistanceEnabled()11624     public boolean isEmergencyAssistanceEnabled() {
11625         mContext.enforceCallingOrSelfPermission(
11626                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11627                 "isEmergencyAssistanceEnabled");
11628         return EMERGENCY_ASSISTANCE_ENABLED;
11629     }
11630 
11631     /**
11632      * Get the emergency number list based on current locale, sim, default, modem and network.
11633      *
11634      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
11635      * priority sources will be located at the smaller index; the priority order of sources are:
11636      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
11637      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
11638      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
11639      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
11640      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
11641      *
11642      * <p>The subscriptions which the returned list would be based on, are all the active
11643      * subscriptions, no matter which subscription could be used to create TelephonyManager.
11644      *
11645      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
11646      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11647      *
11648      * @return Map including the keys as the active subscription IDs (Note: if there is no active
11649      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
11650      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
11651      * or throw a SecurityException if the caller does not have the permission.
11652      */
11653     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
11654     @NonNull
getEmergencyNumberList()11655     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
11656         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
11657         try {
11658             ITelephony telephony = getITelephony();
11659             if (telephony != null) {
11660                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
11661                         null);
11662             } else {
11663                 throw new IllegalStateException("telephony service is null.");
11664             }
11665         } catch (RemoteException ex) {
11666             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
11667             ex.rethrowAsRuntimeException();
11668         }
11669         return emergencyNumberList;
11670     }
11671 
11672     /**
11673      * Get the per-category emergency number list based on current locale, sim, default, modem
11674      * and network.
11675      *
11676      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
11677      * priority sources will be located at the smaller index; the priority order of sources are:
11678      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
11679      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
11680      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
11681      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
11682      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
11683      *
11684      * <p>The subscriptions which the returned list would be based on, are all the active
11685      * subscriptions, no matter which subscription could be used to create TelephonyManager.
11686      *
11687      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
11688      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11689      *
11690      * @param categories the emergency service categories which are the bitwise-OR combination of
11691      * the following constants:
11692      * <ol>
11693      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
11694      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
11695      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
11696      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
11697      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
11698      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
11699      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
11700      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
11701      * </ol>
11702      * @return Map including the keys as the active subscription IDs (Note: if there is no active
11703      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
11704      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
11705      * or throw a SecurityException if the caller does not have the permission.
11706      * @throws IllegalStateException if the Telephony process is not currently available.
11707      */
11708     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
11709     @NonNull
getEmergencyNumberList( @mergencyServiceCategories int categories)11710     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
11711             @EmergencyServiceCategories int categories) {
11712         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
11713         try {
11714             ITelephony telephony = getITelephony();
11715             if (telephony != null) {
11716                 emergencyNumberList = telephony.getEmergencyNumberList(
11717                         mContext.getOpPackageName(), null);
11718                 if (emergencyNumberList != null) {
11719                     for (Integer subscriptionId : emergencyNumberList.keySet()) {
11720                         List<EmergencyNumber> numberList = emergencyNumberList.get(subscriptionId);
11721                         for (EmergencyNumber number : numberList) {
11722                             if (!number.isInEmergencyServiceCategories(categories)) {
11723                                 numberList.remove(number);
11724                             }
11725                         }
11726                     }
11727                 }
11728                 return emergencyNumberList;
11729             } else {
11730                 throw new IllegalStateException("telephony service is null.");
11731             }
11732         } catch (RemoteException ex) {
11733             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
11734             ex.rethrowAsRuntimeException();
11735         }
11736         return emergencyNumberList;
11737     }
11738 
11739     /**
11740      * Identifies if the supplied phone number is an emergency number that matches a known
11741      * emergency number based on current locale, SIM card(s), Android database, modem, network,
11742      * or defaults.
11743      *
11744      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
11745      * numbers are not considered emergency numbers. A dialable phone number consists only
11746      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
11747      *
11748      * <p>The subscriptions which the identification would be based on, are all the active
11749      * subscriptions, no matter which subscription could be used to create TelephonyManager.
11750      *
11751      * @param number - the number to look up
11752      * @return {@code true} if the given number is an emergency number based on current locale,
11753      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
11754      * @throws IllegalStateException if the Telephony process is not currently available.
11755      */
isEmergencyNumber(@onNull String number)11756     public boolean isEmergencyNumber(@NonNull String number) {
11757         try {
11758             ITelephony telephony = getITelephony();
11759             if (telephony != null) {
11760                 return telephony.isEmergencyNumber(number, true);
11761             } else {
11762                 throw new IllegalStateException("telephony service is null.");
11763             }
11764         } catch (RemoteException ex) {
11765             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
11766             ex.rethrowAsRuntimeException();
11767         }
11768         return false;
11769     }
11770 
11771     /**
11772      * Checks if the supplied number is an emergency number based on current locale, sim, default,
11773      * modem and network.
11774      *
11775      * <p> Specifically, this method will return {@code true} if the specified number is an
11776      * emergency number, *or* if the number simply starts with the same digits as any current
11777      * emergency number.
11778      *
11779      * <p>The subscriptions which the identification would be based on, are all the active
11780      * subscriptions, no matter which subscription could be used to create TelephonyManager.
11781      *
11782      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
11783      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11784      *
11785      * @param number - the number to look up
11786      * @return {@code true} if the given number is an emergency number or it simply starts with
11787      * the same digits of any current emergency number based on current locale, sim, modem and
11788      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
11789      * have the required permission/privileges
11790      * @throws IllegalStateException if the Telephony process is not currently available.
11791      * @hide
11792      */
11793     @SystemApi
11794     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isPotentialEmergencyNumber(@onNull String number)11795     public boolean isPotentialEmergencyNumber(@NonNull String number) {
11796         try {
11797             ITelephony telephony = getITelephony();
11798             if (telephony != null) {
11799                 return telephony.isEmergencyNumber(number, false);
11800             } else {
11801                 throw new IllegalStateException("telephony service is null.");
11802             }
11803         } catch (RemoteException ex) {
11804             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
11805             ex.rethrowAsRuntimeException();
11806         }
11807         return false;
11808     }
11809 
11810     /**
11811      * Returns the emergency number database version.
11812      *
11813      * <p>Requires Permission:
11814      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11815      *
11816      * @hide
11817      */
11818     @TestApi
11819     @SystemApi
11820     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyNumberDbVersion()11821     public int getEmergencyNumberDbVersion() {
11822         try {
11823             ITelephony telephony = getITelephony();
11824             if (telephony != null) {
11825                 return telephony.getEmergencyNumberDbVersion(getSubId());
11826             }
11827         } catch (RemoteException ex) {
11828             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
11829             ex.rethrowAsRuntimeException();
11830         }
11831         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
11832     }
11833 
11834     /** @hide */
11835     @Retention(RetentionPolicy.SOURCE)
11836     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
11837             SET_OPPORTUNISTIC_SUB_SUCCESS,
11838             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
11839             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
11840             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
11841             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
11842     public @interface SetOpportunisticSubscriptionResult {}
11843 
11844     /**
11845      * No error. Operation succeeded.
11846      */
11847     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
11848 
11849     /**
11850      * Validation failed when trying to switch to preferred subscription.
11851      */
11852     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
11853 
11854     /**
11855      * The subscription is not valid. It must be an active opportunistic subscription.
11856      */
11857     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
11858 
11859     /**
11860      * The subscription is not valid. It must be an opportunistic subscription.
11861      */
11862     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
11863 
11864     /**
11865      * Subscription service happened remote exception.
11866      */
11867     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
11868 
11869     /** @hide */
11870     @Retention(RetentionPolicy.SOURCE)
11871     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
11872             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
11873             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
11874             UPDATE_AVAILABLE_NETWORKS_ABORTED,
11875             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
11876             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
11877             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
11878             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
11879             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
11880             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
11881             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
11882             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED})
11883     public @interface UpdateAvailableNetworksResult {}
11884 
11885     /**
11886      * No error. Operation succeeded.
11887      */
11888     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
11889 
11890     /**
11891      * There is a unknown failure happened.
11892      */
11893     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
11894 
11895     /**
11896      * The request is aborted.
11897      */
11898     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
11899 
11900     /**
11901      * The parameter passed in is invalid.
11902      */
11903     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
11904 
11905     /**
11906      * No carrier privilege.
11907      */
11908     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
11909 
11910     /**
11911      * Disable modem fail.
11912      */
11913     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
11914 
11915     /**
11916      * Enable modem fail.
11917      */
11918     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
11919 
11920     /**
11921      * Carrier app does not support multiple available networks.
11922      */
11923     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
11924 
11925     /**
11926      * The subscription is not valid. It must be an opportunistic subscription.
11927      */
11928     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
11929 
11930     /**
11931      * There is no OpportunisticNetworkService.
11932      */
11933     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
11934 
11935     /**
11936      * OpportunisticNetworkService is disabled.
11937      */
11938     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
11939 
11940     /**
11941      * Set preferred opportunistic data subscription id.
11942      *
11943      * Switch internet data to preferred opportunistic data subscription id. This api
11944      * can result in lose of internet connectivity for short period of time while internet data
11945      * is handed over.
11946      * <p>Requires that the calling app has carrier privileges on both primary and
11947      * secondary subscriptions (see
11948      * {@link #hasCarrierPrivileges}), or has permission
11949      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11950      *
11951      * @param subId which opportunistic subscription
11952      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
11953      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
11954      * @param needValidation whether validation is needed before switch happens.
11955      * @param executor The executor of where the callback will execute.
11956      * @param callback Callback will be triggered once it succeeds or failed.
11957      *                 See {@link TelephonyManager.SetOpportunisticSubscriptionResult}
11958      *                 for more details. Pass null if don't care about the result.
11959      */
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)11960     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
11961             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
11962         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
11963         try {
11964             IOns iOpportunisticNetworkService = getIOns();
11965             if (iOpportunisticNetworkService == null) {
11966                 if (executor == null || callback == null) {
11967                     return;
11968                 }
11969                 final long identity = Binder.clearCallingIdentity();
11970                 try {
11971                     executor.execute(() -> {
11972                         if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
11973                             callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
11974                         } else {
11975                             callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
11976                         }
11977                     });
11978                 } finally {
11979                     Binder.restoreCallingIdentity(identity);
11980                 }
11981                 return;
11982             }
11983             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
11984                 @Override
11985                 public void onComplete(int result) {
11986                     if (executor == null || callback == null) {
11987                         return;
11988                     }
11989                     final long identity = Binder.clearCallingIdentity();
11990                     try {
11991                         executor.execute(() -> {
11992                             callback.accept(result);
11993                         });
11994                     } finally {
11995                         Binder.restoreCallingIdentity(identity);
11996                     }
11997                 }
11998             };
11999 
12000             iOpportunisticNetworkService
12001                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
12002                             pkgForDebug);
12003         } catch (RemoteException ex) {
12004             Rlog.e(TAG, "setPreferredDataSubscriptionId RemoteException", ex);
12005         }
12006         return;
12007     }
12008 
12009     /**
12010      * Get preferred opportunistic data subscription Id
12011      *
12012      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
12013      * or has either READ_PRIVILEGED_PHONE_STATE
12014      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
12015      * @return subId preferred opportunistic subscription id or
12016      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
12017      * subscription id
12018      *
12019      */
12020     @RequiresPermission(anyOf = {
12021             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
12022             android.Manifest.permission.READ_PHONE_STATE
12023     })
getPreferredOpportunisticDataSubscription()12024     public int getPreferredOpportunisticDataSubscription() {
12025         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12026         String featureId = null;
12027         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
12028         try {
12029             IOns iOpportunisticNetworkService = getIOns();
12030             if (iOpportunisticNetworkService != null) {
12031                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
12032                         packageName, featureId);
12033             }
12034         } catch (RemoteException ex) {
12035             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
12036         }
12037         return subId;
12038     }
12039 
12040     /**
12041      * Update availability of a list of networks in the current location.
12042      *
12043      * This api should be called to inform OpportunisticNetwork Service about the availability
12044      * of a network at the current location. This information will be used by OpportunisticNetwork
12045      * service to enable modem stack and to attach to the network. If an empty list is passed,
12046      * it is assumed that no network is available and will result in disabling the modem stack
12047      * to save power. This api do not switch internet data once network attach is completed.
12048      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
12049      * to switch internet data after network attach is complete.
12050      * Requires that the calling app has carrier privileges on both primary and
12051      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
12052      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12053      * @param availableNetworks is a list of available network information.
12054      * @param executor The executor of where the callback will execute.
12055      * @param callback Callback will be triggered once it succeeds or failed.
12056      *
12057      */
12058     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)12059     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
12060             @Nullable @CallbackExecutor Executor executor,
12061             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
12062         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12063         try {
12064             IOns iOpportunisticNetworkService = getIOns();
12065             if (iOpportunisticNetworkService == null || availableNetworks == null) {
12066                 if (executor == null || callback == null) {
12067                     return;
12068                 }
12069                 if (iOpportunisticNetworkService == null) {
12070                     final long identity = Binder.clearCallingIdentity();
12071                     try {
12072                         executor.execute(() -> {
12073                             if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
12074                                 callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
12075                             } else {
12076                                 callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
12077                             }
12078                         });
12079                     } finally {
12080                         Binder.restoreCallingIdentity(identity);
12081                     }
12082                 } else {
12083                     final long identity = Binder.clearCallingIdentity();
12084                     try {
12085                         executor.execute(() -> {
12086                             callback.accept(UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS);
12087                         });
12088                     } finally {
12089                         Binder.restoreCallingIdentity(identity);
12090                     }
12091                 }
12092                 return;
12093             }
12094             IUpdateAvailableNetworksCallback callbackStub =
12095                     new IUpdateAvailableNetworksCallback.Stub() {
12096                         @Override
12097                         public void onComplete(int result) {
12098                             if (executor == null || callback == null) {
12099                                 return;
12100                             }
12101                             final long identity = Binder.clearCallingIdentity();
12102                             try {
12103                                 executor.execute(() -> {
12104                                     callback.accept(result);
12105                                 });
12106                             } finally {
12107                                 Binder.restoreCallingIdentity(identity);
12108                             }
12109                         }
12110                     };
12111             iOpportunisticNetworkService.updateAvailableNetworks(availableNetworks, callbackStub,
12112                     pkgForDebug);
12113         } catch (RemoteException ex) {
12114             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
12115         }
12116     }
12117 
12118     /**
12119      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
12120      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
12121      * For example, we will disable a modem when user or system believes the corresponding SIM
12122      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
12123      *
12124      * Requires that the calling app has permission
12125      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12126      * @param slotIndex which corresponding modem will operate on.
12127      * @param enable whether to enable or disable the modem stack.
12128      * @return whether the operation is successful.
12129      *
12130      * @hide
12131      */
12132     @SystemApi
12133     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableModemForSlot(int slotIndex, boolean enable)12134     public boolean enableModemForSlot(int slotIndex, boolean enable) {
12135         boolean ret = false;
12136         try {
12137             ITelephony telephony = getITelephony();
12138             if (telephony != null) {
12139                 ret = telephony.enableModemForSlot(slotIndex, enable);
12140             }
12141         } catch (RemoteException ex) {
12142             Log.e(TAG, "enableModem RemoteException", ex);
12143         }
12144         return ret;
12145     }
12146 
12147     /**
12148      * It indicates whether modem is enabled or not per slot.
12149      * It's the corresponding status of {@link #enableModemForSlot}.
12150      *
12151      * @param slotIndex which slot it's checking.
12152      * @hide
12153      */
12154     @SystemApi
isModemEnabledForSlot(int slotIndex)12155     public boolean isModemEnabledForSlot(int slotIndex) {
12156         try {
12157             ITelephony telephony = getITelephony();
12158             if (telephony != null) {
12159                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
12160                         null);
12161             }
12162         } catch (RemoteException ex) {
12163             Log.e(TAG, "enableModem RemoteException", ex);
12164         }
12165         return false;
12166     }
12167 
12168     /**
12169      * Broadcast intent action for network country code changes.
12170      *
12171      * <p>
12172      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
12173      * network returned by {@link #getNetworkCountryIso()}.
12174      *
12175      * <p>There may be a delay of several minutes before reporting that no country is detected.
12176      *
12177      * @see #EXTRA_NETWORK_COUNTRY
12178      * @see #getNetworkCountryIso()
12179      */
12180     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
12181             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
12182 
12183     /**
12184      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
12185      * the country code in ISO 3166 format.
12186      * <p class="note">
12187      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
12188      */
12189     public static final String EXTRA_NETWORK_COUNTRY =
12190             "android.telephony.extra.NETWORK_COUNTRY";
12191 
12192     /**
12193      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
12194      * last known the country code in ISO-3166-1 alpha-2 format.
12195      * <p class="note">
12196      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
12197      *
12198      * @hide
12199      */
12200     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
12201             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
12202 
12203     /**
12204      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
12205      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
12206      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
12207      * policies of the carrier.
12208      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
12209      * access to the network.
12210      *
12211      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
12212      * otherwise.
12213      *
12214      * @hide
12215      */
12216     @SystemApi
12217     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)12218     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
12219         try {
12220             ITelephony service = getITelephony();
12221             if (service != null) {
12222                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
12223             }
12224         } catch (RemoteException e) {
12225             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
12226         }
12227     }
12228 
12229     /**
12230      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12231      * Standby or Dual Active) is supported.
12232      */
12233     public static final int MULTISIM_ALLOWED = 0;
12234 
12235     /**
12236      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12237      * Standby or Dual Active) is not supported by the hardware.
12238      */
12239     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
12240 
12241     /**
12242      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
12243      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
12244      */
12245     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
12246 
12247     /** @hide */
12248     @Retention(RetentionPolicy.SOURCE)
12249     @IntDef(prefix = {"MULTISIM_"},
12250             value = {
12251                     MULTISIM_ALLOWED,
12252                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
12253                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
12254             })
12255     public @interface IsMultiSimSupportedResult {}
12256 
12257     /**
12258      * Returns if the usage of multiple SIM cards at the same time to register on the network
12259      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
12260      *
12261      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12262      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12263      *
12264      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
12265      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
12266      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
12267      * functionality is restricted by the carrier.
12268      */
12269     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12270     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12271     @IsMultiSimSupportedResult
isMultiSimSupported()12272     public int isMultiSimSupported() {
12273         if (getSupportedModemCount() < 2) {
12274             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
12275         }
12276         try {
12277             ITelephony service = getITelephony();
12278             if (service != null) {
12279                 return service.isMultiSimSupported(getOpPackageName(), getFeatureId());
12280             }
12281         } catch (RemoteException e) {
12282             Log.e(TAG, "isMultiSimSupported RemoteException", e);
12283         }
12284         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
12285     }
12286 
12287     /**
12288      * Switch configs to enable multi-sim or switch back to single-sim
12289      * <p>Requires Permission:
12290      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
12291      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12292      *
12293      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
12294      * to single-sim
12295      *
12296      * @param numOfSims number of live SIMs we want to switch to
12297      * @throws android.os.RemoteException
12298      */
12299     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12300     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchMultiSimConfig(int numOfSims)12301     public void switchMultiSimConfig(int numOfSims) {
12302         try {
12303             ITelephony telephony = getITelephony();
12304             if (telephony != null) {
12305                 telephony.switchMultiSimConfig(numOfSims);
12306             }
12307         } catch (RemoteException ex) {
12308             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
12309         }
12310     }
12311 
12312     /**
12313      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
12314      * trigger device reboot.
12315      * The modem configuration change refers to switching from single SIM configuration to DSDS
12316      * or the other way around.
12317      *
12318      *  <p>Requires Permission:
12319      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
12320      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12321      *
12322      * @return {@code true} if reboot will be triggered after making changes to modem
12323      * configurations, otherwise return {@code false}.
12324      */
12325     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
doesSwitchMultiSimConfigTriggerReboot()12326     public boolean doesSwitchMultiSimConfigTriggerReboot() {
12327         try {
12328             ITelephony service = getITelephony();
12329             if (service != null) {
12330                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
12331                         getOpPackageName(), getFeatureId());
12332             }
12333         } catch (RemoteException e) {
12334             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
12335         }
12336         return false;
12337     }
12338 
12339     /**
12340      * Retrieve the Radio HAL Version for this device.
12341      *
12342      * Get the HAL version for the IRadio interface for test purposes.
12343      *
12344      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
12345      *
12346      * @hide
12347      */
12348     @UnsupportedAppUsage
12349     @TestApi
getRadioHalVersion()12350     public Pair<Integer, Integer> getRadioHalVersion() {
12351         try {
12352             ITelephony service = getITelephony();
12353             if (service != null) {
12354                 int version = service.getRadioHalVersion();
12355                 if (version == -1) return new Pair<Integer, Integer>(-1, -1);
12356                 return new Pair<Integer, Integer>(version / 100, version % 100);
12357             }
12358         } catch (RemoteException e) {
12359             Log.e(TAG, "getRadioHalVersion() RemoteException", e);
12360         }
12361         return new Pair<Integer, Integer>(-1, -1);
12362     }
12363 
12364     /**
12365      * Get the calling application status about carrier privileges for the subscription created
12366      * in TelephonyManager. Used by Telephony Module for permission checking.
12367      *
12368      * @param uid Uid to check.
12369      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
12370      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
12371      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
12372      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
12373      *
12374      * @hide
12375      */
12376     @SystemApi
12377     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierPrivilegeStatus(int uid)12378     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
12379         try {
12380             ITelephony telephony = getITelephony();
12381             if (telephony != null) {
12382                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
12383             }
12384         } catch (RemoteException ex) {
12385             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
12386         }
12387         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
12388     }
12389 
12390     /**
12391      * Returns a list of APNs set as overrides by the device policy manager via
12392      * {@link #addDevicePolicyOverrideApn}.
12393      * This method must only be called from the system or phone processes.
12394      *
12395      * @param context Context to use.
12396      * @return {@link List} of APNs that have been set as overrides.
12397      * @throws {@link SecurityException} if the caller is not the system or phone process.
12398      * @hide
12399      */
12400     @SystemApi
12401     @TestApi
12402     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)12403     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
12404         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
12405             if (cursor == null) {
12406                 return Collections.emptyList();
12407             }
12408             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
12409             cursor.moveToPosition(-1);
12410             while (cursor.moveToNext()) {
12411                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
12412                 apnList.add(apn);
12413             }
12414             return apnList;
12415         }
12416     }
12417 
12418     /**
12419      * Used by the device policy manager to add a new override APN.
12420      * This method must only be called from the system or phone processes.
12421      *
12422      * @param context Context to use.
12423      * @param apnSetting The {@link ApnSetting} describing the new APN.
12424      * @return An integer, corresponding to a primary key in a database, that allows the caller to
12425      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
12426      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
12427      *         failed.
12428      * @throws {@link SecurityException} if the caller is not the system or phone process.
12429      * @hide
12430      */
12431     @SystemApi
12432     @TestApi
12433     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)12434     public int addDevicePolicyOverrideApn(@NonNull Context context,
12435             @NonNull ApnSetting apnSetting) {
12436         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
12437 
12438         int resultId = INVALID_APN_ID;
12439         if (resultUri != null) {
12440             try {
12441                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
12442             } catch (NumberFormatException e) {
12443                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
12444                         + resultUri.getLastPathSegment());
12445             }
12446         }
12447         return resultId;
12448     }
12449 
12450     /**
12451      * Used by the device policy manager to modify an override APN.
12452      * This method must only be called from the system or phone processes.
12453      *
12454      * @param context Context to use.
12455      * @param apnId The integer key of the APN to modify, as returned by
12456      *              {@link #addDevicePolicyOverrideApn}
12457      * @param apnSetting The {@link ApnSetting} describing the updated APN.
12458      * @return {@code true} if successful, {@code false} otherwise.
12459      * @throws {@link SecurityException} if the caller is not the system or phone process.
12460      * @hide
12461      */
12462     @SystemApi
12463     @TestApi
12464     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)12465     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
12466             @NonNull ApnSetting apnSetting) {
12467         return context.getContentResolver().update(
12468                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
12469                 apnSetting.toContentValues(), null, null) > 0;
12470     }
12471 
12472     /**
12473      * Return whether data is enabled for certain APN type. This will tell if framework will accept
12474      * corresponding network requests on a subId.
12475      *
12476      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
12477      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
12478      *
12479      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
12480      * It will return true if:
12481      *
12482      *  1) User data is turned on, or
12483      *  2) APN is un-metered for this subscription, or
12484      *  3) APN type is whitelisted. E.g. MMS is whitelisted if
12485      *  {@link #setAlwaysAllowMmsData(boolean)} is turned on.
12486      *
12487      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
12488      * @return whether data is enabled for a apn type.
12489      *
12490      * @hide
12491      */
12492     @SystemApi
12493     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataEnabledForApn(@pnType int apnType)12494     public boolean isDataEnabledForApn(@ApnType int apnType) {
12495         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12496         try {
12497             ITelephony service = getITelephony();
12498             if (service != null) {
12499                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
12500             }
12501         } catch (RemoteException ex) {
12502             if (!isSystemProcess()) {
12503                 ex.rethrowAsRuntimeException();
12504             }
12505         }
12506         return false;
12507     }
12508 
12509     /**
12510      * Whether an APN type is metered or not. It will be evaluated with the subId associated
12511      * with the TelephonyManager instance.
12512      *
12513      * @hide
12514      */
isApnMetered(@pnType int apnType)12515     public boolean isApnMetered(@ApnType int apnType) {
12516         try {
12517             ITelephony service = getITelephony();
12518             if (service != null) {
12519                 return service.isApnMetered(apnType, getSubId());
12520             }
12521         } catch (RemoteException ex) {
12522             if (!isSystemProcess()) {
12523                 ex.rethrowAsRuntimeException();
12524             }
12525         }
12526         return true;
12527     }
12528 
12529     /**
12530      * Specify which bands modem's background scan must act on.
12531      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
12532      * Otherwise, it scans all bands.
12533      *
12534      * For example, CBRS is only on LTE band 48. By specifying this band,
12535      * modem saves more power.
12536      *
12537      * @param specifiers which bands to scan.
12538      * @param executor The executor to execute the callback on
12539      * @param callback The callback that gets invoked when the radio responds to the request. Called
12540      *                 with {@code true} if the request succeeded, {@code false} otherwise.
12541      * @hide
12542      */
12543     @SystemApi
12544     @TestApi
12545     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)12546     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
12547             @NonNull @CallbackExecutor Executor executor,
12548             @NonNull Consumer<Boolean> callback) {
12549         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
12550         Objects.requireNonNull(executor, "Executor must not be null.");
12551         Objects.requireNonNull(callback, "Callback must not be null.");
12552         setSystemSelectionChannelsInternal(specifiers, executor, callback);
12553     }
12554 
12555     /**
12556      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
12557      * used when the caller does not need feedback on the results of the operation.
12558      * @param specifiers which bands to scan.
12559      * @hide
12560      */
12561     @SystemApi
12562     @TestApi
12563     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)12564     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
12565         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
12566         setSystemSelectionChannelsInternal(specifiers, null, null);
12567     }
12568 
12569 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)12570     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
12571             @Nullable @CallbackExecutor Executor executor,
12572             @Nullable Consumer<Boolean> callback) {
12573         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
12574             @Override
12575             public void accept(boolean result) {
12576                 executor.execute(() -> callback.accept(result));
12577             }
12578         };
12579 
12580         try {
12581             ITelephony service = getITelephony();
12582             if (service != null) {
12583                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
12584             }
12585         } catch (RemoteException ex) {
12586             if (!isSystemProcess()) {
12587                 ex.rethrowAsRuntimeException();
12588             }
12589         }
12590     }
12591 
12592     /**
12593      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
12594      *
12595      * @param mccmnc the carrier's mccmnc that you want to match
12596      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
12597      * @param mvnoMatchData the MVNO match data
12598      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
12599      * {@code false} otherwise.
12600      *
12601      * {@hide}
12602      */
12603     @SystemApi
isCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)12604     public boolean isCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
12605             @Nullable String mvnoMatchData) {
12606         try {
12607             if (!mccmnc.equals(getSimOperator())) {
12608                 return false;
12609             }
12610             ITelephony service = getITelephony();
12611             if (service != null) {
12612                 return service.isMvnoMatched(getSubId(), mvnoType, mvnoMatchData);
12613             }
12614         } catch (RemoteException ex) {
12615             if (!isSystemProcess()) {
12616                 ex.rethrowAsRuntimeException();
12617             }
12618         }
12619         return false;
12620     }
12621 
12622     /**
12623      * Gets the voice call forwarding info {@link CallForwardingInfo}, given the call forward
12624      * reason.
12625      *
12626      * @param callForwardingReason the call forwarding reasons
12627      *
12628      * @throws IllegalArgumentException if callForwardingReason is not any of
12629      * {@link CallForwardingInfo.REASON_UNCONDITIONAL}, {@link CallForwardingInfo.REASON_BUSY},
12630      * {@link CallForwardingInfo.REASON_NO_REPLY}, {@link CallForwardingInfo.REASON_NOT_REACHABLE},
12631      * {@link CallForwardingInfo.REASON_ALL}, {@link CallForwardingInfo.REASON_ALL_CONDITIONAL}
12632      *
12633      * @return {@link CallForwardingInfo} with the status {@link CallForwardingInfo#STATUS_ACTIVE}
12634      * or {@link CallForwardingInfo#STATUS_INACTIVE} and the target phone number to forward calls
12635      * to, if it's available. Otherwise, it will return a {@link CallForwardingInfo} with status
12636      * {@link CallForwardingInfo#STATUS_UNKNOWN_ERROR},
12637      * {@link CallForwardingInfo#STATUS_NOT_SUPPORTED},
12638      * or {@link CallForwardingInfo#STATUS_FDN_CHECK_FAILURE} depending on the situation.
12639      *
12640      * @hide
12641      */
12642     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12643     @NonNull
getCallForwarding(@allForwardingReason int callForwardingReason)12644     public CallForwardingInfo getCallForwarding(@CallForwardingReason int callForwardingReason) {
12645         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
12646                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
12647             throw new IllegalArgumentException("callForwardingReason is out of range");
12648         }
12649         try {
12650             ITelephony telephony = getITelephony();
12651             if (telephony != null) {
12652                 return telephony.getCallForwarding(getSubId(), callForwardingReason);
12653             }
12654         } catch (RemoteException ex) {
12655             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
12656         } catch (NullPointerException ex) {
12657             Rlog.e(TAG, "getCallForwarding NPE", ex);
12658         }
12659         return new CallForwardingInfo(
12660                 CallForwardingInfo.STATUS_UNKNOWN_ERROR, 0 /* reason */, null /* number */,
12661                         0 /* timeout */);
12662     }
12663 
12664     /**
12665      * Sets the voice call forwarding info including status (enable/disable), call forwarding
12666      * reason, the number to forward, and the timeout before the forwarding is attempted.
12667      *
12668      * @param callForwardingInfo {@link CallForwardingInfo} to setup the call forwarding.
12669      * Enabling if {@link CallForwardingInfo#getStatus()} returns
12670      * {@link CallForwardingInfo#STATUS_ACTIVE}; Disabling if
12671      * {@link CallForwardingInfo#getStatus()} returns {@link CallForwardingInfo#STATUS_INACTIVE}.
12672      *
12673      * @throws IllegalArgumentException if any of the following for parameter callForwardingInfo:
12674      * 0) it is {@code null}.
12675      * 1) {@link CallForwardingInfo#getStatus()} returns neither
12676      * {@link CallForwardingInfo#STATUS_ACTIVE} nor {@link CallForwardingInfo#STATUS_INACTIVE}.
12677      * 2) {@link CallForwardingInfo#getReason()} is not any of
12678      * {@link CallForwardingInfo.REASON_UNCONDITIONAL}, {@link CallForwardingInfo.REASON_BUSY},
12679      * {@link CallForwardingInfo.REASON_NO_REPLY}, {@link CallForwardingInfo.REASON_NOT_REACHABLE},
12680      * {@link CallForwardingInfo.REASON_ALL}, {@link CallForwardingInfo.REASON_ALL_CONDITIONAL}
12681      * 3) {@link CallForwardingInfo#getNumber()} returns {@code null}.
12682      * 4) {@link CallForwardingInfo#getTimeoutSeconds()} doesn't return a positive value.
12683      *
12684      * @return {@code true} to indicate it was set successfully; {@code false} otherwise.
12685      *
12686      * @hide
12687      */
12688     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo)12689     public boolean setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo) {
12690         if (callForwardingInfo == null) {
12691             throw new IllegalArgumentException("callForwardingInfo is null");
12692         }
12693         int callForwardingStatus = callForwardingInfo.getStatus();
12694         if (callForwardingStatus != CallForwardingInfo.STATUS_ACTIVE
12695                 && callForwardingStatus != CallForwardingInfo.STATUS_INACTIVE) {
12696             throw new IllegalArgumentException(
12697                     "callForwardingStatus is neither active nor inactive");
12698         }
12699         int callForwardingReason = callForwardingInfo.getReason();
12700         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
12701                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
12702             throw new IllegalArgumentException("callForwardingReason is out of range");
12703         }
12704         if (callForwardingInfo.getNumber() == null) {
12705             throw new IllegalArgumentException("callForwarding number is null");
12706         }
12707         if (callForwardingInfo.getTimeoutSeconds() <= 0) {
12708             throw new IllegalArgumentException("callForwarding timeout isn't positive");
12709         }
12710         try {
12711             ITelephony telephony = getITelephony();
12712             if (telephony != null) {
12713                 return telephony.setCallForwarding(getSubId(), callForwardingInfo);
12714             }
12715         } catch (RemoteException ex) {
12716             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
12717         } catch (NullPointerException ex) {
12718             Rlog.e(TAG, "setCallForwarding NPE", ex);
12719         }
12720         return false;
12721     }
12722 
12723     /**
12724      * Indicates the call waiting status is active.
12725      *
12726      * @hide
12727      */
12728     public static final int CALL_WAITING_STATUS_ACTIVE = 1;
12729 
12730     /**
12731      * Indicates the call waiting status is inactive.
12732      *
12733      * @hide
12734      */
12735     public static final int CALL_WAITING_STATUS_INACTIVE = 2;
12736 
12737     /**
12738      * Indicates the call waiting status is with an unknown error.
12739      *
12740      * @hide
12741      */
12742     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
12743 
12744     /**
12745      * Indicates the call waiting is not supported (e.g. called via CDMA).
12746      *
12747      * @hide
12748      */
12749     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
12750 
12751     /**
12752      * Call waiting function status
12753      *
12754      * @hide
12755      */
12756     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
12757         CALL_WAITING_STATUS_ACTIVE,
12758         CALL_WAITING_STATUS_INACTIVE,
12759         CALL_WAITING_STATUS_NOT_SUPPORTED,
12760         CALL_WAITING_STATUS_UNKNOWN_ERROR
12761     })
12762     @Retention(RetentionPolicy.SOURCE)
12763     public @interface CallWaitingStatus {
12764     }
12765 
12766     /**
12767      * Gets the status of voice call waiting function. Call waiting function enables the waiting
12768      * for the incoming call when it reaches the user who is busy to make another call and allows
12769      * users to decide whether to switch to the incoming call.
12770      *
12771      * @return the status of call waiting function.
12772      * @hide
12773      */
12774     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCallWaitingStatus()12775     public @CallWaitingStatus int getCallWaitingStatus() {
12776         try {
12777             ITelephony telephony = getITelephony();
12778             if (telephony != null) {
12779                 return telephony.getCallWaitingStatus(getSubId());
12780             }
12781         } catch (RemoteException ex) {
12782             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
12783         } catch (NullPointerException ex) {
12784             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
12785         }
12786         return CALL_WAITING_STATUS_UNKNOWN_ERROR;
12787     }
12788 
12789     /**
12790      * Sets the status for voice call waiting function. Call waiting function enables the waiting
12791      * for the incoming call when it reaches the user who is busy to make another call and allows
12792      * users to decide whether to switch to the incoming call.
12793      *
12794      * @param isEnable {@code true} to enable; {@code false} to disable.
12795      * @return {@code true} to indicate it was set successfully; {@code false} otherwise.
12796      *
12797      * @hide
12798      */
12799     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallWaitingStatus(boolean isEnable)12800     public boolean setCallWaitingStatus(boolean isEnable) {
12801         try {
12802             ITelephony telephony = getITelephony();
12803             if (telephony != null) {
12804                 return telephony.setCallWaitingStatus(getSubId(), isEnable);
12805             }
12806         } catch (RemoteException ex) {
12807             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
12808         } catch (NullPointerException ex) {
12809             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
12810         }
12811         return false;
12812     }
12813 
12814     /**
12815      * Set allowing mobile data during voice call. This is used for allowing data on the non-default
12816      * data SIM. When a voice call is placed on the non-default data SIM on DSDS devices, users will
12817      * not be able to use mobile data. By calling this API, data will be temporarily enabled on the
12818      * non-default data SIM during the life cycle of the voice call.
12819      *
12820      * @param allow {@code true} if allowing using data during voice call, {@code false} if
12821      * disallowed.
12822      *
12823      * @return {@code true} if operation is successful. otherwise {@code false}.
12824      *
12825      * @throws SecurityException if the caller doesn't have the permission.
12826      *
12827      * @hide
12828      */
12829     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataAllowedDuringVoiceCall(boolean allow)12830     public boolean setDataAllowedDuringVoiceCall(boolean allow) {
12831         try {
12832             ITelephony service = getITelephony();
12833             if (service != null) {
12834                 return service.setDataAllowedDuringVoiceCall(getSubId(), allow);
12835             }
12836         } catch (RemoteException ex) {
12837             // This could happen if binder process crashes.
12838             if (!isSystemProcess()) {
12839                 ex.rethrowAsRuntimeException();
12840             }
12841         }
12842         return false;
12843     }
12844 
12845     /**
12846      * Check whether data is allowed during voice call. This is used for allowing data on the
12847      * non-default data SIM. When a voice call is placed on the non-default data SIM on DSDS
12848      * devices, users will not be able to use mobile data. By calling this API, data will be
12849      * temporarily enabled on the non-default data SIM during the life cycle of the voice call.
12850      *
12851      * @return {@code true} if data is allowed during voice call.
12852      *
12853      * @throws SecurityException if the caller doesn't have the permission.
12854      *
12855      * @hide
12856      */
12857     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataAllowedInVoiceCall()12858     public boolean isDataAllowedInVoiceCall() {
12859         try {
12860             ITelephony service = getITelephony();
12861             if (service != null) {
12862                 return service.isDataAllowedInVoiceCall(getSubId());
12863             }
12864         } catch (RemoteException ex) {
12865             // This could happen if binder process crashes.
12866             if (!isSystemProcess()) {
12867                 ex.rethrowAsRuntimeException();
12868             }
12869         }
12870         return false;
12871     }
12872 
12873     /**
12874      * Set whether the specific sim card always allows MMS connection. If true, MMS network
12875      * request will be accepted by telephony even if user turns "mobile data" off
12876      * on this specific sim card.
12877      *
12878      * @param alwaysAllow whether Mms data is always allowed.
12879      * @return whether operation is successful.
12880      *
12881      * @hide
12882      */
12883     @SystemApi
12884     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysAllowMmsData(boolean alwaysAllow)12885     public boolean setAlwaysAllowMmsData(boolean alwaysAllow) {
12886         try {
12887             ITelephony service = getITelephony();
12888             if (service != null) {
12889                 return service.setAlwaysAllowMmsData(getSubId(), alwaysAllow);
12890             }
12891         } catch (RemoteException ex) {
12892             if (!isSystemProcess()) {
12893                 ex.rethrowAsRuntimeException();
12894             }
12895         }
12896         return false;
12897     }
12898 
12899     /**
12900      * The IccLock state or password was changed successfully.
12901      * @hide
12902      */
12903     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
12904 
12905     /**
12906      * Check whether ICC pin lock is enabled.
12907      * This is a sync call which returns the cached pin enabled state.
12908      *
12909      * @return {@code true} if ICC lock enabled, {@code false} if ICC lock disabled.
12910      *
12911      * @throws SecurityException if the caller doesn't have the permission.
12912      *
12913      * @hide
12914      */
12915     @WorkerThread
12916     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12917     @SystemApi
isIccLockEnabled()12918     public boolean isIccLockEnabled() {
12919         try {
12920             ITelephony telephony = getITelephony();
12921             if (telephony != null) {
12922                 return telephony.isIccLockEnabled(getSubId());
12923             }
12924         } catch (RemoteException e) {
12925             Log.e(TAG, "isIccLockEnabled RemoteException", e);
12926         }
12927         return false;
12928     }
12929 
12930     /**
12931      * Set the ICC pin lock enabled or disabled.
12932      *
12933      * If enable/disable ICC pin lock successfully, a value of {@link Integer#MAX_VALUE} is
12934      * returned.
12935      * If an incorrect old password is specified, the return value will indicate how many more
12936      * attempts the user can make to change the password before the SIM is locked.
12937      * Using PUK code to unlock SIM if enter the incorrect old password 3 times.
12938      *
12939      * @param enabled    "true" for locked, "false" for unlocked.
12940      * @param password   needed to change the ICC pin state, aka. Pin1
12941      * @return an integer representing the status of IccLock enabled or disabled in the following
12942      * three cases:
12943      *   - {@link TelephonyManager#CHANGE_ICC_LOCK_SUCCESS} if enabled or disabled IccLock
12944      *   successfully.
12945      *   - Positive number and zero for remaining password attempts.
12946      *   - Negative number for other failure cases (such like enabling/disabling PIN failed).
12947      *
12948      * @throws SecurityException if the caller doesn't have the permission.
12949      *
12950      * @hide
12951      */
12952     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setIccLockEnabled(boolean enabled, @NonNull String password)12953     public int setIccLockEnabled(boolean enabled, @NonNull String password) {
12954         checkNotNull(password, "setIccLockEnabled password can't be null.");
12955         try {
12956             ITelephony telephony = getITelephony();
12957             if (telephony != null) {
12958                 return telephony.setIccLockEnabled(getSubId(), enabled, password);
12959             }
12960         } catch (RemoteException e) {
12961             Log.e(TAG, "setIccLockEnabled RemoteException", e);
12962         }
12963         return 0;
12964     }
12965 
12966     /**
12967      * Change the ICC password used in ICC pin lock.
12968      *
12969      * If the password was changed successfully, a value of {@link Integer#MAX_VALUE} is returned.
12970      * If an incorrect old password is specified, the return value will indicate how many more
12971      * attempts the user can make to change the password before the SIM is locked.
12972      * Using PUK code to unlock SIM if enter the incorrect old password 3 times.
12973      *
12974      * @param oldPassword is the old password
12975      * @param newPassword is the new password
12976      * @return an integer representing the status of IccLock changed in the following three cases:
12977      *   - {@link TelephonyManager#CHANGE_ICC_LOCK_SUCCESS} if changed IccLock successfully.
12978      *   - Positive number and zero for remaining password attempts.
12979      *   - Negative number for other failure cases (such like enabling/disabling PIN failed).
12980      *
12981      * @throws SecurityException if the caller doesn't have the permission.
12982      *
12983      * @hide
12984      */
12985     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
changeIccLockPassword(@onNull String oldPassword, @NonNull String newPassword)12986     public int changeIccLockPassword(@NonNull String oldPassword, @NonNull String newPassword) {
12987         checkNotNull(oldPassword, "changeIccLockPassword oldPassword can't be null.");
12988         checkNotNull(newPassword, "changeIccLockPassword newPassword can't be null.");
12989         try {
12990             ITelephony telephony = getITelephony();
12991             if (telephony != null) {
12992                 return telephony.changeIccLockPassword(getSubId(), oldPassword, newPassword);
12993             }
12994         } catch (RemoteException e) {
12995             Log.e(TAG, "changeIccLockPassword RemoteException", e);
12996         }
12997         return 0;
12998     }
12999 
13000     /**
13001      * Whether device can connect to 5G network when two SIMs are active.
13002      * @hide
13003      * TODO b/153669716: remove or make system API.
13004      */
canConnectTo5GInDsdsMode()13005     public boolean canConnectTo5GInDsdsMode() {
13006         ITelephony telephony = getITelephony();
13007         if (telephony == null) return true;
13008         try {
13009             return telephony.canConnectTo5GInDsdsMode();
13010         } catch (RemoteException ex) {
13011             return true;
13012         } catch (NullPointerException ex) {
13013             return true;
13014         }
13015     }
13016 }
13017