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.BytesLong;
27 import android.annotation.CallbackExecutor;
28 import android.annotation.IntDef;
29 import android.annotation.LongDef;
30 import android.annotation.NonNull;
31 import android.annotation.Nullable;
32 import android.annotation.RequiresFeature;
33 import android.annotation.RequiresPermission;
34 import android.annotation.SdkConstant;
35 import android.annotation.SdkConstant.SdkConstantType;
36 import android.annotation.StringDef;
37 import android.annotation.SuppressAutoDoc;
38 import android.annotation.SuppressLint;
39 import android.annotation.SystemApi;
40 import android.annotation.SystemService;
41 import android.annotation.TestApi;
42 import android.annotation.WorkerThread;
43 import android.app.PendingIntent;
44 import android.app.PropertyInvalidatedCache;
45 import android.app.role.RoleManager;
46 import android.compat.Compatibility;
47 import android.compat.annotation.ChangeId;
48 import android.compat.annotation.EnabledAfter;
49 import android.compat.annotation.UnsupportedAppUsage;
50 import android.content.ComponentName;
51 import android.content.Context;
52 import android.content.ContextParams;
53 import android.content.Intent;
54 import android.content.pm.PackageManager;
55 import android.database.Cursor;
56 import android.net.ConnectivityManager;
57 import android.net.NetworkCapabilities;
58 import android.net.Uri;
59 import android.os.AsyncTask;
60 import android.os.Binder;
61 import android.os.Build;
62 import android.os.Bundle;
63 import android.os.Handler;
64 import android.os.IBinder;
65 import android.os.Looper;
66 import android.os.OutcomeReceiver;
67 import android.os.ParcelFileDescriptor;
68 import android.os.ParcelUuid;
69 import android.os.Parcelable;
70 import android.os.PersistableBundle;
71 import android.os.RemoteException;
72 import android.os.ResultReceiver;
73 import android.os.SystemProperties;
74 import android.os.WorkSource;
75 import android.provider.Settings.SettingNotFoundException;
76 import android.service.carrier.CarrierIdentifier;
77 import android.service.carrier.CarrierService;
78 import android.sysprop.TelephonyProperties;
79 import android.telecom.CallScreeningService;
80 import android.telecom.InCallService;
81 import android.telecom.PhoneAccount;
82 import android.telecom.PhoneAccountHandle;
83 import android.telecom.TelecomManager;
84 import android.telephony.Annotation.ApnType;
85 import android.telephony.Annotation.CallState;
86 import android.telephony.Annotation.CarrierPrivilegeStatus;
87 import android.telephony.Annotation.NetworkType;
88 import android.telephony.Annotation.RadioPowerState;
89 import android.telephony.Annotation.SimActivationState;
90 import android.telephony.Annotation.ThermalMitigationResult;
91 import android.telephony.Annotation.UiccAppType;
92 import android.telephony.Annotation.UiccAppTypeExt;
93 import android.telephony.CallForwardingInfo.CallForwardingReason;
94 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
95 import android.telephony.data.ApnSetting;
96 import android.telephony.data.ApnSetting.MvnoType;
97 import android.telephony.data.NetworkSlicingConfig;
98 import android.telephony.emergency.EmergencyNumber;
99 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
100 import android.telephony.gba.UaSecurityProtocolIdentifier;
101 import android.telephony.ims.ImsMmTelManager;
102 import android.telephony.ims.aidl.IImsConfig;
103 import android.telephony.ims.aidl.IImsRegistration;
104 import android.telephony.ims.feature.MmTelFeature;
105 import android.telephony.ims.stub.ImsRegistrationImplBase;
106 import android.text.TextUtils;
107 import android.util.Log;
108 import android.util.Pair;
109 
110 import com.android.internal.annotations.GuardedBy;
111 import com.android.internal.annotations.VisibleForTesting;
112 import com.android.internal.os.BackgroundThread;
113 import com.android.internal.telephony.CellNetworkScanResult;
114 import com.android.internal.telephony.IBooleanConsumer;
115 import com.android.internal.telephony.ICallForwardingInfoCallback;
116 import com.android.internal.telephony.IIntegerConsumer;
117 import com.android.internal.telephony.INumberVerificationCallback;
118 import com.android.internal.telephony.IOns;
119 import com.android.internal.telephony.IPhoneSubInfo;
120 import com.android.internal.telephony.ISetOpportunisticDataCallback;
121 import com.android.internal.telephony.ISms;
122 import com.android.internal.telephony.ISub;
123 import com.android.internal.telephony.ITelephony;
124 import com.android.internal.telephony.IUpdateAvailableNetworksCallback;
125 import com.android.internal.telephony.IccLogicalChannelRequest;
126 import com.android.internal.telephony.OperatorInfo;
127 import com.android.internal.telephony.PhoneConstants;
128 import com.android.internal.telephony.RILConstants;
129 import com.android.telephony.Rlog;
130 
131 import java.io.IOException;
132 import java.io.InputStream;
133 import java.io.OutputStream;
134 import java.lang.annotation.Retention;
135 import java.lang.annotation.RetentionPolicy;
136 import java.nio.file.Files;
137 import java.nio.file.Path;
138 import java.util.ArrayList;
139 import java.util.Arrays;
140 import java.util.Collection;
141 import java.util.Collections;
142 import java.util.HashMap;
143 import java.util.HashSet;
144 import java.util.List;
145 import java.util.Locale;
146 import java.util.Map;
147 import java.util.Objects;
148 import java.util.Optional;
149 import java.util.Set;
150 import java.util.UUID;
151 import java.util.concurrent.Executor;
152 import java.util.concurrent.RejectedExecutionException;
153 import java.util.function.Consumer;
154 import java.util.stream.Collectors;
155 import java.util.stream.IntStream;
156 
157 /**
158  * Provides access to information about the telephony services on
159  * the device. Applications can use the methods in this class to
160  * determine telephony services and states, as well as to access some
161  * types of subscriber information. Applications can also register
162  * a listener to receive notification of telephony state changes.
163  * <p>
164  * The returned TelephonyManager will use the default subscription for all calls.
165  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
166  * <code>
167  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
168  * </code>
169  * <p>
170  * Note that access to some telephony information is
171  * permission-protected. Your application cannot access the protected
172  * information unless it has the appropriate permissions declared in
173  * its manifest file. Where permissions apply, they are noted in the
174  * the methods through which you access the protected information.
175  *
176  * <p>TelephonyManager is intended for use on devices that implement
177  * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
178  * that do not implement this feature, the behavior is not reliable.
179  */
180 @SystemService(Context.TELEPHONY_SERVICE)
181 @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
182 public class TelephonyManager {
183     private static final String TAG = "TelephonyManager";
184 
185     private TelephonyRegistryManager mTelephonyRegistryMgr;
186     /**
187      * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
188      * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
189      */
190     @ChangeId
191     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
192     private static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
193 
194     /**
195      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
196      * into the ResultReceiver Bundle.
197      * @hide
198      */
199     public static final String MODEM_ACTIVITY_RESULT_KEY = "controller_activity";
200 
201     /** @hide */
202     public static final String EXCEPTION_RESULT_KEY = "exception";
203 
204     /**
205      * The process name of the Phone app as well as many other apps that use this process name, such
206      * as settings and vendor components.
207      * @hide
208      */
209     public static final String PHONE_PROCESS_NAME = "com.android.phone";
210 
211     /**
212      * The allowed states of Wi-Fi calling.
213      *
214      * @hide
215      */
216     public interface WifiCallingChoices {
217         /** Always use Wi-Fi calling */
218         static final int ALWAYS_USE = 0;
219         /** Ask the user whether to use Wi-Fi on every call */
220         static final int ASK_EVERY_TIME = 1;
221         /** Never use Wi-Fi calling */
222         static final int NEVER_USE = 2;
223     }
224 
225     /** @hide */
226     @Retention(RetentionPolicy.SOURCE)
227     @IntDef(prefix = {"NETWORK_SELECTION_MODE_"},
228             value = {
229                     NETWORK_SELECTION_MODE_UNKNOWN,
230                     NETWORK_SELECTION_MODE_AUTO,
231                     NETWORK_SELECTION_MODE_MANUAL})
232     public @interface NetworkSelectionMode {}
233 
234     public static final int NETWORK_SELECTION_MODE_UNKNOWN = 0;
235     public static final int NETWORK_SELECTION_MODE_AUTO = 1;
236     public static final int NETWORK_SELECTION_MODE_MANUAL = 2;
237 
238     /**
239      * Reasons for Radio being powered off.
240      *
241      * @hide
242      */
243     @Retention(RetentionPolicy.SOURCE)
244     @IntDef(prefix = {"RADIO_POWER_REASON_"},
245             value = {
246                     RADIO_POWER_REASON_USER,
247                     RADIO_POWER_REASON_THERMAL,
248                     RADIO_POWER_REASON_CARRIER,
249                     RADIO_POWER_REASON_NEARBY_DEVICE})
250     public @interface RadioPowerReason {}
251 
252     /**
253      * This reason is used when users want to turn off radio, e.g., users turn on airplane mode.
254      *
255      * @hide
256      */
257     @SystemApi
258     public static final int RADIO_POWER_REASON_USER = 0;
259     /**
260      * This reason is used when radio needs to be turned off due to thermal.
261      *
262      * @hide
263      */
264     @SystemApi
265     public static final int RADIO_POWER_REASON_THERMAL = 1;
266     /**
267      * This reason is used when carriers want to turn off radio. A privileged app can request to
268      * turn off radio via the system service
269      * {@link com.android.carrierdefaultapp.CaptivePortalLoginActivity}, which subsequently calls
270      * the system APIs {@link requestRadioPowerOffForReason} and
271      * {@link clearRadioPowerOffForReason}.
272      *
273      * @hide
274      */
275     @SystemApi
276     public static final int RADIO_POWER_REASON_CARRIER = 2;
277     /**
278      * Used to reduce power on a battery-constrained device when Telephony services are available
279      * via a paired device which is nearby.
280      *
281      * @hide
282      */
283     @SystemApi
284     public static final int RADIO_POWER_REASON_NEARBY_DEVICE = 3;
285 
286     /** The otaspMode passed to PhoneStateListener#onOtaspChanged */
287     /** @hide */
288     static public final int OTASP_UNINITIALIZED = 0;
289     /** @hide */
290     static public final int OTASP_UNKNOWN = 1;
291     /** @hide */
292     static public final int OTASP_NEEDED = 2;
293     /** @hide */
294     static public final int OTASP_NOT_NEEDED = 3;
295     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
296     /** @hide */
297     static public final int OTASP_SIM_UNPROVISIONED = 5;
298 
299     /**
300      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
301      * available for use in ePDG links.
302      *
303      * @hide
304      */
305     @SystemApi
306     static public final int KEY_TYPE_EPDG = 1;
307 
308     /**
309      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
310      * available for use in WLAN links.
311      *
312      * @hide
313      */
314     @SystemApi
315     static public final int KEY_TYPE_WLAN = 2;
316 
317     /** @hide */
318     @Retention(RetentionPolicy.SOURCE)
319     @IntDef(prefix = {"KEY_TYPE_"}, value = {KEY_TYPE_EPDG, KEY_TYPE_WLAN})
320     public @interface KeyType {}
321 
322     /**
323      * No Single Radio Voice Call Continuity (SRVCC) handover is active.
324      * See TS 23.216 for more information.
325      * @hide
326      */
327     @SystemApi
328     public static final int SRVCC_STATE_HANDOVER_NONE  = -1;
329 
330     /**
331      * Single Radio Voice Call Continuity (SRVCC) handover has been started on the network.
332      * See TS 23.216 for more information.
333      * @hide
334      */
335     @SystemApi
336     public static final int SRVCC_STATE_HANDOVER_STARTED  = 0;
337 
338     /**
339      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has successfully completed.
340      * See TS 23.216 for more information.
341      * @hide
342      */
343     @SystemApi
344     public static final int SRVCC_STATE_HANDOVER_COMPLETED = 1;
345 
346     /**
347      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has failed.
348      * See TS 23.216 for more information.
349      * @hide
350      */
351     @SystemApi
352     public static final int SRVCC_STATE_HANDOVER_FAILED   = 2;
353 
354     /**
355      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has been canceled.
356      * See TS 23.216 for more information.
357      * @hide
358      */
359     @SystemApi
360     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
361 
362     /**
363      * Convert srvcc handover state to string.
364      *
365      * @param state The srvcc handover state.
366      * @return The srvcc handover state in string format.
367      *
368      * @hide
369      */
srvccStateToString(int state)370     public static @NonNull String srvccStateToString(int state) {
371         switch (state) {
372             case TelephonyManager.SRVCC_STATE_HANDOVER_NONE:
373                 return "NONE";
374             case TelephonyManager.SRVCC_STATE_HANDOVER_STARTED:
375                 return "STARTED";
376             case TelephonyManager.SRVCC_STATE_HANDOVER_COMPLETED:
377                 return "COMPLETED";
378             case TelephonyManager.SRVCC_STATE_HANDOVER_FAILED:
379                 return "FAILED";
380             case TelephonyManager.SRVCC_STATE_HANDOVER_CANCELED:
381                 return "CANCELED";
382             default:
383                 return "UNKNOWN(" + state + ")";
384         }
385     }
386 
387     /**
388      * A UICC card identifier used if the device does not support the operation.
389      * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
390      * eUICC, or the eUICC cannot be read.
391      */
392     public static final int UNSUPPORTED_CARD_ID = -1;
393 
394     /**
395      * A UICC card identifier used before the UICC card is loaded. See
396      * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
397      * <p>
398      * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
399      */
400     public static final int UNINITIALIZED_CARD_ID = -2;
401 
402     /**
403      * Default port index for a UICC.
404      *
405      * On physical SIM cards the only available port is 0.
406      * See {@link android.telephony.UiccPortInfo} for more information on ports.
407      *
408      * See {@link android.telephony.euicc.EuiccManager#isSimPortAvailable(int)} for information on
409      * how portIndex is used on eUICCs.
410      */
411     public static final int DEFAULT_PORT_INDEX = 0;
412 
413     /** @hide */
414     public static final int INVALID_PORT_INDEX = -1;
415 
416     /** @hide */
417     public static final String PROPERTY_ENABLE_NULL_CIPHER_TOGGLE = "enable_null_cipher_toggle";
418 
419     private final Context mContext;
420     private final int mSubId;
421     @UnsupportedAppUsage
422     private SubscriptionManager mSubscriptionManager;
423     private TelephonyScanManager mTelephonyScanManager;
424 
425     /** Cached service handles, cleared by resetServiceHandles() at death */
426     private static final Object sCacheLock = new Object();
427 
428     /** @hide */
429     private static boolean sServiceHandleCacheEnabled = true;
430 
431     @GuardedBy("sCacheLock")
432     private static ITelephony sITelephony;
433     @GuardedBy("sCacheLock")
434     private static IPhoneSubInfo sIPhoneSubInfo;
435     @GuardedBy("sCacheLock")
436     private static ISub sISub;
437     @GuardedBy("sCacheLock")
438     private static ISms sISms;
439     @GuardedBy("sCacheLock")
440     private static final DeathRecipient sServiceDeath = new DeathRecipient();
441 
442     /**
443      * Cache key for a {@link PropertyInvalidatedCache} which maps from {@link PhoneAccountHandle}
444      * to subscription Id.  The cache is initialized in {@code PhoneInterfaceManager}'s constructor
445      * when {@link PropertyInvalidatedCache#invalidateCache(String)} is called.
446      * The cache is cleared from {@code TelecomAccountRegistry#tearDown} when all phone accounts are
447      * removed from Telecom.
448      * @hide
449      */
450     public static final String CACHE_KEY_PHONE_ACCOUNT_TO_SUBID =
451             "cache_key.telephony.phone_account_to_subid";
452     private static final int CACHE_MAX_SIZE = 4;
453 
454     /**
455      * A {@link PropertyInvalidatedCache} which lives in an app's {@link TelephonyManager} instance.
456      * Caches any queries for a mapping between {@link PhoneAccountHandle} and {@code subscription
457      * id}.  The cache may be invalidated from Telephony when phone account re-registration takes
458      * place.
459      */
460     private PropertyInvalidatedCache<PhoneAccountHandle, Integer> mPhoneAccountHandleToSubIdCache =
461             new PropertyInvalidatedCache<PhoneAccountHandle, Integer>(CACHE_MAX_SIZE,
462                     CACHE_KEY_PHONE_ACCOUNT_TO_SUBID) {
463                 @Override
464                 public Integer recompute(PhoneAccountHandle phoneAccountHandle) {
465                     try {
466                         ITelephony telephony = getITelephony();
467                         if (telephony != null) {
468                             return telephony.getSubIdForPhoneAccountHandle(phoneAccountHandle,
469                                     mContext.getOpPackageName(), mContext.getAttributionTag());
470                         }
471                     } catch (RemoteException e) {
472                         throw e.rethrowAsRuntimeException();
473                     }
474                     return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
475                 }
476             };
477 
478     /** Enum indicating multisim variants
479      *  DSDS - Dual SIM Dual Standby
480      *  DSDA - Dual SIM Dual Active
481      *  TSTS - Triple SIM Triple Standby
482      **/
483     /** @hide */
484     @UnsupportedAppUsage(implicitMember =
485             "values()[Landroid/telephony/TelephonyManager$MultiSimVariants;")
486     public enum MultiSimVariants {
487         @UnsupportedAppUsage
488         DSDS,
489         @UnsupportedAppUsage
490         DSDA,
491         @UnsupportedAppUsage
492         TSTS,
493         @UnsupportedAppUsage
494         UNKNOWN
495     };
496 
497     /** @hide */
498     @UnsupportedAppUsage
TelephonyManager(Context context)499     public TelephonyManager(Context context) {
500       this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
501     }
502 
503     /** @hide */
504     @UnsupportedAppUsage
TelephonyManager(Context context, int subId)505     public TelephonyManager(Context context, int subId) {
506         mSubId = subId;
507         mContext = mergeAttributionAndRenouncedPermissions(context.getApplicationContext(),
508             context);
509         mSubscriptionManager = SubscriptionManager.from(mContext);
510     }
511 
512     /** @hide */
513     @UnsupportedAppUsage
TelephonyManager()514     private TelephonyManager() {
515         mContext = null;
516         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
517     }
518 
519     private static TelephonyManager sInstance = new TelephonyManager();
520 
521     /** @hide
522     /* @deprecated - use getSystemService as described above */
523     @Deprecated
524     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDefault()525     public static TelephonyManager getDefault() {
526         return sInstance;
527     }
528 
529     // This method takes the Application context and adds the attributionTag
530     // and renouncedPermissions from the given context.
mergeAttributionAndRenouncedPermissions(Context to, Context from)531     private Context mergeAttributionAndRenouncedPermissions(Context to, Context from) {
532         Context contextToReturn = from;
533         if (to != null) {
534             if (!Objects.equals(from.getAttributionTag(), to.getAttributionTag())) {
535                 contextToReturn = to.createAttributionContext(from.getAttributionTag());
536             } else {
537                 contextToReturn = to;
538             }
539 
540             Set<String> renouncedPermissions =
541                     from.getAttributionSource().getRenouncedPermissions();
542             if (!renouncedPermissions.isEmpty()) {
543                 if (to.getParams() != null) {
544                     contextToReturn = contextToReturn.createContext(
545                             new ContextParams.Builder(to.getParams())
546                                     .setRenouncedPermissions(renouncedPermissions).build());
547                 } else {
548                     contextToReturn = contextToReturn.createContext(
549                             new ContextParams.Builder()
550                                     .setRenouncedPermissions(renouncedPermissions).build());
551                 }
552             }
553         }
554         return contextToReturn;
555     }
556 
getOpPackageName()557     private String getOpPackageName() {
558         // For legacy reasons the TelephonyManager has API for getting
559         // a static instance with no context set preventing us from
560         // getting the op package name. As a workaround we do a best
561         // effort and get the context from the current activity thread.
562         if (mContext != null) {
563             return mContext.getOpPackageName();
564         } else {
565             ITelephony telephony = getITelephony();
566             if (telephony == null) return null;
567             try {
568                 return telephony.getCurrentPackageName();
569             } catch (RemoteException ex) {
570                 return null;
571             } catch (NullPointerException ex) {
572                 return null;
573             }
574         }
575     }
576 
getAttributionTag()577     private String getAttributionTag() {
578         // For legacy reasons the TelephonyManager has API for getting
579         // a static instance with no context set preventing us from
580         // getting the attribution tag.
581         if (mContext != null) {
582             return mContext.getAttributionTag();
583         }
584         return null;
585     }
586 
getRenouncedPermissions()587     private Set<String> getRenouncedPermissions() {
588         // For legacy reasons the TelephonyManager has API for getting
589         // a static instance with no context set preventing us from
590         // getting the attribution source.
591         if (mContext != null) {
592             return mContext.getAttributionSource().getRenouncedPermissions();
593         }
594         return Collections.emptySet();
595     }
596 
597     /**
598      * Post a runnable to the BackgroundThread.
599      *
600      * Used to invoke user callbacks without calling into the caller's executor from the caller's
601      * calling thread context, for example to provide asynchronous error information that is
602      * generated locally (not over a binder thread).
603      *
604      * <p>This is not necessary unless you are invoking caller's code asynchronously from within
605      * the caller's thread context.
606      *
607      * @param r a runnable.
608      */
runOnBackgroundThread(@onNull Runnable r)609     private static void runOnBackgroundThread(@NonNull Runnable r) {
610         try {
611             BackgroundThread.getExecutor().execute(r);
612         } catch (RejectedExecutionException e) {
613             throw new IllegalStateException(
614                     "Failed to post a callback from the caller's thread context.", e);
615         }
616     }
617 
618     /**
619      * Returns the multi SIM variant
620      * Returns DSDS for Dual SIM Dual Standby
621      * Returns DSDA for Dual SIM Dual Active
622      * Returns TSTS for Triple SIM Triple Standby
623      * Returns UNKNOWN for others
624      */
625     /** {@hide} */
626     @UnsupportedAppUsage
getMultiSimConfiguration()627     public MultiSimVariants getMultiSimConfiguration() {
628         String mSimConfig =
629                 TelephonyProperties.multi_sim_config().orElse("");
630         if (mSimConfig.equals("dsds")) {
631             return MultiSimVariants.DSDS;
632         } else if (mSimConfig.equals("dsda")) {
633             return MultiSimVariants.DSDA;
634         } else if (mSimConfig.equals("tsts")) {
635             return MultiSimVariants.TSTS;
636         } else {
637             return MultiSimVariants.UNKNOWN;
638         }
639     }
640 
641     /**
642      * Returns the number of phones available.
643      * Returns 0 if none of voice, sms, data is not supported
644      * Returns 1 for Single standby mode (Single SIM functionality).
645      * Returns 2 for Dual standby mode (Dual SIM functionality).
646      * Returns 3 for Tri standby mode (Tri SIM functionality).
647      * @deprecated Use {@link #getActiveModemCount} instead.
648      */
649     @Deprecated
getPhoneCount()650     public int getPhoneCount() {
651         return getActiveModemCount();
652     }
653 
654     /**
655      * Returns the number of logical modems currently configured to be activated.
656      *
657      * Returns 0 if none of voice, sms, data is not supported
658      * Returns 1 for Single standby mode (Single SIM functionality).
659      * Returns 2 for Dual standby mode (Dual SIM functionality).
660      * Returns 3 for Tri standby mode (Tri SIM functionality).
661      */
getActiveModemCount()662     public int getActiveModemCount() {
663         int modemCount = 1;
664         switch (getMultiSimConfiguration()) {
665             case UNKNOWN:
666                 modemCount = 1;
667                 // check for voice and data support, 0 if not supported
668                 if (!isVoiceCapable() && !isSmsCapable() && !isDataCapable()) {
669                     modemCount = 0;
670                 }
671                 break;
672             case DSDS:
673             case DSDA:
674                 modemCount = 2;
675                 break;
676             case TSTS:
677                 modemCount = 3;
678                 break;
679         }
680         return modemCount;
681     }
682 
683     /**
684      * Return how many logical modem can be potentially active simultaneously, in terms of hardware
685      * capability.
686      * It might return different value from {@link #getActiveModemCount}. For example, for a
687      * dual-SIM capable device operating in single SIM mode (only one logical modem is turned on),
688      * {@link #getActiveModemCount} returns 1 while this API returns 2.
689      */
getSupportedModemCount()690     public int getSupportedModemCount() {
691         return TelephonyProperties.max_active_modems().orElse(getActiveModemCount());
692     }
693 
694     /**
695      * Gets the maximum number of SIMs that can be active, based on the device's multisim
696      * configuration.
697      * @return 1 for single-SIM, DSDS, and TSTS devices. 2 for DSDA devices.
698      * @hide
699      */
700     @SystemApi
getMaxNumberOfSimultaneouslyActiveSims()701     public int getMaxNumberOfSimultaneouslyActiveSims() {
702         switch (getMultiSimConfiguration()) {
703             case UNKNOWN:
704             case DSDS:
705             case TSTS:
706                 return 1;
707             case DSDA:
708                 return 2;
709         }
710         return 1;
711     }
712 
713     /** {@hide} */
714     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)715     public static TelephonyManager from(Context context) {
716         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
717     }
718 
719     /**
720      * Create a new TelephonyManager object pinned to the given subscription ID.
721      *
722      * @return a TelephonyManager that uses the given subId for all calls.
723      */
createForSubscriptionId(int subId)724     public TelephonyManager createForSubscriptionId(int subId) {
725       // Don't reuse any TelephonyManager objects.
726       return new TelephonyManager(mContext, subId);
727     }
728 
729     /**
730      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
731      * phone account.
732      *
733      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
734      * if the phone account does not correspond to a valid subscription ID.
735      */
736     @Nullable
createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle)737     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
738         int subId = getSubscriptionId(phoneAccountHandle);
739         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
740             return null;
741         }
742         return new TelephonyManager(mContext, subId);
743     }
744 
745     /** {@hide} */
746     @UnsupportedAppUsage
isMultiSimEnabled()747     public boolean isMultiSimEnabled() {
748         return getPhoneCount() > 1;
749     }
750 
751     private static final int MAXIMUM_CALL_COMPOSER_PICTURE_SIZE = 80000;
752 
753     /**
754      * Indicates the maximum size of the call composure picture.
755      *
756      * Pictures sent via
757      * {@link #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)}
758      * or {@link #uploadCallComposerPicture(Path, String, Executor, OutcomeReceiver)} must not
759      * exceed this size, or an error will be returned via the callback in those methods.
760      *
761      * @return Maximum file size in bytes.
762      */
getMaximumCallComposerPictureSize()763     public static @BytesLong long getMaximumCallComposerPictureSize() {
764         return MAXIMUM_CALL_COMPOSER_PICTURE_SIZE;
765     }
766 
767     //
768     // Broadcast Intent actions
769     //
770 
771     /**
772      * Broadcast intent action indicating that the call state
773      * on the device has changed.
774      *
775      * <p>
776      * The {@link #EXTRA_STATE} extra indicates the new call state.
777      * If a receiving app has {@link android.Manifest.permission#READ_CALL_LOG} permission, a second
778      * extra {@link #EXTRA_INCOMING_NUMBER} provides the phone number for incoming and outgoing
779      * calls as a String.
780      * <p>
781      * If the receiving app has
782      * {@link android.Manifest.permission#READ_CALL_LOG} and
783      * {@link android.Manifest.permission#READ_PHONE_STATE} permission, it will receive the
784      * broadcast twice; one with the {@link #EXTRA_INCOMING_NUMBER} populated with the phone number,
785      * and another with it blank.  Due to the nature of broadcasts, you cannot assume the order
786      * in which these broadcasts will arrive, however you are guaranteed to receive two in this
787      * case.  Apps which are interested in the {@link #EXTRA_INCOMING_NUMBER} can ignore the
788      * broadcasts where {@link #EXTRA_INCOMING_NUMBER} is not present in the extras (e.g. where
789      * {@link Intent#hasExtra(String)} returns {@code false}).
790      * <p class="note">
791      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
792      * broadcast in version 1.0, but it is no longer sticky.
793      * Instead, use {@link #getCallState} to synchronously query the current call state.
794      *
795      * @see #EXTRA_STATE
796      * @see #EXTRA_INCOMING_NUMBER
797      * @see #getCallState
798      */
799     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
800     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
801     public static final String ACTION_PHONE_STATE_CHANGED =
802             "android.intent.action.PHONE_STATE";
803 
804     /**
805      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
806      * call. By default, the device's default SMS app consumes this message and sends a text message
807      * to the caller. A third party app can also provide this functionality by consuming this Intent
808      * with a {@link android.app.Service} and sending the message using its own messaging system.
809      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
810      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
811      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
812      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
813      * set of phone numbers if there are multiple recipients. For example, {@code
814      * smsto:2065551234}.</p>
815      *
816      * <p>The intent may also contain extras for the message text (in {@link
817      * android.content.Intent#EXTRA_TEXT}) and a message subject
818      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
819      *
820      * <p class="note"><strong>Note:</strong>
821      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
822      * that requires the
823      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
824      * <p>For example, the service that receives this intent can be declared in the manifest file
825      * with an intent filter like this:</p>
826      * <pre>
827      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
828      * &lt;service android:name=".HeadlessSmsSendService"
829      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
830      *          android:exported="true" >
831      *   &lt;intent-filter>
832      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
833      *     &lt;category android:name="android.intent.category.DEFAULT" />
834      *     &lt;data android:scheme="sms" />
835      *     &lt;data android:scheme="smsto" />
836      *     &lt;data android:scheme="mms" />
837      *     &lt;data android:scheme="mmsto" />
838      *   &lt;/intent-filter>
839      * &lt;/service></pre>
840      * <p>
841      * Output: nothing.
842      */
843     @SdkConstant(SdkConstantType.SERVICE_ACTION)
844     public static final String ACTION_RESPOND_VIA_MESSAGE =
845             "android.intent.action.RESPOND_VIA_MESSAGE";
846 
847     /**
848      * The emergency dialer may choose to present activities with intent filters for this
849      * action as emergency assistance buttons that launch the activity when clicked.
850      *
851      * @hide
852      */
853     @SystemApi
854     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
855     public static final String ACTION_EMERGENCY_ASSISTANCE =
856             "android.telephony.action.EMERGENCY_ASSISTANCE";
857 
858     /**
859      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
860      * call settings page launched by
861      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
862      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
863      * which would also like to manage voicemail settings should set this meta-data to {@code true}
864      * in the manifest registration of their application.
865      *
866      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
867      * @see #ACTION_CONFIGURE_VOICEMAIL
868      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
869      */
870     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
871             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
872 
873     /**
874      * Open the voicemail settings activity to make changes to voicemail configuration.
875      *
876      * <p>
877      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} to
878      * configure voicemail.
879      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
880      * API if set.
881      *
882      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
883      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
884      */
885     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
886     public static final String ACTION_CONFIGURE_VOICEMAIL =
887             "android.telephony.action.CONFIGURE_VOICEMAIL";
888 
889     /**
890      * The boolean value indicating whether the voicemail settings activity launched by {@link
891      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
892      * used by dialer implementations which provides their own voicemail settings UI, but still
893      * needs to expose device specific voicemail settings to the user.
894      *
895      * @see #ACTION_CONFIGURE_VOICEMAIL
896      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
897      */
898     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
899             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
900 
901     /**
902      * @hide
903      */
904     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
905 
906     /**
907      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
908      * for a String containing the new call state.
909      *
910      * <p class="note">
911      * Retrieve with
912      * {@link android.content.Intent#getStringExtra(String)}.
913      *
914      * @see #EXTRA_STATE_IDLE
915      * @see #EXTRA_STATE_RINGING
916      * @see #EXTRA_STATE_OFFHOOK
917      */
918     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
919 
920     /**
921      * Value used with {@link #EXTRA_STATE} corresponding to
922      * {@link #CALL_STATE_IDLE}.
923      */
924     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
925 
926     /**
927      * Value used with {@link #EXTRA_STATE} corresponding to
928      * {@link #CALL_STATE_RINGING}.
929      */
930     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
931 
932     /**
933      * Value used with {@link #EXTRA_STATE} corresponding to
934      * {@link #CALL_STATE_OFFHOOK}.
935      */
936     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
937 
938     /**
939      * Extra key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
940      * for a String containing the incoming or outgoing phone number.
941      * <p>
942      * This extra is only populated for receivers of the {@link #ACTION_PHONE_STATE_CHANGED}
943      * broadcast which have been granted the {@link android.Manifest.permission#READ_CALL_LOG} and
944      * {@link android.Manifest.permission#READ_PHONE_STATE} permissions.
945      * <p>
946      * For incoming calls, the phone number is only guaranteed to be populated when the
947      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_RINGING}.
948      * If the incoming caller is from an unknown number, the extra will be populated with an empty
949      * string.
950      * For outgoing calls, the phone number is only guaranteed to be populated when the
951      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_OFFHOOK}.
952      * <p class="note">
953      * Retrieve with
954      * {@link android.content.Intent#getStringExtra(String)}.
955      * <p>
956      *
957      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
958      * to retrieve the phone number for calls instead.  Apps performing call screening should use
959      * the {@link CallScreeningService} API instead.
960      */
961     @Deprecated
962     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
963 
964     /**
965      * Broadcast intent action indicating that call disconnect cause has changed.
966      *
967      * <p>
968      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
969      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
970      *
971      * <p class="note">
972      * Requires the READ_PRECISE_PHONE_STATE permission.
973      *
974      * @see #EXTRA_DISCONNECT_CAUSE
975      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
976      *
977      * @hide
978      */
979     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
980     public static final String ACTION_CALL_DISCONNECT_CAUSE_CHANGED =
981             "android.intent.action.CALL_DISCONNECT_CAUSE";
982 
983     /**
984      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
985      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
986      * containing the disconnect cause.
987      *
988      * @see DisconnectCause
989      *
990      * <p class="note">
991      * Retrieve with
992      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
993      *
994      * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
995      * @hide
996      */
997     @Deprecated
998     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
999 
1000     /**
1001      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
1002      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
1003      * containing the disconnect cause provided by the RIL.
1004      *
1005      * @see PreciseDisconnectCause
1006      *
1007      * <p class="note">
1008      * Retrieve with
1009      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
1010      *
1011      * @hide
1012      */
1013     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
1014 
1015     /**
1016      * Broadcast intent action for letting the default dialer to know to show voicemail
1017      * notification.
1018      *
1019      * <p>
1020      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
1021      * voicemail is received on.
1022      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
1023      * voicemails.
1024      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
1025      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
1026      * will call the voicemail number when sent. This extra will be empty if the voicemail number
1027      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
1028      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
1029      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
1030      * available when the voicemail number is not set.
1031      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
1032      * notification.
1033      *
1034      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
1035      * @see #EXTRA_NOTIFICATION_COUNT
1036      * @see #EXTRA_VOICEMAIL_NUMBER
1037      * @see #EXTRA_CALL_VOICEMAIL_INTENT
1038      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
1039      * @see #EXTRA_IS_REFRESH
1040      */
1041     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
1042             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
1043 
1044     /**
1045      * The extra used with an {@link #ACTION_CONFIGURE_VOICEMAIL} and
1046      * {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify the
1047      * {@link PhoneAccountHandle} the configuration or notification is for.
1048      * <p class="note">
1049      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
1050      */
1051     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
1052             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
1053 
1054     /**
1055      * The number of voice messages associated with the notification.
1056      */
1057     public static final String EXTRA_NOTIFICATION_COUNT =
1058             "android.telephony.extra.NOTIFICATION_COUNT";
1059 
1060     /**
1061      * The voicemail number.
1062      */
1063     public static final String EXTRA_VOICEMAIL_NUMBER =
1064             "android.telephony.extra.VOICEMAIL_NUMBER";
1065 
1066     /**
1067      * The intent to call voicemail.
1068      */
1069     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
1070             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
1071 
1072     /**
1073      * The intent to launch voicemail settings.
1074      */
1075     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
1076             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
1077 
1078     /**
1079      * Boolean value representing whether the {@link
1080      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
1081      * notification. Notification refresh happens after reboot or connectivity changes. The user has
1082      * already been notified for the voicemail so it should not alert the user, and should not be
1083      * shown again if the user has dismissed it.
1084      */
1085     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
1086 
1087     /**
1088      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
1089      * successfully handed over from WIFI to LTE.
1090      * <p>
1091      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1092      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1093      * @hide
1094      */
1095     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
1096             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
1097 
1098     /**
1099      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
1100      * successfully handed over from LTE to WIFI.
1101      * <p>
1102      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1103      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1104      * @hide
1105      */
1106     public static final String EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI =
1107             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI";
1108 
1109     /**
1110      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
1111      * handed over from LTE to WIFI.
1112      * <p>
1113      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1114      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1115      * @hide
1116      */
1117     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
1118             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
1119 
1120     /**
1121      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
1122      * audio because the data limit was reached.
1123      * <p>
1124      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1125      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1126      * @hide
1127      */
1128     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
1129             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
1130 
1131     /**
1132      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
1133      * audio because the data was disabled.
1134      * <p>
1135      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1136      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1137      * @hide
1138      */
1139     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
1140             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
1141 
1142     /**
1143      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
1144      * the user when an international call is placed while on WFC only.
1145      * <p>
1146      * Used when the carrier config value
1147      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
1148      * is on WFC (VoLTE not available) and an international number is dialed.
1149      * <p>
1150      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1151      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1152      * @hide
1153      */
1154     public static final String EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
1155             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
1156 
1157     /**
1158      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
1159      * forwarded to another number.
1160      * <p>
1161      * Sent in response to an IMS supplementary service notification indicating the call has been
1162      * forwarded.
1163      * <p>
1164      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1165      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1166      * @hide
1167      */
1168     public static final String EVENT_CALL_FORWARDED =
1169             "android.telephony.event.EVENT_CALL_FORWARDED";
1170 
1171     /**
1172      * {@link android.telecom.Connection} event used to indicate that a supplementary service
1173      * notification has been received.
1174      * <p>
1175      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1176      * The {@link Bundle} parameter is expected to include the following extras:
1177      * <ul>
1178      *     <li>{@link #EXTRA_NOTIFICATION_TYPE} - the notification type.</li>
1179      *     <li>{@link #EXTRA_NOTIFICATION_CODE} - the notification code.</li>
1180      *     <li>{@link #EXTRA_NOTIFICATION_MESSAGE} - human-readable message associated with the
1181      *     supplementary service notification.</li>
1182      * </ul>
1183      * @hide
1184      */
1185     public static final String EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION =
1186             "android.telephony.event.EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION";
1187 
1188     /**
1189      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1190      * the type of supplementary service notification which occurred.
1191      * Will be either
1192      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_1}
1193      * or
1194      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_2}
1195      * <p>
1196      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1197      * @hide
1198      */
1199     public static final String EXTRA_NOTIFICATION_TYPE =
1200             "android.telephony.extra.NOTIFICATION_TYPE";
1201 
1202     /**
1203      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1204      * the supplementary service notification which occurred.
1205      * <p>
1206      * Depending on the {@link #EXTRA_NOTIFICATION_TYPE}, the code will be one of the {@code CODE_*}
1207      * codes defined in {@link com.android.internal.telephony.gsm.SuppServiceNotification}.
1208      * <p>
1209      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1210      * @hide
1211      */
1212     public static final String EXTRA_NOTIFICATION_CODE =
1213             "android.telephony.extra.NOTIFICATION_CODE";
1214 
1215     /**
1216      * {@link CharSequence} extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION}
1217      * which contains a human-readable message which can be displayed to the user for the
1218      * supplementary service notification.
1219      * <p>
1220      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1221      * @hide
1222      */
1223     public static final String EXTRA_NOTIFICATION_MESSAGE =
1224             "android.telephony.extra.NOTIFICATION_MESSAGE";
1225 
1226     /* Visual voicemail protocols */
1227 
1228     /**
1229      * The OMTP protocol.
1230      */
1231     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
1232 
1233     /**
1234      * A flavor of OMTP protocol with a different mobile originated (MO) format
1235      */
1236     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
1237 
1238     /**
1239      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
1240      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
1241      * setting, this key will not exist.
1242      *
1243      * @see #getVisualVoicemailSettings()
1244      * @hide
1245      */
1246     @SystemApi
1247     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
1248             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
1249 
1250     /**
1251      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
1252      * access PIN scrambled during the auto provisioning process. The user is expected to reset
1253      * their PIN if this value is not {@code null}.
1254      *
1255      * @see #getVisualVoicemailSettings()
1256      * @hide
1257      */
1258     @SystemApi
1259     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
1260             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
1261 
1262     /**
1263      * Broadcast action to be received by Broadcast receivers.
1264      *
1265      * Indicates multi-SIM configuration is changed. For example, it changed
1266      * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
1267      *
1268      * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
1269      * or that all steps during multi-SIM change are done. To know those information you still need
1270      * to listen to SIM_STATE changes or active subscription changes.
1271      *
1272      * See extra of {@link #EXTRA_ACTIVE_SIM_SUPPORTED_COUNT} for updated value.
1273      */
1274     public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
1275             "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
1276 
1277 
1278     /**
1279      * The number of active SIM supported by current multi-SIM config. It's not related to how many
1280      * SIM/subscriptions are currently active.
1281      *
1282      * Same value will be returned by {@link #getActiveModemCount()}.
1283      *
1284      * For single SIM mode, it's 1.
1285      * For DSDS or DSDA mode, it's 2.
1286      * For triple-SIM mode, it's 3.
1287      *
1288      * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
1289      *
1290      * type: integer
1291      */
1292     public static final String EXTRA_ACTIVE_SIM_SUPPORTED_COUNT =
1293             "android.telephony.extra.ACTIVE_SIM_SUPPORTED_COUNT";
1294 
1295     /**
1296      * @hide
1297      */
1298     public static final String USSD_RESPONSE = "USSD_RESPONSE";
1299 
1300     /**
1301      * USSD return code success.
1302      * @hide
1303      */
1304     public static final int USSD_RETURN_SUCCESS = 100;
1305 
1306     /**
1307      * Failed code returned when the mobile network has failed to complete a USSD request.
1308      * <p>
1309      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1310      * TelephonyManager, String, int)}.
1311      */
1312     public static final int USSD_RETURN_FAILURE = -1;
1313 
1314     /**
1315      * Failure code returned when a USSD request has failed to execute because the Telephony
1316      * service is unavailable.
1317      * <p>
1318      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1319      * TelephonyManager, String, int)}.
1320      */
1321     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
1322 
1323     /**
1324      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which leaves the roaming
1325      * mode set to the radio default or to the user's preference if they've indicated one.
1326      */
1327     public static final int CDMA_ROAMING_MODE_RADIO_DEFAULT = -1;
1328     /**
1329      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which only permits
1330      * connections on home networks.
1331      */
1332     public static final int CDMA_ROAMING_MODE_HOME = 0;
1333     /**
1334      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1335      * affiliated networks.
1336      */
1337     public static final int CDMA_ROAMING_MODE_AFFILIATED = 1;
1338     /**
1339      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1340      * any network.
1341      */
1342     public static final int CDMA_ROAMING_MODE_ANY = 2;
1343 
1344     /** @hide */
1345     @IntDef(prefix = { "CDMA_ROAMING_MODE_" }, value = {
1346             CDMA_ROAMING_MODE_RADIO_DEFAULT,
1347             CDMA_ROAMING_MODE_HOME,
1348             CDMA_ROAMING_MODE_AFFILIATED,
1349             CDMA_ROAMING_MODE_ANY
1350     })
1351     @Retention(RetentionPolicy.SOURCE)
1352     public @interface CdmaRoamingMode{}
1353 
1354     /**
1355      * An unknown carrier id. It could either be subscription unavailable or the subscription
1356      * carrier cannot be recognized. Unrecognized carriers here means
1357      * {@link #getSimOperator() MCC+MNC} cannot be identified.
1358      */
1359     public static final int UNKNOWN_CARRIER_ID = -1;
1360 
1361     /**
1362      * An unknown carrier id list version.
1363      * @hide
1364      */
1365     @TestApi
1366     public static final int UNKNOWN_CARRIER_ID_LIST_VERSION = -1;
1367 
1368     /**
1369      * Broadcast Action: The subscription carrier identity has changed.
1370      * This intent could be sent on the following events:
1371      * <ul>
1372      *   <li>Subscription absent. Carrier identity could change from a valid id to
1373      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID}.</li>
1374      *   <li>Subscription loaded. Carrier identity could change from
1375      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID} to a valid id.</li>
1376      *   <li>The subscription carrier is recognized after a remote update.</li>
1377      * </ul>
1378      * The intent will have the following extra values:
1379      * <ul>
1380      *   <li>{@link #EXTRA_CARRIER_ID} The up-to-date carrier id of the current subscription id.
1381      *   </li>
1382      *   <li>{@link #EXTRA_CARRIER_NAME} The up-to-date carrier name of the current subscription.
1383      *   </li>
1384      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1385      *   identity.
1386      *   </li>
1387      * </ul>
1388      * <p class="note">This is a protected intent that can only be sent by the system.
1389      */
1390     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1391     public static final String ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED =
1392             "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED";
1393 
1394     /**
1395      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which indicates
1396      * the updated carrier id returned by {@link TelephonyManager#getSimCarrierId()}.
1397      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1398      * the carrier cannot be identified.
1399      */
1400     public static final String EXTRA_CARRIER_ID = "android.telephony.extra.CARRIER_ID";
1401 
1402     /**
1403      * An string extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which
1404      * indicates the updated carrier name of the current subscription.
1405      * @see TelephonyManager#getSimCarrierIdName()
1406      * <p>Carrier name is a user-facing name of the carrier id {@link #EXTRA_CARRIER_ID},
1407      * usually the brand name of the subsidiary (e.g. T-Mobile).
1408      */
1409     public static final String EXTRA_CARRIER_NAME = "android.telephony.extra.CARRIER_NAME";
1410 
1411     /**
1412      * Broadcast Action: The subscription specific carrier identity has changed.
1413      *
1414      * A specific carrier ID returns the fine-grained carrier ID of the current subscription.
1415      * It can represent the fact that a carrier may be in effect an aggregation of other carriers
1416      * (ie in an MVNO type scenario) where each of these specific carriers which are used to make
1417      * up the actual carrier service may have different carrier configurations.
1418      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
1419      * different carrier configuration for different service offering such as a prepaid plan.
1420      *
1421      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
1422      * about the carrier itself should use the regular carrier ID returned by
1423      * {@link #getSimCarrierId()}.
1424      *
1425      * <p>Similar like {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED}, this intent will be
1426      * sent on the event of {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} while its also
1427      * possible to be sent without {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} when
1428      * specific carrier ID changes while carrier ID remains the same.
1429      * e.g, the same subscription switches to different IMSI could potentially change its
1430      * specific carrier ID while carrier id remains the same.
1431      * @see #getSimSpecificCarrierId()
1432      * @see #getSimCarrierId()
1433      *
1434      * The intent will have the following extra values:
1435      * <ul>
1436      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_ID} The up-to-date specific carrier id of the
1437      *   current subscription.
1438      *   </li>
1439      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_NAME} The up-to-date name of the specific carrier id.
1440      *   </li>
1441      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1442      *   identity.
1443      *   </li>
1444      * </ul>
1445      * <p class="note">This is a protected intent that can only be sent by the system.
1446      */
1447     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1448     public static final String ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED =
1449             "android.telephony.action.SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED";
1450 
1451     /**
1452      * An int extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED} which
1453      * indicates the updated specific carrier id returned by
1454      * {@link TelephonyManager#getSimSpecificCarrierId()}. Note, its possible specific carrier id
1455      * changes while {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} remains the same
1456      * e.g, when subscription switch to different IMSIs.
1457      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1458      * the carrier cannot be identified.
1459      */
1460     public static final String EXTRA_SPECIFIC_CARRIER_ID =
1461             "android.telephony.extra.SPECIFIC_CARRIER_ID";
1462 
1463     /**
1464      * An string extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED}
1465      * which indicates the updated specific carrier name returned by
1466      * {@link TelephonyManager#getSimSpecificCarrierIdName()}.
1467      * <p>it's a user-facing name of the specific carrier id {@link #EXTRA_SPECIFIC_CARRIER_ID}
1468      * e.g, Tracfone-AT&T
1469      */
1470     public static final String EXTRA_SPECIFIC_CARRIER_NAME =
1471             "android.telephony.extra.SPECIFIC_CARRIER_NAME";
1472 
1473     /**
1474      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} to indicate the
1475      * subscription which has changed; or in general whenever a subscription ID needs specified.
1476      */
1477     public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
1478 
1479     /**
1480      * Broadcast Action: The Service Provider string(s) have been updated. Activities or
1481      * services that use these strings should update their display.
1482      *
1483      * <p>The intent will have the following extra values:
1484      * <dl>
1485      *   <dt>{@link #EXTRA_SHOW_PLMN}</dt>
1486      *   <dd>Boolean that indicates whether the PLMN should be shown.</dd>
1487      *   <dt>{@link #EXTRA_PLMN}</dt>
1488      *   <dd>The operator name of the registered network, as a string.</dd>
1489      *   <dt>{@link #EXTRA_SHOW_SPN}</dt>
1490      *   <dd>Boolean that indicates whether the SPN should be shown.</dd>
1491      *   <dt>{@link #EXTRA_SPN}</dt>
1492      *   <dd>The service provider name, as a string.</dd>
1493      *   <dt>{@link #EXTRA_DATA_SPN}</dt>
1494      *   <dd>The service provider name for data service, as a string.</dd>
1495      * </dl>
1496      *
1497      * Note that {@link #EXTRA_SHOW_PLMN} may indicate that {@link #EXTRA_PLMN} should be displayed,
1498      * even though the value for {@link #EXTRA_PLMN} is null. This can happen, for example, if the
1499      * phone has not registered to a network yet. In this case the receiver may substitute an
1500      * appropriate placeholder string (eg, "No service").
1501      *
1502      * It is recommended to display {@link #EXTRA_PLMN} before / above {@link #EXTRA_SPN} if
1503      * both are displayed.
1504      *
1505      * <p>Note: this is a protected intent that can only be sent by the system.
1506      * @hide
1507      */
1508     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1509     public static final String ACTION_SERVICE_PROVIDERS_UPDATED =
1510             "android.telephony.action.SERVICE_PROVIDERS_UPDATED";
1511 
1512     /**
1513      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1514      * whether the PLMN should be shown.
1515      * @hide
1516      */
1517     public static final String EXTRA_SHOW_PLMN = "android.telephony.extra.SHOW_PLMN";
1518 
1519     /**
1520      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1521      * the operator name of the registered network.
1522      * @hide
1523      */
1524     public static final String EXTRA_PLMN = "android.telephony.extra.PLMN";
1525 
1526     /**
1527      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1528      * whether the PLMN should be shown.
1529      * @hide
1530      */
1531     public static final String EXTRA_SHOW_SPN = "android.telephony.extra.SHOW_SPN";
1532 
1533     /**
1534      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1535      * the service provider name.
1536      * @hide
1537      */
1538     public static final String EXTRA_SPN = "android.telephony.extra.SPN";
1539 
1540     /**
1541      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1542      * the service provider name for data service.
1543      * @hide
1544      */
1545     public static final String EXTRA_DATA_SPN = "android.telephony.extra.DATA_SPN";
1546 
1547     /**
1548      * Broadcast intent action indicating that when data stall recovery is attempted by Telephony,
1549      * intended for report every data stall recovery step attempted.
1550      *
1551      * <p>
1552      * The {@link #EXTRA_RECOVERY_ACTION} extra indicates the action associated with the data
1553      * stall recovery.
1554      * The phone id where the data stall recovery is attempted.
1555      *
1556      * <p class="note">
1557      * Requires the READ_PHONE_STATE permission.
1558      *
1559      * <p class="note">
1560      * This is a protected intent that can only be sent by the system.
1561      *
1562      * @see #EXTRA_RECOVERY_ACTION
1563      *
1564      * @hide
1565      */
1566     // TODO(b/78370030) : Restrict this to system applications only
1567     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1568     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1569     public static final String ACTION_DATA_STALL_DETECTED =
1570             "android.intent.action.DATA_STALL_DETECTED";
1571 
1572     /**
1573      * A service action that identifies
1574      * a {@link android.service.carrier.CarrierMessagingClientService} subclass in the
1575      * AndroidManifest.xml.
1576      *
1577      * <p>See {@link android.service.carrier.CarrierMessagingClientService} for the details.
1578      */
1579     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1580     public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE =
1581             "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
1582 
1583     /**
1584      * An int extra used with {@link #ACTION_DATA_STALL_DETECTED} to indicate the
1585      * action associated with the data stall recovery.
1586      *
1587      * @see #ACTION_DATA_STALL_DETECTED
1588      *
1589      * @hide
1590      */
1591     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
1592 
1593     private static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000;
1594 
1595     /**
1596      * Intent sent when an error occurs that debug tools should log and possibly take further
1597      * action such as capturing vendor-specific logs.
1598      *
1599      * A privileged application that reads these events should take appropriate vendor-specific
1600      * action to record the event and collect further information to assist in analysis, debugging,
1601      * and resolution of any associated issue.
1602      *
1603      * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
1604      * should generally be sent at a low rate. Instead, this mechanism should be used for the
1605      * framework to notify a debugging application that an event (such as a bug) has occured
1606      * within the framework if that event should trigger the collection and preservation of other
1607      * more detailed device state for debugging.
1608      *
1609      * <p>At most one application can receive these events and should register a receiver in
1610      * in the application manifest. For performance reasons, if no application to receive these
1611      * events is detected at boot, then these events will not be sent.
1612      *
1613      * <p>Each event will include an {@link EXTRA_ANOMALY_ID} that will uniquely identify the
1614      * event that has occurred. Each event will be sent to the diagnostic monitor only once per
1615      * boot cycle (as another optimization).
1616      *
1617      * @see #EXTRA_ANOMALY_ID
1618      * @see #EXTRA_ANOMALY_DESCRIPTION
1619      * @hide
1620      */
1621     @SystemApi
1622     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1623     public static final String ACTION_ANOMALY_REPORTED =
1624             "android.telephony.action.ANOMALY_REPORTED";
1625 
1626     /**
1627      * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
1628      *
1629      * This field must be included in all {@link ACTION_ANOMALY_REPORTED} events.
1630      *
1631      * @see #ACTION_ANOMALY_REPORTED
1632      * @hide
1633      */
1634     @SystemApi
1635     public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
1636 
1637     /**
1638      * A freeform string description of the Anomaly.
1639      *
1640      * This field is optional for all {@link ACTION_ANOMALY_REPORTED}s, as a guideline should not
1641      * exceed 80 characters, and should be as short as possible to convey the essence of the event.
1642      *
1643      * @see #ACTION_ANOMALY_REPORTED
1644      * @hide
1645      */
1646     @SystemApi
1647     public static final String EXTRA_ANOMALY_DESCRIPTION =
1648             "android.telephony.extra.ANOMALY_DESCRIPTION";
1649 
1650     /**
1651      * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
1652      *
1653      * @hide
1654      */
1655     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1656     public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
1657             "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
1658 
1659     /**
1660      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1661      * to indicate what type of SIM selection is needed.
1662      *
1663      * @hide
1664      */
1665     public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
1666             "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
1667 
1668     /** @hide */
1669     @IntDef({
1670             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE,
1671             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
1672             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE,
1673             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS,
1674             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL
1675     })
1676     @Retention(RetentionPolicy.SOURCE)
1677     public @interface DefaultSubscriptionSelectType{}
1678 
1679     /**
1680      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1681      * to indicate there's no need to re-select any default subscription.
1682      * @hide
1683      */
1684     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
1685 
1686     /**
1687      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1688      * to indicate there's a need to select default data subscription.
1689      * @hide
1690      */
1691     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
1692 
1693     /**
1694      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1695      * to indicate there's a need to select default voice call subscription.
1696      * @hide
1697      */
1698     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
1699 
1700     /**
1701      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1702      * to indicate there's a need to select default sms subscription.
1703      * @hide
1704      */
1705     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
1706 
1707     /**
1708      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1709      * to indicate user to decide whether current SIM should be preferred for all
1710      * data / voice / sms. {@link #EXTRA_SUBSCRIPTION_ID} will specified to indicate
1711      * which subscription should be the default subscription.
1712      * @hide
1713      */
1714     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL = 4;
1715 
1716     /**
1717      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1718      * to indicate that default subscription for data/sms/voice is now determined, that
1719      * it should dismiss any dialog or pop-ups that is asking user to select default sub.
1720      * This is used when, for example, opportunistic subscription is configured. At that
1721      * time the primary becomes default sub there's no need to ask user to select anymore.
1722      * @hide
1723      */
1724     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS = 5;
1725 
1726     /**
1727      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1728      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1729      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1730      *
1731      * @hide
1732      */
1733     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1734             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1735 
1736     /** @hide */
1737     @IntDef({
1738             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1739             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1740     })
1741     @Retention(RetentionPolicy.SOURCE)
1742     public @interface SimCombinationWarningType{}
1743 
1744     /**
1745      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1746      * to indicate there's no SIM combination warning.
1747      * @hide
1748      */
1749     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1750 
1751     /**
1752      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1753      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1754      * @hide
1755      */
1756     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1757 
1758     /**
1759      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1760      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1761      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1762      * name will be "operator1 & operator2".
1763      *
1764      * @hide
1765      */
1766     public static final String EXTRA_SIM_COMBINATION_NAMES =
1767             "android.telephony.extra.SIM_COMBINATION_NAMES";
1768 
1769     /**
1770      * <p>Broadcast Action: The emergency callback mode is changed.
1771      * <ul>
1772      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1773      *   false=ECM off</li>
1774      * </ul>
1775      * <p class="note">
1776      * You can <em>not</em> receive this through components declared
1777      * in manifests, only by explicitly registering for it with
1778      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1779      * android.content.IntentFilter) Context.registerReceiver()}.
1780      *
1781      * <p class="note">This is a protected intent that can only be sent by the system.
1782      *
1783      * @see #EXTRA_PHONE_IN_ECM_STATE
1784      *
1785      * @hide
1786      */
1787     @SystemApi
1788     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1789     @SuppressLint("ActionValue")
1790     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1791             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1792 
1793 
1794     /**
1795      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1796      * Indicates whether the phone is in an emergency phone state.
1797      *
1798      * @hide
1799      */
1800     @SystemApi
1801     public static final String EXTRA_PHONE_IN_ECM_STATE =
1802             "android.telephony.extra.PHONE_IN_ECM_STATE";
1803 
1804     /**
1805      * Broadcast action sent when a data connection is redirected with validation failure.
1806      *
1807      * This action is intended for sim/account status checks and only sent to the carrier apps
1808      * specified in the carrier config for the subscription ID that's attached to this intent.
1809      *
1810      * The intent will have the following extra values:
1811      * <ul>
1812      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1813      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>A string indicating the redirection url</dd>
1814      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1815      *          <dd>The subscription ID on which the validation failure happened.</dd>
1816      * </ul>
1817      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1818      */
1819     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1820     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1821             "android.telephony.action.CARRIER_SIGNAL_REDIRECTED";
1822 
1823     /**
1824      * Broadcast action sent when a data connection setup fails.
1825      *
1826      * This action is intended for sim/account status checks and only sent to the carrier apps
1827      * specified in the carrier config for the subscription ID that's attached to this intent.
1828      *
1829      * The intent will have the following extra values:
1830      * <ul>
1831      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1832      *   <li>{@link #EXTRA_DATA_FAIL_CAUSE}</li><dd>A integer indicating the data fail cause.</dd>
1833      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1834      *          <dd>The subscription ID on which the data setup failure happened.</dd>
1835      * </ul>
1836      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1837      */
1838     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1839     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1840             "android.telephony.action.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1841 
1842     /**
1843      * Broadcast action sent when a PCO value becomes available from the modem.
1844      *
1845      * This action is intended for sim/account status checks and only sent to the carrier apps
1846      * specified in the carrier config for the subscription ID that's attached to this intent.
1847      *
1848      * The intent will have the following extra values:</p>
1849      * <ul>
1850      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1851      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>An integer indicating the protocol of the apn
1852      *      connection</dd>
1853      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the PCO id for the data.</dd>
1854      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of PCO data read from modem.</dd>
1855      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1856      *          <dd>The subscription ID for which the PCO info was received.</dd>
1857      * </ul>
1858      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1859      */
1860     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1861     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1862             "android.telephony.action.CARRIER_SIGNAL_PCO_VALUE";
1863 
1864     /**
1865      * Broadcast action sent when the availability of the system default network changes.
1866      *
1867      * @see ConnectivityManager#registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)
1868      *
1869      * This action is intended for carrier apps to set/reset carrier actions. It is only sent to the
1870      * carrier apps specified in the carrier config for the subscription ID attached to this intent.
1871      *
1872      * The intent will have the following extra values:</p>
1873      * <ul>
1874      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1875      *   <dd>{@code true} if the default network is now available, {@code false} otherwise.</dd>
1876      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1877      *          <dd>The subscription ID on which the default network availability changed.</dd>
1878      * </ul>
1879      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1880      */
1881     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1882     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1883             "android.telephony.action.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1884 
1885     /**
1886      * Broadcast action sent when carrier apps should reset their internal state.
1887      *
1888      * Sent when certain events such as turning on/off mobile data, removing the SIM, etc. require
1889      * carrier apps to reset their state.
1890      *
1891      * This action is intended to signal carrier apps to perform cleanup operations. It is only sent
1892      * to the carrier apps specified in the carrier config for the subscription ID attached to
1893      * this intent.
1894      *
1895      * The intent will have the following extra values:</p>
1896      * <ul>
1897      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1898      *          <dd>The subscription ID for which state should be reset.</dd>
1899      * </ul>
1900      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1901      */
1902     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1903     public static final String ACTION_CARRIER_SIGNAL_RESET =
1904             "android.telephony.action.CARRIER_SIGNAL_RESET";
1905 
1906     /**
1907      * String extra containing the redirection URL sent with
1908      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
1909      */
1910     public static final String EXTRA_REDIRECTION_URL = "android.telephony.extra.REDIRECTION_URL";
1911 
1912     /**
1913      * An integer extra containing the data fail cause.
1914      *
1915      * Sent with {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}. See {@link DataFailCause}
1916      * for a list of possible values.
1917      */
1918     public static final String EXTRA_DATA_FAIL_CAUSE = "android.telephony.extra.DATA_FAIL_CAUSE";
1919 
1920     /**
1921      * An integer extra containing the APN type.
1922      *
1923      * Sent with the  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1924      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}, and {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE}
1925      * broadcasts.
1926      * See the {@code TYPE_} constants in {@link ApnSetting} for a list of possible values.
1927      */
1928     public static final String EXTRA_APN_TYPE = "android.telephony.extra.APN_TYPE";
1929 
1930     /**
1931      * An integer extra containing the protocol of the apn connection.
1932      *
1933      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
1934      * See the {@code PROTOCOL_*} constants in {@link ApnSetting} for a list of possible values.
1935      */
1936     public static final String EXTRA_APN_PROTOCOL = "android.telephony.extra.APN_PROTOCOL";
1937 
1938     /**
1939      * An integer extra indicating the ID for the PCO data.
1940      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
1941      */
1942     public static final String EXTRA_PCO_ID = "android.telephony.extra.PCO_ID";
1943 
1944     /**
1945      * A byte array extra containing PCO data read from the modem.
1946      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
1947      */
1948     public static final String EXTRA_PCO_VALUE = "android.telephony.extra.PCO_VALUE";
1949 
1950     /**
1951      * A boolean extra indicating the availability of the default network.
1952      * Sent with the {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcast.
1953      */
1954     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE =
1955             "android.telephony.extra.DEFAULT_NETWORK_AVAILABLE";
1956 
1957     /**
1958      * <p>Broadcast Action: The emergency call state is changed.
1959      * <ul>
1960      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
1961      *   call, false otherwise</li>
1962      * </ul>
1963      * <p class="note">
1964      * You can <em>not</em> receive this through components declared
1965      * in manifests, only by explicitly registering for it with
1966      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1967      * android.content.IntentFilter) Context.registerReceiver()}.
1968      *
1969      * <p class="note">This is a protected intent that can only be sent by the system.
1970      *
1971      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
1972      *
1973      * @hide
1974      */
1975     @SystemApi
1976     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1977     @SuppressLint("ActionValue")
1978     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
1979             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
1980 
1981 
1982     /**
1983      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
1984      * It indicates whether the phone is making an emergency call.
1985      *
1986      * @hide
1987      */
1988     @SystemApi
1989     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
1990             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
1991 
1992     /**
1993      * <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
1994      * <p class="note">.
1995      * This is to pop up a notice to show user that the phone is in emergency callback mode
1996      * and data calls and outgoing sms are blocked.
1997      *
1998      * <p class="note">This is a protected intent that can only be sent by the system.
1999      *
2000      * @hide
2001      */
2002     @SystemApi
2003     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS =
2004             "android.telephony.action.SHOW_NOTICE_ECM_BLOCK_OTHERS";
2005 
2006     /**
2007      * Broadcast Action: The default data subscription has changed in a multi-SIM device.
2008      * This has the following extra values:</p>
2009      * <ul>
2010      *   <li><em>subscription</em> - A int, the current data default subscription.</li>
2011      * </ul>
2012      *
2013      * @hide
2014      */
2015     @SystemApi
2016     @SuppressLint("ActionValue")
2017     public static final String ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED =
2018             "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED";
2019 
2020     /**
2021      * Broadcast Action: The default voice subscription has changed in a mult-SIm device.
2022      * This has the following extra values:</p>
2023      * <ul>
2024      *   <li><em>subscription</em> - A int, the current voice default subscription.</li>
2025      * </ul>
2026      *
2027      * @hide
2028      */
2029     @SystemApi
2030     @SuppressLint("ActionValue")
2031     public static final String ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED =
2032             "android.intent.action.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED";
2033 
2034     /**
2035      * Broadcast Action: This triggers a client initiated OMA-DM session to the OMA server.
2036      * <p class="note">
2037      * Open Mobile Alliance (OMA) Device Management (DM).
2038      *
2039      * This intent is used by the system components to trigger OMA-DM
2040      *
2041      * @hide
2042      */
2043     @SystemApi
2044     @SuppressLint("ActionValue")
2045     public static final String ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE =
2046             "com.android.omadm.service.CONFIGURATION_UPDATE";
2047 
2048     //
2049     //
2050     // Device Info
2051     //
2052     //
2053 
2054     /**
2055      * Returns the software version number for the device, for example,
2056      * the IMEI/SV for GSM phones. Return null if the software version is
2057      * not available.
2058      * <p>
2059      */
2060     @RequiresPermission(anyOf = {
2061             android.Manifest.permission.READ_PHONE_STATE,
2062             android.Manifest.permission.READ_BASIC_PHONE_STATE})
2063     @Nullable
getDeviceSoftwareVersion()2064     public String getDeviceSoftwareVersion() {
2065         return getDeviceSoftwareVersion(getSlotIndex());
2066     }
2067 
2068     /**
2069      * Returns the software version number for the device, for example,
2070      * the IMEI/SV for GSM phones. Return null if the software version is
2071      * not available.
2072      * <p>
2073      * Requires Permission: READ_PHONE_STATE.
2074      *
2075      * @param slotIndex of which deviceID is returned
2076      *
2077      * @hide
2078      */
2079     @SystemApi
2080     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2081     @Nullable
getDeviceSoftwareVersion(int slotIndex)2082     public String getDeviceSoftwareVersion(int slotIndex) {
2083         ITelephony telephony = getITelephony();
2084         if (telephony == null) return null;
2085 
2086         try {
2087             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
2088                     getAttributionTag());
2089         } catch (RemoteException ex) {
2090             return null;
2091         } catch (NullPointerException ex) {
2092             return null;
2093         }
2094     }
2095 
2096     /**
2097      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
2098      * or ESN for CDMA phones. Return null if device ID is not available.
2099      *
2100      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2101      * restrictions, and apps are recommended to use resettable identifiers (see <a
2102      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2103      * method can be invoked if one of the following requirements is met:
2104      * <ul>
2105      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2106      *     is a privileged permission that can only be granted to apps preloaded on the device.
2107      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2108      *     owner of an organization-owned device, or their delegates (see {@link
2109      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2110      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2111      *     active subscription.
2112      *     <li>If the calling app is the default SMS role holder (see {@link
2113      *     RoleManager#isRoleHeld(String)}).
2114      * </ul>
2115      *
2116      * <p>If the calling app does not meet one of these requirements then this method will behave
2117      * as follows:
2118      *
2119      * <ul>
2120      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2121      *     READ_PHONE_STATE permission then null is returned.</li>
2122      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2123      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2124      *     higher, then a SecurityException is thrown.</li>
2125      * </ul>
2126      *
2127      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2128      * MEID for CDMA.
2129      */
2130     @Deprecated
2131     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2132     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()2133     public String getDeviceId() {
2134         try {
2135             ITelephony telephony = getITelephony();
2136             if (telephony == null)
2137                 return null;
2138             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
2139                     mContext.getAttributionTag());
2140         } catch (RemoteException ex) {
2141             return null;
2142         } catch (NullPointerException ex) {
2143             return null;
2144         }
2145     }
2146 
2147     /**
2148      * Returns the unique device ID of a subscription, for example, the IMEI for
2149      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
2150      *
2151      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2152      * restrictions, and apps are recommended to use resettable identifiers (see <a
2153      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2154      * method can be invoked if one of the following requirements is met:
2155      * <ul>
2156      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2157      *     is a privileged permission that can only be granted to apps preloaded on the device.
2158      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2159      *     owner of an organization-owned device, or their delegates (see {@link
2160      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2161      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2162      *     active subscription.
2163      *     <li>If the calling app is the default SMS role holder (see {@link
2164      *     RoleManager#isRoleHeld(String)}).
2165      * </ul>
2166      *
2167      * <p>If the calling app does not meet one of these requirements then this method will behave
2168      * as follows:
2169      *
2170      * <ul>
2171      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2172      *     READ_PHONE_STATE permission then null is returned.</li>
2173      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2174      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2175      *     higher, then a SecurityException is thrown.</li>
2176      * </ul>
2177      *
2178      * @param slotIndex of which deviceID is returned
2179      *
2180      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2181      * MEID for CDMA.
2182      */
2183     @Deprecated
2184     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2185     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)2186     public String getDeviceId(int slotIndex) {
2187         // FIXME this assumes phoneId == slotIndex
2188         try {
2189             IPhoneSubInfo info = getSubscriberInfoService();
2190             if (info == null)
2191                 return null;
2192             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
2193                     mContext.getAttributionTag());
2194         } catch (RemoteException ex) {
2195             return null;
2196         } catch (NullPointerException ex) {
2197             return null;
2198         }
2199     }
2200 
2201     /**
2202      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2203      * available.
2204      *
2205      * See {@link #getImei(int)} for details on the required permissions and behavior
2206      * when the caller does not hold sufficient permissions.
2207      */
2208     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2209     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2210     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
getImei()2211     public String getImei() {
2212         return getImei(getSlotIndex());
2213     }
2214 
2215     /**
2216      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2217      * available.
2218      *
2219      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2220      * restrictions, and apps are recommended to use resettable identifiers (see <a
2221      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2222      * method can be invoked if one of the following requirements is met:
2223      * <ul>
2224      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2225      *     is a privileged permission that can only be granted to apps preloaded on the device.
2226      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2227      *     owner of an organization-owned device, or their delegates (see {@link
2228      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2229      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2230      *     active subscription.
2231      *     <li>If the calling app is the default SMS role holder (see {@link
2232      *     RoleManager#isRoleHeld(String)}).
2233      *     <li>If the calling app has been granted the
2234      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
2235      * </ul>
2236      *
2237      * <p>If the calling app does not meet one of these requirements then this method will behave
2238      * as follows:
2239      *
2240      * <ul>
2241      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2242      *     READ_PHONE_STATE permission then null is returned.</li>
2243      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2244      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2245      *     higher, then a SecurityException is thrown.</li>
2246      * </ul>
2247      *
2248      * @param slotIndex of which IMEI is returned
2249      */
2250     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2251     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2252     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
getImei(int slotIndex)2253     public String getImei(int slotIndex) {
2254         ITelephony telephony = getITelephony();
2255         if (telephony == null) return null;
2256 
2257         try {
2258             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
2259         } catch (RemoteException ex) {
2260             return null;
2261         } catch (NullPointerException ex) {
2262             return null;
2263         }
2264     }
2265 
2266     /**
2267      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2268      * available.
2269      */
2270     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
2271     @Nullable
getTypeAllocationCode()2272     public String getTypeAllocationCode() {
2273         return getTypeAllocationCode(getSlotIndex());
2274     }
2275 
2276     /**
2277      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2278      * available.
2279      *
2280      * @param slotIndex of which Type Allocation Code is returned
2281      */
2282     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
2283     @Nullable
getTypeAllocationCode(int slotIndex)2284     public String getTypeAllocationCode(int slotIndex) {
2285         ITelephony telephony = getITelephony();
2286         if (telephony == null) return null;
2287 
2288         try {
2289             return telephony.getTypeAllocationCodeForSlot(slotIndex);
2290         } catch (RemoteException ex) {
2291             return null;
2292         } catch (NullPointerException ex) {
2293             return null;
2294         }
2295     }
2296 
2297     /**
2298      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2299      *
2300      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2301      * restrictions, and apps are recommended to use resettable identifiers (see <a
2302      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2303      * method can be invoked if one of the following requirements is met:
2304      * <ul>
2305      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2306      *     is a privileged permission that can only be granted to apps preloaded on the device.
2307      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2308      *     owner of an organization-owned device, or their delegates (see {@link
2309      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2310      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2311      *     active subscription.
2312      *     <li>If the calling app is the default SMS role holder (see {@link
2313      *     RoleManager#isRoleHeld(String)}).
2314      * </ul>
2315      *
2316      * <p>If the calling app does not meet one of these requirements then this method will behave
2317      * as follows:
2318      *
2319      * <ul>
2320      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2321      *     READ_PHONE_STATE permission then null is returned.</li>
2322      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2323      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2324      *     higher, then a SecurityException is thrown.</li>
2325      * </ul>
2326      */
2327     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2328     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2329     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getMeid()2330     public String getMeid() {
2331         return getMeid(getSlotIndex());
2332     }
2333 
2334     /**
2335      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2336      *
2337      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2338      * restrictions, and apps are recommended to use resettable identifiers (see <a
2339      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2340      * method can be invoked if one of the following requirements is met:
2341      * <ul>
2342      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2343      *     is a privileged permission that can only be granted to apps preloaded on the device.
2344      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2345      *     owner of an organization-owned device, or their delegates (see {@link
2346      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2347      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2348      *     active subscription.
2349      *     <li>If the calling app is the default SMS role holder (see {@link
2350      *     RoleManager#isRoleHeld(String)}).
2351      * </ul>
2352      *
2353      * <p>If the calling app does not meet one of these requirements then this method will behave
2354      * as follows:
2355      *
2356      * <ul>
2357      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2358      *     READ_PHONE_STATE permission then null is returned.</li>
2359      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2360      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2361      *     higher, then a SecurityException is thrown.</li>
2362      * </ul>
2363      *
2364      * @param slotIndex of which MEID is returned
2365      */
2366     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2367     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2368     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getMeid(int slotIndex)2369     public String getMeid(int slotIndex) {
2370         ITelephony telephony = getITelephony();
2371         if (telephony == null) return null;
2372 
2373         try {
2374             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
2375                     getAttributionTag());
2376             if (TextUtils.isEmpty(meid)) {
2377                 Log.d(TAG, "getMeid: return null because MEID is not available");
2378                 return null;
2379             }
2380             return meid;
2381         } catch (RemoteException ex) {
2382             return null;
2383         } catch (NullPointerException ex) {
2384             return null;
2385         }
2386     }
2387 
2388     /**
2389      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2390      * available.
2391      */
2392     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
2393     @Nullable
getManufacturerCode()2394     public String getManufacturerCode() {
2395         return getManufacturerCode(getSlotIndex());
2396     }
2397 
2398     /**
2399      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2400      * available.
2401      *
2402      * @param slotIndex of which Type Allocation Code is returned
2403      */
2404     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
2405     @Nullable
getManufacturerCode(int slotIndex)2406     public String getManufacturerCode(int slotIndex) {
2407         ITelephony telephony = getITelephony();
2408         if (telephony == null) return null;
2409 
2410         try {
2411             return telephony.getManufacturerCodeForSlot(slotIndex);
2412         } catch (RemoteException ex) {
2413             return null;
2414         } catch (NullPointerException ex) {
2415             return null;
2416         }
2417     }
2418 
2419     /**
2420      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2421      *
2422      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2423      * restrictions, and apps are recommended to use resettable identifiers (see <a
2424      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2425      * method can be invoked if one of the following requirements is met:
2426      * <ul>
2427      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2428      *     is a privileged permission that can only be granted to apps preloaded on the device.
2429      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2430      *     owner of an organization-owned device, or their delegates (see {@link
2431      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2432      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2433      *     <li>If the calling app is the default SMS role holder (see {@link
2434      *     RoleManager#isRoleHeld(String)}).
2435      * </ul>
2436      *
2437      * <p>If the calling app does not meet one of these requirements then this method will behave
2438      * as follows:
2439      *
2440      * <ul>
2441      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2442      *     READ_PHONE_STATE permission then null is returned.</li>
2443      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2444      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2445      *     higher, then a SecurityException is thrown.</li>
2446      * </ul>
2447      */
2448     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2449     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2450     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getNai()2451     public String getNai() {
2452         return getNaiBySubscriberId(getSubId());
2453     }
2454 
getNaiBySubscriberId(int subId)2455     private String getNaiBySubscriberId(int subId) {
2456         try {
2457             IPhoneSubInfo info = getSubscriberInfoService();
2458             if (info == null)
2459                 return null;
2460             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2461                     mContext.getAttributionTag());
2462             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2463                 Rlog.v(TAG, "Nai = " + nai);
2464             }
2465             return nai;
2466         } catch (RemoteException ex) {
2467             return null;
2468         } catch (NullPointerException ex) {
2469             return null;
2470         }
2471     }
2472 
2473     /**
2474      * Returns the current location of the device.
2475      *<p>
2476      * If there is only one radio in the device and that radio has an LTE connection,
2477      * this method will return null. The implementation must not to try add LTE
2478      * identifiers into the existing cdma/gsm classes.
2479      *<p>
2480      * @return Current location of the device or null if not available.
2481      *
2482      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2483      */
2484     @Deprecated
2485     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getCellLocation()2486     public CellLocation getCellLocation() {
2487         try {
2488             ITelephony telephony = getITelephony();
2489             if (telephony == null) {
2490                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2491                 return null;
2492             }
2493 
2494             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2495                     mContext.getAttributionTag());
2496             CellLocation cl = cellIdentity.asCellLocation();
2497             if (cl == null || cl.isEmpty()) {
2498                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2499                         + " phone type doesn't match CellLocation type");
2500                 return null;
2501             }
2502 
2503             return cl;
2504         } catch (RemoteException ex) {
2505             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2506             return null;
2507         }
2508     }
2509 
2510     /**
2511      * Returns the neighboring cell information of the device.
2512      *
2513      * @return List of NeighboringCellInfo or null if info unavailable.
2514      *
2515      * @removed
2516      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2517      *             from NeighboringCellInfo, including LTE cell information.
2518      */
2519     @Deprecated
2520     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
getNeighboringCellInfo()2521     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2522         try {
2523             ITelephony telephony = getITelephony();
2524             if (telephony == null)
2525                 return null;
2526             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2527                     mContext.getAttributionTag());
2528         } catch (RemoteException ex) {
2529             return null;
2530         } catch (NullPointerException ex) {
2531             return null;
2532         }
2533     }
2534 
2535     /** No phone radio. */
2536     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2537     /** Phone radio is GSM. */
2538     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2539     /** Phone radio is CDMA. */
2540     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2541     /** Phone is via SIP. */
2542     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2543 
2544     /**
2545      * Phone is via IMS.
2546      *
2547      * @hide
2548      */
2549     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2550 
2551     /**
2552      * Phone is via Third Party.
2553      *
2554      * @hide
2555      */
2556     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2557 
2558     /**
2559      * Returns the current phone type.
2560      * TODO: This is a last minute change and hence hidden.
2561      *
2562      * @see #PHONE_TYPE_NONE
2563      * @see #PHONE_TYPE_GSM
2564      * @see #PHONE_TYPE_CDMA
2565      * @see #PHONE_TYPE_SIP
2566      *
2567      * {@hide}
2568      */
2569     @SystemApi
getCurrentPhoneType()2570     public int getCurrentPhoneType() {
2571         return getCurrentPhoneType(getSubId());
2572     }
2573 
2574     /**
2575      * Returns a constant indicating the device phone type for a subscription.
2576      *
2577      * @see #PHONE_TYPE_NONE
2578      * @see #PHONE_TYPE_GSM
2579      * @see #PHONE_TYPE_CDMA
2580      *
2581      * @param subId for which phone type is returned
2582      * @hide
2583      */
2584     @SystemApi
getCurrentPhoneType(int subId)2585     public int getCurrentPhoneType(int subId) {
2586         int phoneId;
2587         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2588             // if we don't have any sims, we don't have subscriptions, but we
2589             // still may want to know what type of phone we've got.
2590             phoneId = 0;
2591         } else {
2592             phoneId = SubscriptionManager.getPhoneId(subId);
2593         }
2594 
2595         return getCurrentPhoneTypeForSlot(phoneId);
2596     }
2597 
2598     /**
2599      * See getCurrentPhoneType.
2600      *
2601      * @hide
2602      */
getCurrentPhoneTypeForSlot(int slotIndex)2603     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2604         try{
2605             ITelephony telephony = getITelephony();
2606             if (telephony != null) {
2607                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2608             } else {
2609                 // This can happen when the ITelephony interface is not up yet.
2610                 return getPhoneTypeFromProperty(slotIndex);
2611             }
2612         } catch (RemoteException ex) {
2613             // This shouldn't happen in the normal case, as a backup we
2614             // read from the system property.
2615             return getPhoneTypeFromProperty(slotIndex);
2616         } catch (NullPointerException ex) {
2617             // This shouldn't happen in the normal case, as a backup we
2618             // read from the system property.
2619             return getPhoneTypeFromProperty(slotIndex);
2620         }
2621     }
2622 
2623     /**
2624      * Returns a constant indicating the device phone type.  This
2625      * indicates the type of radio used to transmit voice calls.
2626      *
2627      * @see #PHONE_TYPE_NONE
2628      * @see #PHONE_TYPE_GSM
2629      * @see #PHONE_TYPE_CDMA
2630      * @see #PHONE_TYPE_SIP
2631      */
getPhoneType()2632     public int getPhoneType() {
2633         if (!isVoiceCapable()) {
2634             return PHONE_TYPE_NONE;
2635         }
2636         return getCurrentPhoneType();
2637     }
2638 
getPhoneTypeFromProperty()2639     private int getPhoneTypeFromProperty() {
2640         return getPhoneTypeFromProperty(getPhoneId());
2641     }
2642 
2643     /** {@hide} */
2644     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2645     private int getPhoneTypeFromProperty(int phoneId) {
2646         Integer type = getTelephonyProperty(
2647                 phoneId, TelephonyProperties.current_active_phone(), null);
2648         if (type != null) return type;
2649         return getPhoneTypeFromNetworkType(phoneId);
2650     }
2651 
getPhoneTypeFromNetworkType()2652     private int getPhoneTypeFromNetworkType() {
2653         return getPhoneTypeFromNetworkType(getPhoneId());
2654     }
2655 
2656     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2657     private int getPhoneTypeFromNetworkType(int phoneId) {
2658         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2659         // use the system property for default network type.
2660         // This is a fail safe, and can only happen at first boot.
2661         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2662         if (mode != null) {
2663             return TelephonyManager.getPhoneType(mode);
2664         }
2665         return TelephonyManager.PHONE_TYPE_NONE;
2666     }
2667 
2668     /**
2669      * This function returns the type of the phone, depending
2670      * on the network mode.
2671      *
2672      * @param networkMode
2673      * @return Phone Type
2674      *
2675      * @hide
2676      */
2677     @UnsupportedAppUsage
getPhoneType(int networkMode)2678     public static int getPhoneType(int networkMode) {
2679         switch(networkMode) {
2680         case RILConstants.NETWORK_MODE_CDMA:
2681         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2682         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2683             return PhoneConstants.PHONE_TYPE_CDMA;
2684 
2685         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2686         case RILConstants.NETWORK_MODE_GSM_ONLY:
2687         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2688         case RILConstants.NETWORK_MODE_GSM_UMTS:
2689         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2690         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2691         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2692         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2693         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2694         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2695         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2696         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2697         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2698         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2699         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2700         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2701             return PhoneConstants.PHONE_TYPE_GSM;
2702 
2703         // Use CDMA Phone for the global mode including CDMA
2704         case RILConstants.NETWORK_MODE_GLOBAL:
2705         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2706         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2707             return PhoneConstants.PHONE_TYPE_CDMA;
2708 
2709         case RILConstants.NETWORK_MODE_LTE_ONLY:
2710             if (TelephonyProperties.lte_on_cdma_device().orElse(
2711                     PhoneConstants.LTE_ON_CDMA_FALSE) == PhoneConstants.LTE_ON_CDMA_TRUE) {
2712                 return PhoneConstants.PHONE_TYPE_CDMA;
2713             } else {
2714                 return PhoneConstants.PHONE_TYPE_GSM;
2715             }
2716         default:
2717             return PhoneConstants.PHONE_TYPE_GSM;
2718         }
2719     }
2720 
2721     /**
2722      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2723      * @hide
2724      */
2725     @SystemApi
getMaxNumberVerificationTimeoutMillis()2726     public static long getMaxNumberVerificationTimeoutMillis() {
2727         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2728     }
2729 
2730     //
2731     //
2732     // Current Network
2733     //
2734     //
2735 
2736     /**
2737      * Returns the alphabetic name of current registered operator.
2738      * <p>
2739      * Availability: Only when user is registered to a network. Result may be
2740      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2741      * on a CDMA network).
2742      */
2743     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkOperatorName()2744     public String getNetworkOperatorName() {
2745         return getNetworkOperatorName(getSubId());
2746     }
2747 
2748     /**
2749      * Returns the alphabetic name of current registered operator
2750      * for a particular subscription.
2751      * <p>
2752      * Availability: Only when user is registered to a network. Result may be
2753      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2754      * on a CDMA network).
2755      * @param subId
2756      * @hide
2757      */
2758     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2759     public String getNetworkOperatorName(int subId) {
2760         int phoneId = SubscriptionManager.getPhoneId(subId);
2761         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2762     }
2763 
2764     /**
2765      * Returns the numeric name (MCC+MNC) of current registered operator.
2766      * <p>
2767      * Availability: Only when user is registered to a network. Result may be
2768      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2769      * on a CDMA network).
2770      */
2771     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkOperator()2772     public String getNetworkOperator() {
2773         return getNetworkOperatorForPhone(getPhoneId());
2774     }
2775 
2776     /**
2777      * Returns the numeric name (MCC+MNC) of current registered operator
2778      * for a particular subscription.
2779      * <p>
2780      * Availability: Only when user is registered to a network. Result may be
2781      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2782      * on a CDMA network).
2783      *
2784      * @param subId
2785      * @hide
2786      */
2787     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2788     public String getNetworkOperator(int subId) {
2789         int phoneId = SubscriptionManager.getPhoneId(subId);
2790         return getNetworkOperatorForPhone(phoneId);
2791      }
2792 
2793     /**
2794      * Returns the numeric name (MCC+MNC) of current registered operator
2795      * for a particular subscription.
2796      * <p>
2797      * Availability: Only when user is registered to a network. Result may be
2798      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2799      * on a CDMA network).
2800      *
2801      * @param phoneId
2802      * @hide
2803      **/
2804     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2805     public String getNetworkOperatorForPhone(int phoneId) {
2806         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2807     }
2808 
2809 
2810     /**
2811      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2812      * network specifier is used by {@link
2813      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2814      * android.net.NetworkRequest} that connects through the subscription.
2815      *
2816      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2817      * @see #createForSubscriptionId(int)
2818      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2819      */
2820     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getNetworkSpecifier()2821     public String getNetworkSpecifier() {
2822         return String.valueOf(getSubId());
2823     }
2824 
2825     /**
2826      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
2827      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
2828      * default values.
2829      *
2830      * <p>This method may take several seconds to complete, so it should only be called from a
2831      * worker thread.
2832      *
2833      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2834      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2835      *
2836      * @see CarrierConfigManager#getConfigForSubId(int)
2837      * @see #createForSubscriptionId(int)
2838      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2839      */
2840     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2841     @WorkerThread
2842     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2843     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierConfig()2844     public PersistableBundle getCarrierConfig() {
2845         CarrierConfigManager carrierConfigManager = mContext
2846                 .getSystemService(CarrierConfigManager.class);
2847         return carrierConfigManager.getConfigForSubId(getSubId());
2848     }
2849 
2850     /**
2851      * Returns true if the device is considered roaming on the current
2852      * network, for GSM purposes.
2853      * <p>
2854      * Availability: Only when user registered to a network.
2855      */
2856     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isNetworkRoaming()2857     public boolean isNetworkRoaming() {
2858         return isNetworkRoaming(getSubId());
2859     }
2860 
2861     /**
2862      * Returns true if the device is considered roaming on the current
2863      * network for a subscription.
2864      * <p>
2865      * Availability: Only when user registered to a network.
2866      *
2867      * @param subId
2868      * @hide
2869      */
2870     @UnsupportedAppUsage
isNetworkRoaming(int subId)2871     public boolean isNetworkRoaming(int subId) {
2872         int phoneId = SubscriptionManager.getPhoneId(subId);
2873         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
2874     }
2875 
2876     /**
2877      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2878      * the current registered operator or the cell nearby, if available.
2879      *
2880      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2881      * if on a CDMA network).
2882      * <p>
2883      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2884      * available.
2885      */
2886     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkCountryIso()2887     public String getNetworkCountryIso() {
2888         return getNetworkCountryIso(getSlotIndex());
2889     }
2890 
2891     /**
2892      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2893      * the current registered operator or the cell nearby, if available. This is same as
2894      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
2895      * accessing network country info from the SIM slot that does not have SIM inserted.
2896      *
2897      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2898      * if on a CDMA network).
2899      * <p>
2900      *
2901      * @param slotIndex the SIM slot index to get network country ISO.
2902      *
2903      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2904      * available.
2905      *
2906      * @throws IllegalArgumentException when the slotIndex is invalid.
2907      *
2908      */
2909     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
2910     @NonNull
getNetworkCountryIso(int slotIndex)2911     public String getNetworkCountryIso(int slotIndex) {
2912         try {
2913             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
2914                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
2915                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
2916             }
2917 
2918             ITelephony telephony = getITelephony();
2919             if (telephony == null) return "";
2920             return telephony.getNetworkCountryIsoForPhone(slotIndex);
2921         } catch (RemoteException ex) {
2922             return "";
2923         }
2924     }
2925 
2926     /**
2927      * @hide
2928      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
2929      */
2930     @Deprecated
2931     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
2932             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)2933     public String getNetworkCountryIsoForPhone(int phoneId) {
2934         return getNetworkCountryIso(phoneId);
2935     }
2936 
2937     /*
2938      * When adding a network type to the list below, make sure to add the correct icon to
2939      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
2940      * Do not add negative types.
2941      */
2942     /** Network type is unknown */
2943     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
2944     /** Current network is GPRS */
2945     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
2946     /** Current network is EDGE */
2947     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
2948     /** Current network is UMTS */
2949     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
2950     /** Current network is CDMA: Either IS95A or IS95B*/
2951     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
2952     /** Current network is EVDO revision 0*/
2953     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
2954     /** Current network is EVDO revision A*/
2955     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
2956     /** Current network is 1xRTT*/
2957     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
2958     /** Current network is HSDPA */
2959     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
2960     /** Current network is HSUPA */
2961     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
2962     /** Current network is HSPA */
2963     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
2964     /**
2965      * Current network is iDen
2966      * @deprecated Legacy network type no longer being used starting in Android U.
2967      */
2968     @Deprecated
2969     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
2970     /** Current network is EVDO revision B*/
2971     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
2972     /** Current network is LTE */
2973     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
2974     /** Current network is eHRPD */
2975     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
2976     /** Current network is HSPA+ */
2977     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
2978     /** Current network is GSM */
2979     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
2980     /** Current network is TD_SCDMA */
2981     public static final int NETWORK_TYPE_TD_SCDMA =
2982             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
2983     /** Current network is IWLAN */
2984     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
2985     /** Current network is LTE_CA {@hide} */
2986     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2987     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
2988     /**
2989      * Current network is NR (New Radio) 5G.
2990      * This will only be returned for 5G SA.
2991      * For 5G NSA, the network type will be {@link #NETWORK_TYPE_LTE}.
2992      */
2993     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
2994 
2995     private static final @NetworkType int[] NETWORK_TYPES = {
2996             NETWORK_TYPE_GPRS,
2997             NETWORK_TYPE_EDGE,
2998             NETWORK_TYPE_UMTS,
2999             NETWORK_TYPE_CDMA,
3000             NETWORK_TYPE_EVDO_0,
3001             NETWORK_TYPE_EVDO_A,
3002             NETWORK_TYPE_1xRTT,
3003             NETWORK_TYPE_HSDPA,
3004             NETWORK_TYPE_HSUPA,
3005             NETWORK_TYPE_HSPA,
3006             NETWORK_TYPE_IDEN,
3007             NETWORK_TYPE_EVDO_B,
3008             NETWORK_TYPE_LTE,
3009             NETWORK_TYPE_EHRPD,
3010             NETWORK_TYPE_HSPAP,
3011             NETWORK_TYPE_GSM,
3012             NETWORK_TYPE_TD_SCDMA,
3013             NETWORK_TYPE_IWLAN,
3014             NETWORK_TYPE_LTE_CA,
3015             NETWORK_TYPE_NR
3016     };
3017 
3018     /**
3019      * Returns an array of all valid network types.
3020      *
3021      * @return An integer array containing all valid network types in no particular order.
3022      *
3023      * @hide
3024      */
3025     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getAllNetworkTypes()3026     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
3027         return NETWORK_TYPES.clone();
3028     }
3029 
3030     /**
3031      * Return the current data network type.
3032      *
3033      * @deprecated use {@link #getDataNetworkType()}
3034      * @return the NETWORK_TYPE_xxxx for current data connection.
3035      */
3036     @Deprecated
3037     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNetworkType()3038     public @NetworkType int getNetworkType() {
3039         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3040     }
3041 
3042     /**
3043      * Returns a constant indicating the radio technology (network type)
3044      * currently in use on the device for a subscription.
3045      * @return the network type
3046      *
3047      * @param subId for which network type is returned
3048      *
3049      * @see #NETWORK_TYPE_UNKNOWN
3050      * @see #NETWORK_TYPE_GPRS
3051      * @see #NETWORK_TYPE_EDGE
3052      * @see #NETWORK_TYPE_UMTS
3053      * @see #NETWORK_TYPE_HSDPA
3054      * @see #NETWORK_TYPE_HSUPA
3055      * @see #NETWORK_TYPE_HSPA
3056      * @see #NETWORK_TYPE_CDMA
3057      * @see #NETWORK_TYPE_EVDO_0
3058      * @see #NETWORK_TYPE_EVDO_A
3059      * @see #NETWORK_TYPE_EVDO_B
3060      * @see #NETWORK_TYPE_1xRTT
3061      * @see #NETWORK_TYPE_IDEN
3062      * @see #NETWORK_TYPE_LTE
3063      * @see #NETWORK_TYPE_EHRPD
3064      * @see #NETWORK_TYPE_HSPAP
3065      * @see #NETWORK_TYPE_NR
3066      *
3067      * @hide
3068      */
3069     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3070     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)3071     public int getNetworkType(int subId) {
3072         try {
3073             ITelephony telephony = getITelephony();
3074             if (telephony != null) {
3075                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
3076                         getAttributionTag());
3077             } else {
3078                 // This can happen when the ITelephony interface is not up yet.
3079                 return NETWORK_TYPE_UNKNOWN;
3080             }
3081         } catch (RemoteException ex) {
3082             // This shouldn't happen in the normal case
3083             return NETWORK_TYPE_UNKNOWN;
3084         } catch (NullPointerException ex) {
3085             // This could happen before phone restarts due to crashing
3086             return NETWORK_TYPE_UNKNOWN;
3087         }
3088     }
3089 
3090     /**
3091      * Returns a constant indicating the radio technology (network type)
3092      * currently in use on the device for data transmission.
3093      *
3094      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
3095      * subId. Otherwise, applies to {@link SubscriptionManager#getActiveDataSubscriptionId()}.
3096      *
3097      * Note: Before {@link SubscriptionManager#getActiveDataSubscriptionId()} was introduced in API
3098      * level 30, it was applied to {@link SubscriptionManager#getDefaultDataSubscriptionId()} which
3099      * may be different now from {@link SubscriptionManager#getActiveDataSubscriptionId()}, e.g.
3100      * when opportunistic network is providing cellular internet connection to the user.
3101      *
3102      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3103      * or {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
3104      * READ_BASIC_PHONE_STATE} or that the calling app has carrier privileges
3105      * (see {@link #hasCarrierPrivileges}).
3106      *
3107      * @return the network type
3108      *
3109      * @see #NETWORK_TYPE_UNKNOWN
3110      * @see #NETWORK_TYPE_GPRS
3111      * @see #NETWORK_TYPE_EDGE
3112      * @see #NETWORK_TYPE_UMTS
3113      * @see #NETWORK_TYPE_HSDPA
3114      * @see #NETWORK_TYPE_HSUPA
3115      * @see #NETWORK_TYPE_HSPA
3116      * @see #NETWORK_TYPE_CDMA
3117      * @see #NETWORK_TYPE_EVDO_0
3118      * @see #NETWORK_TYPE_EVDO_A
3119      * @see #NETWORK_TYPE_EVDO_B
3120      * @see #NETWORK_TYPE_1xRTT
3121      * @see #NETWORK_TYPE_IDEN
3122      * @see #NETWORK_TYPE_LTE
3123      * @see #NETWORK_TYPE_EHRPD
3124      * @see #NETWORK_TYPE_HSPAP
3125      * @see #NETWORK_TYPE_NR
3126      */
3127     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3128     @RequiresPermission(anyOf = {
3129             android.Manifest.permission.READ_PHONE_STATE,
3130             android.Manifest.permission.READ_BASIC_PHONE_STATE})
3131     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataNetworkType()3132     public @NetworkType int getDataNetworkType() {
3133         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3134     }
3135 
3136     /**
3137      * Returns a constant indicating the radio technology (network type)
3138      * currently in use on the device for data transmission for a subscription
3139      * @return the network type
3140      *
3141      * @param subId for which network type is returned
3142      * @hide
3143      */
3144     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3145     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)3146     public int getDataNetworkType(int subId) {
3147         try{
3148             ITelephony telephony = getITelephony();
3149             if (telephony != null) {
3150                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
3151                         getAttributionTag());
3152             } else {
3153                 // This can happen when the ITelephony interface is not up yet.
3154                 return NETWORK_TYPE_UNKNOWN;
3155             }
3156         } catch(RemoteException ex) {
3157             // This shouldn't happen in the normal case
3158             return NETWORK_TYPE_UNKNOWN;
3159         } catch (NullPointerException ex) {
3160             // This could happen before phone restarts due to crashing
3161             return NETWORK_TYPE_UNKNOWN;
3162         }
3163     }
3164 
3165     /**
3166      * Returns the NETWORK_TYPE_xxxx for voice
3167      *
3168      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3169      * or {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
3170      * READ_BASIC_PHONE_STATE} or that the calling app has carrier privileges
3171      * (see {@link #hasCarrierPrivileges}).
3172      */
3173     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3174     @RequiresPermission(anyOf = {
3175             android.Manifest.permission.READ_PHONE_STATE,
3176             android.Manifest.permission.READ_BASIC_PHONE_STATE})
3177     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceNetworkType()3178     public @NetworkType int getVoiceNetworkType() {
3179         return getVoiceNetworkType(getSubId());
3180     }
3181 
3182     /**
3183      * Returns the NETWORK_TYPE_xxxx for voice for a subId
3184      * @hide
3185      */
3186     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3187     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)3188     public int getVoiceNetworkType(int subId) {
3189         try{
3190             ITelephony telephony = getITelephony();
3191             if (telephony != null) {
3192                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
3193                         getAttributionTag());
3194             } else {
3195                 // This can happen when the ITelephony interface is not up yet.
3196                 return NETWORK_TYPE_UNKNOWN;
3197             }
3198         } catch(RemoteException ex) {
3199             // This shouldn't happen in the normal case
3200             return NETWORK_TYPE_UNKNOWN;
3201         } catch (NullPointerException ex) {
3202             // This could happen before phone restarts due to crashing
3203             return NETWORK_TYPE_UNKNOWN;
3204         }
3205     }
3206 
3207     /**
3208      * Returns a string representation of the radio technology (network type)
3209      * currently in use on the device.
3210      * @return the name of the radio technology
3211      *
3212      * @hide pending API council review
3213      */
3214     @UnsupportedAppUsage
getNetworkTypeName()3215     public String getNetworkTypeName() {
3216         return getNetworkTypeName(getNetworkType());
3217     }
3218 
3219     /**
3220      * Returns a string representation of the radio technology (network type)
3221      * currently in use on the device.
3222      * @param subId for which network type is returned
3223      * @return the name of the radio technology
3224      *
3225      */
3226     /** {@hide} */
3227     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)3228     public static String getNetworkTypeName(@NetworkType int type) {
3229         switch (type) {
3230             case NETWORK_TYPE_GPRS:
3231                 return "GPRS";
3232             case NETWORK_TYPE_EDGE:
3233                 return "EDGE";
3234             case NETWORK_TYPE_UMTS:
3235                 return "UMTS";
3236             case NETWORK_TYPE_HSDPA:
3237                 return "HSDPA";
3238             case NETWORK_TYPE_HSUPA:
3239                 return "HSUPA";
3240             case NETWORK_TYPE_HSPA:
3241                 return "HSPA";
3242             case NETWORK_TYPE_CDMA:
3243                 return "CDMA";
3244             case NETWORK_TYPE_EVDO_0:
3245                 return "CDMA - EvDo rev. 0";
3246             case NETWORK_TYPE_EVDO_A:
3247                 return "CDMA - EvDo rev. A";
3248             case NETWORK_TYPE_EVDO_B:
3249                 return "CDMA - EvDo rev. B";
3250             case NETWORK_TYPE_1xRTT:
3251                 return "CDMA - 1xRTT";
3252             case NETWORK_TYPE_LTE:
3253                 return "LTE";
3254             case NETWORK_TYPE_EHRPD:
3255                 return "CDMA - eHRPD";
3256             case NETWORK_TYPE_IDEN:
3257                 return "iDEN";
3258             case NETWORK_TYPE_HSPAP:
3259                 return "HSPA+";
3260             case NETWORK_TYPE_GSM:
3261                 return "GSM";
3262             case NETWORK_TYPE_TD_SCDMA:
3263                 return "TD_SCDMA";
3264             case NETWORK_TYPE_IWLAN:
3265                 return "IWLAN";
3266             case NETWORK_TYPE_LTE_CA:
3267                 return "LTE_CA";
3268             case NETWORK_TYPE_NR:
3269                 return "NR";
3270             case NETWORK_TYPE_UNKNOWN:
3271                 return "UNKNOWN";
3272             default:
3273                 return "UNKNOWN(" + type + ")";
3274         }
3275     }
3276 
3277     /**
3278      * Returns the bitmask for a given technology (network type)
3279      * @param networkType for which bitmask is returned
3280      * @return the network type bitmask
3281      * {@hide}
3282      */
getBitMaskForNetworkType(@etworkType int networkType)3283     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
3284         switch(networkType) {
3285             case NETWORK_TYPE_GSM:
3286                 return NETWORK_TYPE_BITMASK_GSM;
3287             case NETWORK_TYPE_GPRS:
3288                 return NETWORK_TYPE_BITMASK_GPRS;
3289             case NETWORK_TYPE_EDGE:
3290                 return NETWORK_TYPE_BITMASK_EDGE;
3291             case NETWORK_TYPE_CDMA:
3292                 return NETWORK_TYPE_BITMASK_CDMA;
3293             case NETWORK_TYPE_1xRTT:
3294                 return NETWORK_TYPE_BITMASK_1xRTT;
3295             case NETWORK_TYPE_EVDO_0:
3296                 return NETWORK_TYPE_BITMASK_EVDO_0;
3297             case NETWORK_TYPE_EVDO_A:
3298                 return NETWORK_TYPE_BITMASK_EVDO_A;
3299             case NETWORK_TYPE_EVDO_B:
3300                 return NETWORK_TYPE_BITMASK_EVDO_B;
3301             case NETWORK_TYPE_EHRPD:
3302                 return NETWORK_TYPE_BITMASK_EHRPD;
3303             case NETWORK_TYPE_HSUPA:
3304                 return NETWORK_TYPE_BITMASK_HSUPA;
3305             case NETWORK_TYPE_HSDPA:
3306                 return NETWORK_TYPE_BITMASK_HSDPA;
3307             case NETWORK_TYPE_HSPA:
3308                 return NETWORK_TYPE_BITMASK_HSPA;
3309             case NETWORK_TYPE_HSPAP:
3310                 return NETWORK_TYPE_BITMASK_HSPAP;
3311             case NETWORK_TYPE_UMTS:
3312                 return NETWORK_TYPE_BITMASK_UMTS;
3313             case NETWORK_TYPE_TD_SCDMA:
3314                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
3315             case NETWORK_TYPE_LTE:
3316             case NETWORK_TYPE_LTE_CA:
3317                 return NETWORK_TYPE_BITMASK_LTE;
3318             case NETWORK_TYPE_NR:
3319                 return NETWORK_TYPE_BITMASK_NR;
3320             case NETWORK_TYPE_IWLAN:
3321                 return NETWORK_TYPE_BITMASK_IWLAN;
3322             case NETWORK_TYPE_IDEN:
3323                 return NETWORK_TYPE_BITMASK_IDEN;
3324             default:
3325                 return NETWORK_TYPE_BITMASK_UNKNOWN;
3326         }
3327     }
3328 
3329     //
3330     //
3331     // SIM Card
3332     //
3333     //
3334 
3335     /** @hide */
3336     @IntDef(prefix = {"SIM_STATE_"},
3337             value = {
3338                     SIM_STATE_UNKNOWN,
3339                     SIM_STATE_ABSENT,
3340                     SIM_STATE_PIN_REQUIRED,
3341                     SIM_STATE_PUK_REQUIRED,
3342                     SIM_STATE_NETWORK_LOCKED,
3343                     SIM_STATE_READY,
3344                     SIM_STATE_NOT_READY,
3345                     SIM_STATE_PERM_DISABLED,
3346                     SIM_STATE_CARD_IO_ERROR,
3347                     SIM_STATE_CARD_RESTRICTED,
3348                     SIM_STATE_LOADED,
3349                     SIM_STATE_PRESENT,
3350             })
3351     public @interface SimState {}
3352 
3353     /**
3354      * SIM card state: Unknown. Signifies that the SIM is in transition
3355      * between states. For example, when the user inputs the SIM pin
3356      * under PIN_REQUIRED state, a query for sim status returns
3357      * this state before turning to SIM_STATE_READY.
3358      *
3359      * These are the ordinal value of IccCardConstants.State.
3360      */
3361 
3362     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
3363     /** SIM card state: no SIM card is available in the device */
3364     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3365     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3366     public static final int SIM_STATE_PIN_REQUIRED =
3367             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3368     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3369     public static final int SIM_STATE_PUK_REQUIRED =
3370             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3371     /** SIM card state: Locked: requires a network PIN to unlock */
3372     public static final int SIM_STATE_NETWORK_LOCKED =
3373             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3374     /** SIM card state: Ready */
3375     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3376     /** SIM card state: SIM Card is NOT READY */
3377     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3378     /** SIM card state: SIM Card Error, permanently disabled */
3379     public static final int SIM_STATE_PERM_DISABLED =
3380             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3381     /** SIM card state: SIM Card Error, present but faulty */
3382     public static final int SIM_STATE_CARD_IO_ERROR =
3383             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3384     /** SIM card state: SIM Card restricted, present but not usable due to
3385      * carrier restrictions.
3386      */
3387     public static final int SIM_STATE_CARD_RESTRICTED =
3388             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3389     /**
3390      * SIM card state: Loaded: SIM card applications have been loaded
3391      * @hide
3392      */
3393     @SystemApi
3394     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3395     /**
3396      * SIM card state: SIM Card is present
3397      * @hide
3398      */
3399     @SystemApi
3400     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3401 
3402     /**
3403      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3404      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3405      *
3406      * @hide
3407      */
3408     @SystemApi
3409     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3410 
3411     /**
3412      * Broadcast Action: The sim card state has changed.
3413      * The intent will have the following extra values:</p>
3414      * <dl>
3415      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3416      *   <dd>The sim card state. One of:
3417      *     <dl>
3418      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3419      *       <dd>SIM card not found</dd>
3420      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3421      *       <dd>SIM card IO error</dd>
3422      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3423      *       <dd>SIM card is restricted</dd>
3424      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3425      *       <dd>SIM card is present</dd>
3426      *     </dl>
3427      *   </dd>
3428      * </dl>
3429      *
3430      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3431      *
3432      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3433      *
3434      * <p class="note">This is a protected intent that can only be sent by the system.
3435      * @hide
3436      */
3437     @SystemApi
3438     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3439     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3440             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3441 
3442     /**
3443      * Broadcast Action: The sim application state has changed.
3444      * The intent will have the following extra values:</p>
3445      * <dl>
3446      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3447      *   <dd>The sim application state. One of:
3448      *     <dl>
3449      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3450      *       <dd>SIM card applications not ready</dd>
3451      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3452      *       <dd>SIM card PIN locked</dd>
3453      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3454      *       <dd>SIM card PUK locked</dd>
3455      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3456      *       <dd>SIM card network locked</dd>
3457      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3458      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3459      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3460      *       <dd>SIM card data loaded</dd>
3461      *     </dl>
3462      *   </dd>
3463      * </dl>
3464      *
3465      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3466      *
3467      * <p class="note">The current state can also be queried using
3468      * {@link #getSimApplicationState()}.
3469      *
3470      * <p class="note">This is a protected intent that can only be sent by the system.
3471      * @hide
3472      */
3473     @SystemApi
3474     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3475     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3476             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3477 
3478     /**
3479      * Broadcast Action: Status of the SIM slots on the device has changed.
3480      *
3481      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3482      *
3483      * <p class="note">The status can be queried using
3484      * {@link #getUiccSlotsInfo()}
3485      *
3486      * <p class="note">This is a protected intent that can only be sent by the system.
3487      * @hide
3488      */
3489     @SystemApi
3490     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3491     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3492             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3493 
3494     /**
3495      * Broadcast Action: A debug code has been entered in the dialer.
3496      * <p>
3497      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3498      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3499      * (see {@link #hasCarrierPrivileges}).
3500      * <p>
3501      * These "secret codes" are used to activate developer menus by dialing certain codes.
3502      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3503      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3504      * receiver would be woken up even if it is not currently running.
3505      * <p>
3506      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3507      * in the next Android version.
3508      * Before that both of these two actions will be broadcast.
3509      */
3510     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3511     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3512 
3513     /**
3514      * This API is used to check if there is an ICC card present in the device.
3515      *
3516      * An ICC card is a smart card that contains a subscriber identity module (SIM) and is used
3517      * to identify and authenticate users to a mobile network.
3518      *
3519      * Note: In case of embedded SIM there is an ICC card always present irrespective
3520      * of whether an active SIM profile is present or not so this API would always return true.
3521      *
3522      * @return true if a ICC card is present.
3523      */
3524     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
hasIccCard()3525     public boolean hasIccCard() {
3526         return hasIccCard(getSlotIndex());
3527     }
3528 
3529     /**
3530      * @return true if a ICC card is present for a subscription
3531      *
3532      * @param slotIndex for which icc card presence is checked
3533      */
3534     /** {@hide} */
3535     // FIXME Input argument slotIndex should be of type int
3536     @UnsupportedAppUsage
hasIccCard(int slotIndex)3537     public boolean hasIccCard(int slotIndex) {
3538 
3539         try {
3540             ITelephony telephony = getITelephony();
3541             if (telephony == null)
3542                 return false;
3543             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3544         } catch (RemoteException ex) {
3545             // Assume no ICC card if remote exception which shouldn't happen
3546             return false;
3547         } catch (NullPointerException ex) {
3548             // This could happen before phone restarts due to crashing
3549             return false;
3550         }
3551     }
3552 
3553     /**
3554      * Returns a constant indicating the state of the default SIM card.
3555      *
3556      * @see #SIM_STATE_UNKNOWN
3557      * @see #SIM_STATE_ABSENT
3558      * @see #SIM_STATE_PIN_REQUIRED
3559      * @see #SIM_STATE_PUK_REQUIRED
3560      * @see #SIM_STATE_NETWORK_LOCKED
3561      * @see #SIM_STATE_READY
3562      * @see #SIM_STATE_NOT_READY
3563      * @see #SIM_STATE_PERM_DISABLED
3564      * @see #SIM_STATE_CARD_IO_ERROR
3565      * @see #SIM_STATE_CARD_RESTRICTED
3566      */
3567     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimState()3568     public @SimState int getSimState() {
3569         int simState = getSimStateIncludingLoaded();
3570         if (simState == SIM_STATE_LOADED) {
3571             simState = SIM_STATE_READY;
3572         }
3573         return simState;
3574     }
3575 
getSimStateIncludingLoaded()3576     private @SimState int getSimStateIncludingLoaded() {
3577         int slotIndex = getSlotIndex();
3578         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3579         // sim state
3580         if (slotIndex < 0) {
3581             // query for all slots and return absent if all sim states are absent, otherwise
3582             // return unknown
3583             for (int i = 0; i < getPhoneCount(); i++) {
3584                 int simState = getSimState(i);
3585                 if (simState != SIM_STATE_ABSENT) {
3586                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3587                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3588                     return SIM_STATE_UNKNOWN;
3589                 }
3590             }
3591             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3592                     "state as absent");
3593             return SIM_STATE_ABSENT;
3594         }
3595         return getSimStateForSlotIndex(slotIndex);
3596     }
3597 
3598     /**
3599      * Returns a constant indicating the state of the default SIM card.
3600      *
3601      * @see #SIM_STATE_UNKNOWN
3602      * @see #SIM_STATE_ABSENT
3603      * @see #SIM_STATE_CARD_IO_ERROR
3604      * @see #SIM_STATE_CARD_RESTRICTED
3605      * @see #SIM_STATE_PRESENT
3606      *
3607      * @hide
3608      */
3609     @SystemApi
3610     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCardState()3611     public @SimState int getSimCardState() {
3612         int simState = getSimState();
3613         return getSimCardStateFromSimState(simState);
3614     }
3615 
3616     /**
3617      * Returns a constant indicating the state of the device SIM card in a physical slot.
3618      *
3619      * @param physicalSlotIndex physical slot index
3620      *
3621      * @see #SIM_STATE_UNKNOWN
3622      * @see #SIM_STATE_ABSENT
3623      * @see #SIM_STATE_CARD_IO_ERROR
3624      * @see #SIM_STATE_CARD_RESTRICTED
3625      * @see #SIM_STATE_PRESENT
3626      *
3627      * @hide
3628      * @deprecated instead use {@link #getSimCardState(int, int)}
3629      */
3630     @SystemApi
3631     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3632     @Deprecated
getSimCardState(int physicalSlotIndex)3633     public @SimState int getSimCardState(int physicalSlotIndex) {
3634         int activePort = getFirstActivePortIndex(physicalSlotIndex);
3635         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex, activePort));
3636         return getSimCardStateFromSimState(simState);
3637     }
3638 
3639     /**
3640      * Returns a constant indicating the state of the device SIM card in a physical slot and
3641      * port index.
3642      *
3643      * @param physicalSlotIndex physical slot index
3644      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3645      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3646      *
3647      * @see #SIM_STATE_UNKNOWN
3648      * @see #SIM_STATE_ABSENT
3649      * @see #SIM_STATE_CARD_IO_ERROR
3650      * @see #SIM_STATE_CARD_RESTRICTED
3651      * @see #SIM_STATE_PRESENT
3652      *
3653      * @hide
3654      */
3655     @SystemApi
3656     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3657     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCardState(int physicalSlotIndex, int portIndex)3658     public @SimState int getSimCardState(int physicalSlotIndex, int portIndex) {
3659         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex, portIndex));
3660         return getSimCardStateFromSimState(simState);
3661     }
3662     /**
3663      * Converts SIM state to SIM card state.
3664      * @param simState
3665      * @return SIM card state
3666      */
getSimCardStateFromSimState(int simState)3667     private @SimState int getSimCardStateFromSimState(int simState) {
3668         switch (simState) {
3669             case SIM_STATE_UNKNOWN:
3670             case SIM_STATE_ABSENT:
3671             case SIM_STATE_CARD_IO_ERROR:
3672             case SIM_STATE_CARD_RESTRICTED:
3673                 return simState;
3674             default:
3675                 return SIM_STATE_PRESENT;
3676         }
3677     }
3678 
3679     /**
3680      * Converts a physical slot index to logical slot index.
3681      * @param physicalSlotIndex physical slot index
3682      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3683      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3684      * @return logical slot index
3685      */
getLogicalSlotIndex(int physicalSlotIndex, int portIndex)3686     private int getLogicalSlotIndex(int physicalSlotIndex, int portIndex) {
3687         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3688         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length
3689                 && slotInfos[physicalSlotIndex] != null) {
3690             for (UiccPortInfo portInfo : slotInfos[physicalSlotIndex].getPorts()) {
3691                 if (portInfo.getPortIndex() == portIndex) {
3692                     return portInfo.getLogicalSlotIndex();
3693                 }
3694             }
3695         }
3696 
3697         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3698     }
3699 
3700     /**
3701      * Returns a constant indicating the state of the card applications on the default SIM card.
3702      *
3703      * @see #SIM_STATE_UNKNOWN
3704      * @see #SIM_STATE_PIN_REQUIRED
3705      * @see #SIM_STATE_PUK_REQUIRED
3706      * @see #SIM_STATE_NETWORK_LOCKED
3707      * @see #SIM_STATE_NOT_READY
3708      * @see #SIM_STATE_PERM_DISABLED
3709      * @see #SIM_STATE_LOADED
3710      *
3711      * @hide
3712      */
3713     @SystemApi
3714     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimApplicationState()3715     public @SimState int getSimApplicationState() {
3716         int simState = getSimStateIncludingLoaded();
3717         return getSimApplicationStateFromSimState(simState);
3718     }
3719 
3720     /**
3721      * Returns a constant indicating the state of the card applications on the device SIM card in
3722      * a physical slot.
3723      *
3724      * @param physicalSlotIndex physical slot index
3725      *
3726      * @see #SIM_STATE_UNKNOWN
3727      * @see #SIM_STATE_PIN_REQUIRED
3728      * @see #SIM_STATE_PUK_REQUIRED
3729      * @see #SIM_STATE_NETWORK_LOCKED
3730      * @see #SIM_STATE_NOT_READY
3731      * @see #SIM_STATE_PERM_DISABLED
3732      * @see #SIM_STATE_LOADED
3733      *
3734      * @hide
3735      * @deprecated instead use {@link #getSimApplicationState(int, int)}
3736      */
3737     @SystemApi
3738     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3739     @Deprecated
getSimApplicationState(int physicalSlotIndex)3740     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3741         int activePort = getFirstActivePortIndex(physicalSlotIndex);
3742         int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, activePort));
3743         return getSimApplicationStateFromSimState(simState);
3744     }
3745 
3746     /**
3747      * Returns a constant indicating the state of the card applications on the device SIM card in
3748      * a physical slot.
3749      *
3750      * @param physicalSlotIndex physical slot index
3751      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3752      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3753      *
3754      * @see #SIM_STATE_UNKNOWN
3755      * @see #SIM_STATE_PIN_REQUIRED
3756      * @see #SIM_STATE_PUK_REQUIRED
3757      * @see #SIM_STATE_NETWORK_LOCKED
3758      * @see #SIM_STATE_NOT_READY
3759      * @see #SIM_STATE_PERM_DISABLED
3760      * @see #SIM_STATE_LOADED
3761      *
3762      * @hide
3763      */
3764     @SystemApi
3765     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3766     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimApplicationState(int physicalSlotIndex, int portIndex)3767     public @SimState int getSimApplicationState(int physicalSlotIndex, int portIndex) {
3768         int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, portIndex));
3769         return getSimApplicationStateFromSimState(simState);
3770     }
3771 
3772     /**
3773      * Converts SIM state to SIM application state.
3774      * @param simState
3775      * @return SIM application state
3776      */
getSimApplicationStateFromSimState(int simState)3777     private @SimState int getSimApplicationStateFromSimState(int simState) {
3778         switch (simState) {
3779             case SIM_STATE_UNKNOWN:
3780             case SIM_STATE_ABSENT:
3781             case SIM_STATE_CARD_IO_ERROR:
3782             case SIM_STATE_CARD_RESTRICTED:
3783                 return SIM_STATE_UNKNOWN;
3784             case SIM_STATE_READY:
3785                 // Ready is not a valid state anymore. The state that is broadcast goes from
3786                 // NOT_READY to either LOCKED or LOADED.
3787                 return SIM_STATE_NOT_READY;
3788             default:
3789                 return simState;
3790         }
3791     }
3792 
3793 
3794     /**
3795      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
3796      * on the UICC card.
3797      *
3798      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
3799      *
3800      * @param appType the uicc app type like {@link APPTYPE_CSIM}
3801      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
3802      * @hide
3803      */
3804     @SystemApi
3805     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3806     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
isApplicationOnUicc(@iccAppType int appType)3807     public boolean isApplicationOnUicc(@UiccAppType int appType) {
3808         try {
3809             ITelephony service = getITelephony();
3810             if (service != null) {
3811                 return service.isApplicationOnUicc(getSubId(), appType);
3812             }
3813         } catch (RemoteException e) {
3814             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
3815         }
3816         return false;
3817     }
3818 
3819     /**
3820      * Returns a constant indicating the state of the device SIM card in a logical slot.
3821      *
3822      * @param slotIndex logical slot index
3823      *
3824      * @see #SIM_STATE_UNKNOWN
3825      * @see #SIM_STATE_ABSENT
3826      * @see #SIM_STATE_PIN_REQUIRED
3827      * @see #SIM_STATE_PUK_REQUIRED
3828      * @see #SIM_STATE_NETWORK_LOCKED
3829      * @see #SIM_STATE_READY
3830      * @see #SIM_STATE_NOT_READY
3831      * @see #SIM_STATE_PERM_DISABLED
3832      * @see #SIM_STATE_CARD_IO_ERROR
3833      * @see #SIM_STATE_CARD_RESTRICTED
3834      */
3835     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimState(int slotIndex)3836     public @SimState int getSimState(int slotIndex) {
3837         int simState = getSimStateForSlotIndex(slotIndex);
3838         if (simState == SIM_STATE_LOADED) {
3839             simState = SIM_STATE_READY;
3840         }
3841         return simState;
3842     }
3843 
3844     /**
3845      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3846      * provider of the SIM. 5 or 6 decimal digits.
3847      * <p>
3848      * Availability: SIM state must be {@link #SIM_STATE_READY}
3849      *
3850      * @see #getSimState
3851      */
3852     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimOperator()3853     public String getSimOperator() {
3854         return getSimOperatorNumeric();
3855     }
3856 
3857     /**
3858      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3859      * provider of the SIM. 5 or 6 decimal digits.
3860      * <p>
3861      * Availability: SIM state must be {@link #SIM_STATE_READY}
3862      *
3863      * @see #getSimState
3864      *
3865      * @param subId for which SimOperator is returned
3866      * @hide
3867      */
3868     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)3869     public String getSimOperator(int subId) {
3870         return getSimOperatorNumeric(subId);
3871     }
3872 
3873     /**
3874      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3875      * provider of the SIM. 5 or 6 decimal digits.
3876      * <p>
3877      * Availability: SIM state must be {@link #SIM_STATE_READY}
3878      *
3879      * @see #getSimState
3880      * @hide
3881      */
3882     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()3883     public String getSimOperatorNumeric() {
3884         int subId = mSubId;
3885         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3886             subId = SubscriptionManager.getDefaultDataSubscriptionId();
3887             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3888                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
3889                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3890                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
3891                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3892                         subId = SubscriptionManager.getDefaultSubscriptionId();
3893                     }
3894                 }
3895             }
3896         }
3897         return getSimOperatorNumeric(subId);
3898     }
3899 
3900     /**
3901      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3902      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3903      * <p>
3904      * Availability: SIM state must be {@link #SIM_STATE_READY}
3905      *
3906      * @see #getSimState
3907      *
3908      * @param subId for which SimOperator is returned
3909      * @hide
3910      */
3911     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)3912     public String getSimOperatorNumeric(int subId) {
3913         int phoneId = SubscriptionManager.getPhoneId(subId);
3914         return getSimOperatorNumericForPhone(phoneId);
3915     }
3916 
3917     /**
3918      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3919      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3920      * <p>
3921      *
3922      * @param phoneId for which SimOperator is returned
3923      * @hide
3924      */
3925     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)3926     public String getSimOperatorNumericForPhone(int phoneId) {
3927         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
3928     }
3929 
3930     /**
3931      * Returns the Service Provider Name (SPN).
3932      * <p>
3933      * Availability: SIM state must be {@link #SIM_STATE_READY}
3934      *
3935      * @see #getSimState
3936      */
3937     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimOperatorName()3938     public String getSimOperatorName() {
3939         return getSimOperatorNameForPhone(getPhoneId());
3940     }
3941 
3942     /**
3943      * Returns the Service Provider Name (SPN).
3944      * <p>
3945      * Availability: SIM state must be {@link #SIM_STATE_READY}
3946      *
3947      * @see #getSimState
3948      *
3949      * @param subId for which SimOperatorName is returned
3950      * @hide
3951      */
3952     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)3953     public String getSimOperatorName(int subId) {
3954         int phoneId = SubscriptionManager.getPhoneId(subId);
3955         return getSimOperatorNameForPhone(phoneId);
3956     }
3957 
3958     /**
3959      * Returns the Service Provider Name (SPN).
3960      *
3961      * @hide
3962      */
3963     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)3964     public String getSimOperatorNameForPhone(int phoneId) {
3965         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
3966     }
3967 
3968     /**
3969      * Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
3970      * <p>
3971      * The ISO-3166-1 alpha-2 country code is provided in lowercase 2 character format.
3972      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string is not
3973      * available.
3974      */
3975     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCountryIso()3976     public String getSimCountryIso() {
3977         return getSimCountryIsoForPhone(getPhoneId());
3978     }
3979 
3980     /**
3981      * Returns the ISO country code equivalent for the SIM provider's country code.
3982      *
3983      * @param subId for which SimCountryIso is returned
3984      * @hide
3985      */
3986     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)3987     public static String getSimCountryIso(int subId) {
3988         int phoneId = SubscriptionManager.getPhoneId(subId);
3989         return getSimCountryIsoForPhone(phoneId);
3990     }
3991 
3992     /**
3993      * Returns the ISO country code equivalent for the SIM provider's country code.
3994      *
3995      * @hide
3996      */
3997     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)3998     public static String getSimCountryIsoForPhone(int phoneId) {
3999         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
4000     }
4001 
4002     /**
4003      * Returns the serial number of the SIM, if applicable. Return null if it is
4004      * unavailable.
4005      *
4006      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4007      * restrictions, and apps are recommended to use resettable identifiers (see <a
4008      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4009      * method can be invoked if one of the following requirements is met:
4010      * <ul>
4011      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4012      *     is a privileged permission that can only be granted to apps preloaded on the device.
4013      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4014      *     owner of an organization-owned device, or their delegates (see {@link
4015      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4016      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4017      *     <li>If the calling app is the default SMS role holder (see {@link
4018      *     RoleManager#isRoleHeld(String)}).
4019      * </ul>
4020      *
4021      * <p>If the calling app does not meet one of these requirements then this method will behave
4022      * as follows:
4023      *
4024      * <ul>
4025      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4026      *     READ_PHONE_STATE permission then null is returned.</li>
4027      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4028      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4029      *     higher, then a SecurityException is thrown.</li>
4030      * </ul>
4031      */
4032     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4033     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4034     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSerialNumber()4035     public String getSimSerialNumber() {
4036          return getSimSerialNumber(getSubId());
4037     }
4038 
4039     /**
4040      * Returns the serial number for the given subscription, if applicable. Return null if it is
4041      * unavailable.
4042      *
4043      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4044      * restrictions, and apps are recommended to use resettable identifiers (see <a
4045      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4046      * method can be invoked if one of the following requirements is met:
4047      * <ul>
4048      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4049      *     is a privileged permission that can only be granted to apps preloaded on the device.
4050      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4051      *     owner of an organization-owned device, or their delegates (see {@link
4052      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4053      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4054      *     <li>If the calling app is the default SMS role holder (see {@link
4055      *     RoleManager#isRoleHeld(String)}).
4056      * </ul>
4057      *
4058      * <p>If the calling app does not meet one of these requirements then this method will behave
4059      * as follows:
4060      *
4061      * <ul>
4062      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4063      *     READ_PHONE_STATE permission then null is returned.</li>
4064      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4065      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4066      *     higher, then a SecurityException is thrown.</li>
4067      * </ul>
4068      *
4069      * @param subId for which Sim Serial number is returned
4070      * @hide
4071      */
4072     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4073     @UnsupportedAppUsage
getSimSerialNumber(int subId)4074     public String getSimSerialNumber(int subId) {
4075         try {
4076             IPhoneSubInfo info = getSubscriberInfoService();
4077             if (info == null)
4078                 return null;
4079             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
4080                     mContext.getAttributionTag());
4081         } catch (RemoteException ex) {
4082             return null;
4083         } catch (NullPointerException ex) {
4084             // This could happen before phone restarts due to crashing
4085             return null;
4086         }
4087     }
4088 
4089     /**
4090      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
4091      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
4092      *
4093      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
4094      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
4095      *
4096      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
4097      *         {@code false} if not supported or unknown
4098      * @hide
4099      */
4100     @SystemApi
4101     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4102     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isLteCdmaEvdoGsmWcdmaEnabled()4103     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
4104         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
4105     }
4106 
4107     /**
4108      * Return if the current radio is LTE on CDMA for Subscription. This
4109      * is a tri-state return value as for a period of time
4110      * the mode may be unknown.
4111      *
4112      * @param subId for which radio is LTE on CDMA is returned
4113      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
4114      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
4115      * @hide
4116      */
4117     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4118     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)4119     public int getLteOnCdmaMode(int subId) {
4120         try {
4121             ITelephony telephony = getITelephony();
4122             if (telephony == null)
4123                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4124             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
4125                     getAttributionTag());
4126         } catch (RemoteException ex) {
4127             // Assume no ICC card if remote exception which shouldn't happen
4128             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4129         } catch (NullPointerException ex) {
4130             // This could happen before phone restarts due to crashing
4131             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4132         }
4133     }
4134 
4135     /**
4136      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
4137      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
4138      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
4139      *
4140      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
4141      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
4142      * through a factory reset.
4143      *
4144      * @return card ID of the default eUICC card, if loaded.
4145      */
4146     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
getCardIdForDefaultEuicc()4147     public int getCardIdForDefaultEuicc() {
4148         try {
4149             ITelephony telephony = getITelephony();
4150             if (telephony == null) {
4151                 return UNINITIALIZED_CARD_ID;
4152             }
4153             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
4154         } catch (RemoteException e) {
4155             return UNINITIALIZED_CARD_ID;
4156         }
4157     }
4158 
4159     /**
4160      * Gets information about currently inserted UICCs and eUICCs.
4161      * <p>
4162      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4163      * <p>
4164      * If the caller has carrier priviliges on any active subscription, then they have permission to
4165      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
4166      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the physical slot index where the card is
4167      * inserted ({@link UiccCardInfo#getPhysicalSlotIndex()}.
4168      * <p>
4169      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
4170      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
4171      * UICC or eUICC card.
4172      * <p>
4173      * See {@link UiccCardInfo} for more details on the kind of information available.
4174      *
4175      * @return a list of UiccCardInfo objects, representing information on the currently inserted
4176      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
4177      * the caller does not have adequate permissions for that card.
4178      */
4179     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4180     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4181     @NonNull
getUiccCardsInfo()4182     public List<UiccCardInfo> getUiccCardsInfo() {
4183         try {
4184             ITelephony telephony = getITelephony();
4185             if (telephony == null) {
4186                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
4187                 return new ArrayList<UiccCardInfo>();
4188             }
4189             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
4190         } catch (RemoteException e) {
4191             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
4192             return new ArrayList<UiccCardInfo>();
4193         }
4194     }
4195 
4196     /**
4197      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
4198      * available, which is possible between phone process starting and getting slot info from modem.
4199      *
4200      * @return UiccSlotInfo array.
4201      *
4202      * @hide
4203      */
4204     @SystemApi
4205     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4206     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getUiccSlotsInfo()4207     public UiccSlotInfo[] getUiccSlotsInfo() {
4208         try {
4209             ITelephony telephony = getITelephony();
4210             if (telephony == null) {
4211                 return null;
4212             }
4213             return telephony.getUiccSlotsInfo(mContext.getOpPackageName());
4214         } catch (RemoteException e) {
4215             return null;
4216         }
4217     }
4218 
4219     /**
4220      * Test method to reload the UICC profile.
4221      *
4222      * @hide
4223      */
4224     @TestApi
4225     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()4226     public void refreshUiccProfile() {
4227         try {
4228             ITelephony telephony = getITelephony();
4229             telephony.refreshUiccProfile(mSubId);
4230         } catch (RemoteException ex) {
4231             Rlog.w(TAG, "RemoteException", ex);
4232         }
4233     }
4234 
4235     /**
4236      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
4237      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
4238      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
4239      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
4240      * logical slots.
4241      *
4242      * @param physicalSlots The content of the array represents the physical slot index. The array
4243      *        size should be same as {@link #getUiccSlotsInfo()}.
4244      * @return boolean Return true if the switch succeeds, false if the switch fails.
4245      * @hide
4246      * @deprecated {@link #setSimSlotMapping(Collection, Executor, Consumer)}
4247      */
4248      // TODO: once integrating the HAL changes we can  convert int[] to List<UiccSlotMapping> and
4249      // converge API's in ITelephony.aidl and PhoneInterfaceManager
4250 
4251     @SystemApi
4252     @Deprecated
4253     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchSlots(int[] physicalSlots)4254     public boolean switchSlots(int[] physicalSlots) {
4255         try {
4256             ITelephony telephony = getITelephony();
4257             if (telephony == null) {
4258                 return false;
4259             }
4260             return telephony.switchSlots(physicalSlots);
4261         } catch (RemoteException e) {
4262             return false;
4263         }
4264     }
4265 
4266     /**
4267      * @param slotMapping Logical to physical slot and port mapping.
4268      * @return {@code true} if slotMapping is valid.
4269      * @return {@code false} if slotMapping is invalid.
4270      *
4271      * slotMapping is invalid if there are different entries (physical slot + port) mapping to the
4272      * same logical slot or if there are same {physical slot + port} mapping to the different
4273      * logical slot
4274      * @hide
4275      */
isSlotMappingValid(@onNull Collection<UiccSlotMapping> slotMapping)4276     private static boolean isSlotMappingValid(@NonNull Collection<UiccSlotMapping> slotMapping) {
4277         // Grouping the collection by logicalSlotIndex, finding different entries mapping to the
4278         // same logical slot
4279         Map<Integer, List<UiccSlotMapping>> slotMappingInfo = slotMapping.stream().collect(
4280                 Collectors.groupingBy(UiccSlotMapping::getLogicalSlotIndex));
4281         for (Map.Entry<Integer, List<UiccSlotMapping>> entry : slotMappingInfo.entrySet()) {
4282             List<UiccSlotMapping> logicalSlotMap = entry.getValue();
4283             if (logicalSlotMap.size() > 1) {
4284                 // duplicate logicalSlotIndex found
4285                 return false;
4286             }
4287         }
4288 
4289         // Grouping the collection by physical slot and port, finding same entries mapping to the
4290         // different logical slot
4291         Map<List<Integer>, List<UiccSlotMapping>> slotMapInfos = slotMapping.stream().collect(
4292                 Collectors.groupingBy(
4293                         slot -> Arrays.asList(slot.getPhysicalSlotIndex(), slot.getPortIndex())));
4294         for (Map.Entry<List<Integer>, List<UiccSlotMapping>> entry : slotMapInfos.entrySet()) {
4295             List<UiccSlotMapping> portAndPhysicalSlotList = entry.getValue();
4296             if (portAndPhysicalSlotList.size() > 1) {
4297                 // duplicate pair of portIndex and physicalSlotIndex found
4298                 return false;
4299             }
4300         }
4301         return true;
4302     }
4303     /**
4304      * Maps the logical slots to physical slots and ports. Mapping is specified from
4305      * {@link UiccSlotMapping} which consist of both physical slot index and port index.
4306      * Logical slot is the slot that is seen by modem. Physical slot is the actual physical slot.
4307      * Port index is the index (enumerated value) for the associated port available on the SIM.
4308      * Each physical slot can have multiple ports if
4309      * {@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP} is supported.
4310      *
4311      * Example: no. of logical slots 1 and physical slots 2 do not support MEP, each physical slot
4312      * has one port:
4313      * The only logical slot (index 0) can be mapped to first physical slot (value 0), port(index
4314      * 0) or
4315      * second physical slot(value 1), port (index 0), while the other physical slot remains unmapped
4316      * and inactive.
4317      * slotMapping[0] = UiccSlotMapping{0 //port index, 0 //physical slot, 0 //logical slot} or
4318      * slotMapping[0] = UiccSlotMapping{0 //port index, 1 //physical slot, 0 //logical slot}
4319      *
4320      * Example no. of logical slots 2 and physical slots 2 supports MEP with 2 ports available:
4321      * Each logical slot must be mapped to a port (physical slot and port combination).
4322      * First logical slot (index 0) can be mapped to physical slot 1 and the second logical slot
4323      * can be mapped to either port from physical slot 2.
4324      *
4325      * slotMapping[0] = UiccSlotMapping{0, 0, 0} and slotMapping[1] = UiccSlotMapping{0, 1, 1} or
4326      * slotMapping[0] = UiccSlotMapping{0, 0, 0} and slotMapping[1] = UiccSlotMapping{1, 1, 1}
4327      *
4328      * or the other way around, the second logical slot(index 1) can be mapped to physical slot 1
4329      * and the first logical slot can be mapped to either port from physical slot 2.
4330      *
4331      * slotMapping[1] = UiccSlotMapping{0, 0, 0} and slotMapping[0] = UiccSlotMapping{0, 1, 1} or
4332      * slotMapping[1] = UiccSlotMapping{0, 0, 0} and slotMapping[0] = UiccSlotMapping{1, 1, 1}
4333      *
4334      * another possible mapping is each logical slot maps to each port of physical slot 2 and there
4335      * is no active logical modem mapped to physical slot 1.
4336      *
4337      * slotMapping[0] = UiccSlotMapping{0, 1, 0} and slotMapping[1] = UiccSlotMapping{1, 1, 1} or
4338      * slotMapping[0] = UiccSlotMapping{1, 1, 0} and slotMapping[1] = UiccSlotMapping{0, 1, 1}
4339      *
4340      * @param slotMapping Logical to physical slot and port mapping.
4341      * @throws IllegalStateException if telephony service is null or slot mapping was sent when the
4342      *         radio in middle of a silent restart or other invalid states to handle the command
4343      * @throws IllegalArgumentException if the caller passes in an invalid collection of
4344      *         UiccSlotMapping like duplicate data, etc
4345      *
4346      * @hide
4347      */
4348     @SystemApi
4349     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4350     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimSlotMapping(@onNull Collection<UiccSlotMapping> slotMapping)4351     public void setSimSlotMapping(@NonNull Collection<UiccSlotMapping> slotMapping) {
4352         try {
4353             ITelephony telephony = getITelephony();
4354             if (telephony != null) {
4355                 if (isSlotMappingValid(slotMapping)) {
4356                     boolean result = telephony.setSimSlotMapping(new ArrayList(slotMapping));
4357                     if (!result) {
4358                         throw new IllegalStateException("setSimSlotMapping has failed");
4359                     }
4360                 } else {
4361                     throw new IllegalArgumentException("Duplicate UiccSlotMapping data found");
4362                 }
4363             } else {
4364                 throw new IllegalStateException("telephony service is null.");
4365             }
4366         } catch (RemoteException e) {
4367             throw e.rethrowAsRuntimeException();
4368         }
4369     }
4370 
4371     /**
4372      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
4373      * id and the value is the physical slots id mapped to this logical slot id.
4374      *
4375      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
4376      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
4377      *
4378      * @hide
4379      * @deprecated use {@link #getSimSlotMapping()} instead.
4380      */
4381     @SystemApi
4382     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4383     @NonNull
4384     @Deprecated
getLogicalToPhysicalSlotMapping()4385     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
4386         Map<Integer, Integer> slotMapping = new HashMap<>();
4387         try {
4388             ITelephony telephony = getITelephony();
4389             if (telephony != null) {
4390                 List<UiccSlotMapping> simSlotsMapping = telephony.getSlotsMapping(
4391                         mContext.getOpPackageName());
4392                 for (UiccSlotMapping slotMap : simSlotsMapping) {
4393                     slotMapping.put(slotMap.getLogicalSlotIndex(), slotMap.getPhysicalSlotIndex());
4394                 }
4395             }
4396         } catch (RemoteException e) {
4397             Log.e(TAG, "getSlotsMapping RemoteException", e);
4398         }
4399         return slotMapping;
4400     }
4401 
4402     /**
4403      * Get the mapping from logical slots to physical sim slots and port indexes. Initially the
4404      * logical slot index was mapped to physical slot index, but with support for multi-enabled
4405      * profile(MEP){@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP},logical slot is now mapped to
4406      * port index.
4407      *
4408      * @return a collection of {@link UiccSlotMapping} which indicates the mapping from logical
4409      *         slots to ports and physical slots.
4410      * @hide
4411      */
4412     @SystemApi
4413     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4414     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4415     @NonNull
getSimSlotMapping()4416     public Collection<UiccSlotMapping> getSimSlotMapping() {
4417         List<UiccSlotMapping> slotMap;
4418         try {
4419             ITelephony telephony = getITelephony();
4420             if (telephony != null) {
4421                 slotMap = telephony.getSlotsMapping(mContext.getOpPackageName());
4422             } else {
4423                 throw new IllegalStateException("telephony service is null.");
4424             }
4425         } catch (RemoteException e) {
4426             throw e.rethrowAsRuntimeException();
4427         }
4428         return slotMap;
4429     }
4430     //
4431     //
4432     // Subscriber Info
4433     //
4434     //
4435 
4436     /**
4437      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
4438      * Return null if it is unavailable.
4439      *
4440      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4441      * restrictions, and apps are recommended to use resettable identifiers (see <a
4442      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4443      * method can be invoked if one of the following requirements is met:
4444      * <ul>
4445      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4446      *     is a privileged permission that can only be granted to apps preloaded on the device.
4447      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4448      *     owner of an organization-owned device, or their delegates (see {@link
4449      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4450      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4451      *     <li>If the calling app is the default SMS role holder (see {@link
4452      *     RoleManager#isRoleHeld(String)}).
4453      *     <li>If the calling app has been granted the
4454      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
4455      * </ul>
4456      *
4457      * <p>If the calling app does not meet one of these requirements then this method will behave
4458      * as follows:
4459      *
4460      * <ul>
4461      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4462      *     READ_PHONE_STATE permission then null is returned.</li>
4463      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4464      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4465      *     higher, then a SecurityException is thrown.</li>
4466      * </ul>
4467      */
4468     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4469     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4470     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriberId()4471     public String getSubscriberId() {
4472         return getSubscriberId(getSubId());
4473     }
4474 
4475     /**
4476      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
4477      * for a subscription.
4478      * Return null if it is unavailable.
4479      *
4480      * See {@link #getSubscriberId()} for details on the required permissions and behavior
4481      * when the caller does not hold sufficient permissions.
4482      *
4483      * @param subId whose subscriber id is returned
4484      * @hide
4485      */
4486     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4487     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)4488     public String getSubscriberId(int subId) {
4489         try {
4490             IPhoneSubInfo info = getSubscriberInfoService();
4491             if (info == null)
4492                 return null;
4493             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
4494                     mContext.getAttributionTag());
4495         } catch (RemoteException ex) {
4496             return null;
4497         } catch (NullPointerException ex) {
4498             // This could happen before phone restarts due to crashing
4499             return null;
4500         }
4501     }
4502 
4503     /**
4504      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
4505      * including the public key and the key identifier; or {@code null} if not available.
4506      * <p>
4507      * For a multi-sim device, the dafault data sim is used if not specified.
4508      * <p>
4509      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
4510      *
4511      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
4512      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
4513      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
4514      *         IMSI and IMPI. This includes the public key and the key identifier. This information
4515      *         will be stored in the device keystore. {@code null} will be returned when no key is
4516      *         found, and the carrier does not require a key.
4517      * @throws IllegalArgumentException when an invalid key is found or when key is required but
4518      *         not found.
4519      * @hide
4520      */
4521     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4522     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4523     @SystemApi
4524     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)4525     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
4526         try {
4527             IPhoneSubInfo info = getSubscriberInfoService();
4528             if (info == null) {
4529                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
4530                 return null;
4531             }
4532             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4533             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
4534                 throw new IllegalArgumentException("IMSI error: Invalid key type");
4535             }
4536             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
4537                     subId, keyType, mContext.getOpPackageName());
4538             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
4539                 Rlog.e(TAG, "IMSI error: key is required but not found");
4540                 throw new IllegalArgumentException("IMSI error: key is required but not found");
4541             }
4542             return imsiEncryptionInfo;
4543         } catch (RemoteException ex) {
4544             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4545         } catch (NullPointerException ex) {
4546             // This could happen before phone restarts due to crashing
4547             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
4548         }
4549         return null;
4550     }
4551 
4552     /**
4553      * Resets the carrier keys used to encrypt the IMSI and IMPI.
4554      * <p>
4555      * This involves 2 steps:
4556      *  1. Delete the keys from the database.
4557      *  2. Send an intent to download new Certificates.
4558      * <p>
4559      * For a multi-sim device, the dafault data sim is used if not specified.
4560      * <p>
4561      * Requires Permission: MODIFY_PHONE_STATE.
4562      *
4563      * @see #getCarrierInfoForImsiEncryption
4564      * @hide
4565      */
4566     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4567     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4568     @SystemApi
resetCarrierKeysForImsiEncryption()4569     public void resetCarrierKeysForImsiEncryption() {
4570         try {
4571             IPhoneSubInfo info = getSubscriberInfoService();
4572             if (info == null) {
4573                 throw new RuntimeException("IMSI error: Subscriber Info is null");
4574             }
4575             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4576             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
4577         } catch (RemoteException ex) {
4578             Rlog.e(TAG, "Telephony#getCarrierInfoForImsiEncryption RemoteException" + ex);
4579         }
4580     }
4581 
4582     /**
4583      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
4584      * @param keyType the key type which is being checked. (WLAN, EPDG)
4585      * @return true if the digit at position keyType is 1, else false.
4586      * @hide
4587      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)4588     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
4589         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
4590         return (returnValue == 1) ? true : false;
4591     }
4592 
4593     /**
4594      * If Carrier requires Imsi to be encrypted.
4595      * @hide
4596      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4597     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4598         CarrierConfigManager configManager =
4599                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4600         if (configManager == null) {
4601             return false;
4602         }
4603         PersistableBundle pb = configManager.getConfigForSubId(subId);
4604         if (pb == null) {
4605             return false;
4606         }
4607         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4608         return isKeyEnabled(keyAvailability, keyType);
4609     }
4610 
4611     /**
4612      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4613      * This includes the public key and the key identifier. This information will be stored in the
4614      * device keystore.
4615      * <p>
4616      * Requires Permission:
4617      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4618      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4619      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4620      *        The keyIdentifier Attribute value pair that helps a server locate
4621      *        the private key to decrypt the permanent identity. This field is
4622      *        optional and if it is present then it’s always separated from encrypted
4623      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4624      *        with “name=value” format.
4625      * @hide
4626      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4627     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4628         try {
4629             IPhoneSubInfo info = getSubscriberInfoService();
4630             if (info == null) return;
4631             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4632                     imsiEncryptionInfo);
4633         } catch (NullPointerException ex) {
4634             // This could happen before phone restarts due to crashing
4635             return;
4636         } catch (RemoteException ex) {
4637             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4638             return;
4639         }
4640     }
4641 
4642     /**
4643      * Exception that may be supplied to the callback in {@link #uploadCallComposerPicture} if
4644      * something goes awry.
4645      */
4646     public static class CallComposerException extends Exception {
4647         /**
4648          * Used internally only, signals success of the upload to the carrier.
4649          * @hide
4650          */
4651         public static final int SUCCESS = -1;
4652         /**
4653          * Indicates that an unknown error was encountered when uploading the call composer picture.
4654          *
4655          * Clients that encounter this error should retry the upload.
4656          */
4657         public static final int ERROR_UNKNOWN = 0;
4658 
4659         /**
4660          * Indicates that the phone process died or otherwise became unavailable while uploading the
4661          * call composer picture.
4662          *
4663          * Clients that encounter this error should retry the upload.
4664          */
4665         public static final int ERROR_REMOTE_END_CLOSED = 1;
4666 
4667         /**
4668          * Indicates that the file or stream supplied exceeds the size limit defined in
4669          * {@link #getMaximumCallComposerPictureSize()}.
4670          *
4671          * Clients that encounter this error should retry the upload after reducing the size of the
4672          * picture.
4673          */
4674         public static final int ERROR_FILE_TOO_LARGE = 2;
4675 
4676         /**
4677          * Indicates that the device failed to authenticate with the carrier when uploading the
4678          * picture.
4679          *
4680          * Clients that encounter this error should not retry the upload unless a reboot or radio
4681          * reset has been performed in the interim.
4682          */
4683         public static final int ERROR_AUTHENTICATION_FAILED = 3;
4684 
4685         /**
4686          * Indicates that the {@link InputStream} passed to {@link #uploadCallComposerPicture}
4687          * was closed.
4688          *
4689          * The caller should retry if this error is encountered, and be sure to not close the stream
4690          * before the callback is called this time.
4691          */
4692         public static final int ERROR_INPUT_CLOSED = 4;
4693 
4694         /**
4695          * Indicates that an {@link IOException} was encountered while reading the picture.
4696          *
4697          * The offending {@link IOException} will be available via {@link #getIOException()}.
4698          * Clients should use the contents of the exception to determine whether a retry is
4699          * warranted.
4700          */
4701         public static final int ERROR_IO_EXCEPTION = 5;
4702 
4703         /**
4704          * Indicates that the device is currently not connected to a network that's capable of
4705          * reaching a carrier's RCS servers.
4706          *
4707          * Clients should prompt the user to remedy the issue by moving to an area with better
4708          * signal, by connecting to a different network, or to retry at another time.
4709          */
4710         public static final int ERROR_NETWORK_UNAVAILABLE = 6;
4711 
4712         /** @hide */
4713         @IntDef(prefix = {"ERROR_"}, value = {
4714                 ERROR_UNKNOWN,
4715                 ERROR_REMOTE_END_CLOSED,
4716                 ERROR_FILE_TOO_LARGE,
4717                 ERROR_AUTHENTICATION_FAILED,
4718                 ERROR_INPUT_CLOSED,
4719                 ERROR_IO_EXCEPTION,
4720                 ERROR_NETWORK_UNAVAILABLE,
4721         })
4722 
4723         @Retention(RetentionPolicy.SOURCE)
4724         public @interface CallComposerError {}
4725 
4726         private final int mErrorCode;
4727         private final IOException mIOException;
4728 
CallComposerException(@allComposerError int errorCode, @Nullable IOException ioException)4729         public CallComposerException(@CallComposerError int errorCode,
4730                 @Nullable IOException ioException) {
4731             mErrorCode = errorCode;
4732             mIOException = ioException;
4733         }
4734 
4735         /**
4736          * Fetches the error code associated with this exception.
4737          * @return An error code.
4738          */
getErrorCode()4739         public @CallComposerError int getErrorCode() {
4740             return mErrorCode;
4741         }
4742 
4743         /**
4744          * Fetches the {@link IOException} that caused the error.
4745          */
4746         // Follows the naming of IOException
4747         @SuppressLint("AcronymName")
getIOException()4748         public @Nullable IOException getIOException() {
4749             return mIOException;
4750         }
4751     }
4752 
4753     /** @hide */
4754     public static final String KEY_CALL_COMPOSER_PICTURE_HANDLE = "call_composer_picture_handle";
4755 
4756     /**
4757      * Uploads a picture to the carrier network for use with call composer.
4758      *
4759      * @see #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)
4760      * @param pictureToUpload Path to a local file containing the picture to upload.
4761      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg)
4762      * @param executor The {@link Executor} on which the {@code pictureToUpload} file will be read
4763      *                 from disk, as well as on which {@code callback} will be called.
4764      * @param callback A callback called when the upload operation terminates, either in success
4765      *                 or in error.
4766      */
4767     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
uploadCallComposerPicture(@onNull Path pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)4768     public void uploadCallComposerPicture(@NonNull Path pictureToUpload,
4769             @NonNull String contentType,
4770             @CallbackExecutor @NonNull Executor executor,
4771             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
4772         Objects.requireNonNull(pictureToUpload);
4773         Objects.requireNonNull(executor);
4774         Objects.requireNonNull(callback);
4775 
4776         // Do the role check now so that we can quit early if needed -- there's an additional
4777         // permission check on the other side of the binder call as well.
4778         RoleManager rm = mContext.getSystemService(RoleManager.class);
4779         if (!rm.isRoleHeld(RoleManager.ROLE_DIALER)) {
4780             throw new SecurityException("You must hold RoleManager.ROLE_DIALER to do this");
4781         }
4782 
4783         executor.execute(() -> {
4784             try {
4785                 if (Looper.getMainLooper().isCurrentThread()) {
4786                     Log.w(TAG, "Uploading call composer picture on main thread!"
4787                             + " hic sunt dracones!");
4788                 }
4789                 long size = Files.size(pictureToUpload);
4790                 if (size > getMaximumCallComposerPictureSize()) {
4791                     callback.onError(new CallComposerException(
4792                             CallComposerException.ERROR_FILE_TOO_LARGE, null));
4793                     return;
4794                 }
4795                 InputStream fileStream = Files.newInputStream(pictureToUpload);
4796                 try {
4797                     uploadCallComposerPicture(fileStream, contentType, executor,
4798                             new OutcomeReceiver<ParcelUuid, CallComposerException>() {
4799                                 @Override
4800                                 public void onResult(ParcelUuid result) {
4801                                     try {
4802                                         fileStream.close();
4803                                     } catch (IOException e) {
4804                                         // ignore
4805                                         Log.e(TAG, "Error closing file input stream when"
4806                                                 + " uploading call composer pic");
4807                                     }
4808                                     callback.onResult(result);
4809                                 }
4810 
4811                                 @Override
4812                                 public void onError(CallComposerException error) {
4813                                     try {
4814                                         fileStream.close();
4815                                     } catch (IOException e) {
4816                                         // ignore
4817                                         Log.e(TAG, "Error closing file input stream when"
4818                                                 + " uploading call composer pic");
4819                                     }
4820                                     callback.onError(error);
4821                                 }
4822                             });
4823                 } catch (Exception e) {
4824                     Log.e(TAG, "Got exception calling into stream-version of"
4825                             + " uploadCallComposerPicture: " + e);
4826                     try {
4827                         fileStream.close();
4828                     } catch (IOException e1) {
4829                         // ignore
4830                         Log.e(TAG, "Error closing file input stream when uploading"
4831                                 + " call composer pic");
4832                     }
4833                 }
4834             } catch (IOException e) {
4835                 Log.e(TAG, "IOException when uploading call composer pic:" + e);
4836                 callback.onError(
4837                         new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e));
4838             }
4839         });
4840 
4841     }
4842 
4843     /**
4844      * Uploads a picture to the carrier network for use with call composer.
4845      *
4846      * This method allows a dialer app to upload a picture to the carrier network that can then
4847      * later be attached to an outgoing call. In order to attach the picture to a call, use the
4848      * {@link ParcelUuid} returned from {@code callback} upon successful upload as the value to
4849      * {@link TelecomManager#EXTRA_OUTGOING_PICTURE}.
4850      *
4851      * This functionality is only available to the app filling the {@link RoleManager#ROLE_DIALER}
4852      * role on the device.
4853      *
4854      * This functionality is only available when
4855      * {@link CarrierConfigManager#KEY_SUPPORTS_CALL_COMPOSER_BOOL} is set to {@code true} in the
4856      * bundle returned from {@link #getCarrierConfig()}.
4857      *
4858      * @param pictureToUpload An {@link InputStream} that supplies the bytes representing the
4859      *                        picture to upload. The client bears responsibility for closing this
4860      *                        stream after {@code callback} is called with success or failure.
4861      *
4862      *                        Additionally, if the stream supplies more bytes than the return value
4863      *                        of {@link #getMaximumCallComposerPictureSize()}, the upload will be
4864      *                        aborted and the callback will be called with an exception containing
4865      *                        {@link CallComposerException#ERROR_FILE_TOO_LARGE}.
4866      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg). The list
4867      *                    of acceptable content types can be found at 3GPP TS 26.141 sections
4868      *                    4.2 and 4.3.
4869      * @param executor The {@link Executor} on which the {@code pictureToUpload} stream will be
4870      *                 read, as well as on which the callback will be called.
4871      * @param callback A callback called when the upload operation terminates, either in success
4872      *                 or in error.
4873      */
4874     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
uploadCallComposerPicture(@onNull InputStream pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)4875     public void uploadCallComposerPicture(@NonNull InputStream pictureToUpload,
4876             @NonNull String contentType,
4877             @CallbackExecutor @NonNull Executor executor,
4878             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
4879         Objects.requireNonNull(pictureToUpload);
4880         Objects.requireNonNull(executor);
4881         Objects.requireNonNull(callback);
4882 
4883         ITelephony telephony = getITelephony();
4884         if (telephony == null) {
4885             throw new IllegalStateException("Telephony service not available.");
4886         }
4887 
4888         ParcelFileDescriptor writeFd;
4889         ParcelFileDescriptor readFd;
4890         try {
4891             ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
4892             writeFd = pipe[1];
4893             readFd = pipe[0];
4894         } catch (IOException e) {
4895             executor.execute(() -> callback.onError(
4896                     new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e)));
4897             return;
4898         }
4899 
4900         OutputStream output = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
4901 
4902         try {
4903             telephony.uploadCallComposerPicture(getSubId(), mContext.getOpPackageName(),
4904                     contentType, readFd, new ResultReceiver(null) {
4905                         @Override
4906                         protected void onReceiveResult(int resultCode, Bundle result) {
4907                             if (resultCode != CallComposerException.SUCCESS) {
4908                                 executor.execute(() -> callback.onError(
4909                                         new CallComposerException(resultCode, null)));
4910                                 return;
4911                             }
4912                             ParcelUuid resultUuid =
4913                                     result.getParcelable(KEY_CALL_COMPOSER_PICTURE_HANDLE, android.os.ParcelUuid.class);
4914                             if (resultUuid == null) {
4915                                 Log.e(TAG, "Got null uuid without an error"
4916                                         + " while uploading call composer pic");
4917                                 executor.execute(() -> callback.onError(
4918                                         new CallComposerException(
4919                                                 CallComposerException.ERROR_UNKNOWN, null)));
4920                                 return;
4921                             }
4922                             executor.execute(() -> callback.onResult(resultUuid));
4923                         }
4924                     });
4925         } catch (RemoteException e) {
4926             Log.e(TAG, "Remote exception uploading call composer pic:" + e);
4927             e.rethrowAsRuntimeException();
4928         }
4929 
4930         executor.execute(() -> {
4931             if (Looper.getMainLooper().isCurrentThread()) {
4932                 Log.w(TAG, "Uploading call composer picture on main thread!"
4933                         + " hic sunt dracones!");
4934             }
4935 
4936             int totalBytesRead = 0;
4937             byte[] buffer = new byte[16 * 1024];
4938             try {
4939                 while (true) {
4940                     int numRead;
4941                     try {
4942                         numRead = pictureToUpload.read(buffer);
4943                     } catch (IOException e) {
4944                         Log.e(TAG, "IOException reading from input while uploading pic: " + e);
4945                         // Most likely, this was because the stream was closed. We have no way to
4946                         // tell though.
4947                         callback.onError(new CallComposerException(
4948                                 CallComposerException.ERROR_INPUT_CLOSED, e));
4949                         try {
4950                             writeFd.closeWithError("input closed");
4951                         } catch (IOException e1) {
4952                             // log and ignore
4953                             Log.e(TAG, "Error closing fd pipe: " + e1);
4954                         }
4955                         break;
4956                     }
4957 
4958                     if (numRead < 0) {
4959                         break;
4960                     }
4961 
4962                     totalBytesRead += numRead;
4963                     if (totalBytesRead > getMaximumCallComposerPictureSize()) {
4964                         Log.e(TAG, "Read too many bytes from call composer pic stream: "
4965                                 + totalBytesRead);
4966                         try {
4967                             callback.onError(new CallComposerException(
4968                                     CallComposerException.ERROR_FILE_TOO_LARGE, null));
4969                             writeFd.closeWithError("too large");
4970                         } catch (IOException e1) {
4971                             // log and ignore
4972                             Log.e(TAG, "Error closing fd pipe: " + e1);
4973                         }
4974                         break;
4975                     }
4976 
4977                     try {
4978                         output.write(buffer, 0, numRead);
4979                     } catch (IOException e) {
4980                         callback.onError(new CallComposerException(
4981                                 CallComposerException.ERROR_REMOTE_END_CLOSED, e));
4982                         try {
4983                             writeFd.closeWithError("remote end closed");
4984                         } catch (IOException e1) {
4985                             // log and ignore
4986                             Log.e(TAG, "Error closing fd pipe: " + e1);
4987                         }
4988                         break;
4989                     }
4990                 }
4991             } finally {
4992                 try {
4993                     output.close();
4994                 } catch (IOException e) {
4995                     // Ignore -- we might've already closed it.
4996                 }
4997             }
4998         });
4999     }
5000 
5001     /**
5002      * Returns the Group Identifier Level1 for a GSM phone.
5003      * Return null if it is unavailable.
5004      *
5005      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5006      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5007      */
5008     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5009     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5010     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getGroupIdLevel1()5011     public String getGroupIdLevel1() {
5012         try {
5013             IPhoneSubInfo info = getSubscriberInfoService();
5014             if (info == null)
5015                 return null;
5016             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
5017                     mContext.getAttributionTag());
5018         } catch (RemoteException ex) {
5019             return null;
5020         } catch (NullPointerException ex) {
5021             // This could happen before phone restarts due to crashing
5022             return null;
5023         }
5024     }
5025 
5026     /**
5027      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
5028      * Return null if it is unavailable.
5029      *
5030      * @param subId whose subscriber id is returned
5031      * @hide
5032      */
5033     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5034     @UnsupportedAppUsage
getGroupIdLevel1(int subId)5035     public String getGroupIdLevel1(int subId) {
5036         try {
5037             IPhoneSubInfo info = getSubscriberInfoService();
5038             if (info == null)
5039                 return null;
5040             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
5041                     mContext.getAttributionTag());
5042         } catch (RemoteException ex) {
5043             return null;
5044         } catch (NullPointerException ex) {
5045             // This could happen before phone restarts due to crashing
5046             return null;
5047         }
5048     }
5049 
5050     /**
5051      * Returns the phone number string for line 1, for example, the MSISDN
5052      * for a GSM phone for a particular subscription. Return null if it is unavailable.
5053      * <p>
5054      * The default SMS app can also use this.
5055      *
5056      * <p>Requires Permission:
5057      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5058      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5059      *     that the caller is the default SMS app,
5060      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5061      *     for any API level.
5062      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5063      *     for apps targeting SDK API level 29 and below.
5064      *
5065      * @deprecated use {@link SubscriptionManager#getPhoneNumber(int)} instead.
5066      */
5067     @Deprecated
5068     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
5069     @RequiresPermission(anyOf = {
5070             android.Manifest.permission.READ_PHONE_STATE,
5071             android.Manifest.permission.READ_SMS,
5072             android.Manifest.permission.READ_PHONE_NUMBERS
5073     })
getLine1Number()5074     public String getLine1Number() {
5075         return getLine1Number(getSubId());
5076     }
5077 
5078     /**
5079      * Returns the phone number string for line 1, for example, the MSISDN
5080      * for a GSM phone for a particular subscription. Return null if it is unavailable.
5081      * <p>
5082      * The default SMS app can also use this.
5083      *
5084      * <p>Requires Permission:
5085      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5086      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5087      *     that the caller is the default SMS app,
5088      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5089      *     for any API level.
5090      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5091      *     for apps targeting SDK API level 29 and below.
5092      *
5093      * @param subId whose phone number for line 1 is returned
5094      * @hide
5095      */
5096     @RequiresPermission(anyOf = {
5097             android.Manifest.permission.READ_PHONE_STATE,
5098             android.Manifest.permission.READ_SMS,
5099             android.Manifest.permission.READ_PHONE_NUMBERS
5100     })
5101     @UnsupportedAppUsage
getLine1Number(int subId)5102     public String getLine1Number(int subId) {
5103         String number = null;
5104         try {
5105             ITelephony telephony = getITelephony();
5106             if (telephony != null)
5107                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
5108                          mContext.getAttributionTag());
5109         } catch (RemoteException ex) {
5110         } catch (NullPointerException ex) {
5111         }
5112         if (number != null) {
5113             return number;
5114         }
5115         try {
5116             IPhoneSubInfo info = getSubscriberInfoService();
5117             if (info == null)
5118                 return null;
5119             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
5120                     mContext.getAttributionTag());
5121         } catch (RemoteException ex) {
5122             return null;
5123         } catch (NullPointerException ex) {
5124             // This could happen before phone restarts due to crashing
5125             return null;
5126         }
5127     }
5128 
5129     /**
5130      * Set the line 1 phone number string and its alphatag for the current ICCID
5131      * for display purpose only, for example, displayed in Phone Status. It won't
5132      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
5133      * value.
5134      *
5135      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5136      *
5137      * @param alphaTag alpha-tagging of the dailing nubmer
5138      * @param number The dialing number
5139      * @return true if the operation was executed correctly.
5140      * @deprecated use {@link SubscriptionManager#setCarrierPhoneNumber(int, String)} instead.
5141      */
5142     @Deprecated
setLine1NumberForDisplay(String alphaTag, String number)5143     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
5144         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
5145     }
5146 
5147     /**
5148      * Set the line 1 phone number string and its alphatag for the current ICCID
5149      * for display purpose only, for example, displayed in Phone Status. It won't
5150      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
5151      * value.
5152      *
5153      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5154      *
5155      * @param subId the subscriber that the alphatag and dialing number belongs to.
5156      * @param alphaTag alpha-tagging of the dailing nubmer
5157      * @param number The dialing number
5158      * @return true if the operation was executed correctly.
5159      * @hide
5160      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)5161     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
5162         try {
5163             // This API is deprecated; call the new API to allow smooth migartion.
5164             // The new API doesn't accept null so convert null to empty string.
5165             mSubscriptionManager.setCarrierPhoneNumber(subId, (number == null ? "" : number));
5166 
5167             ITelephony telephony = getITelephony();
5168             if (telephony != null)
5169                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
5170         } catch (RemoteException ex) {
5171         } catch (NullPointerException ex) {
5172         }
5173         return false;
5174     }
5175 
5176     /**
5177      * Returns the alphabetic identifier associated with the line 1 number.
5178      * Return null if it is unavailable.
5179      * @hide
5180      * nobody seems to call this.
5181      */
5182     @UnsupportedAppUsage
5183     @TestApi
5184     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()5185     public String getLine1AlphaTag() {
5186         return getLine1AlphaTag(getSubId());
5187     }
5188 
5189     /**
5190      * Returns the alphabetic identifier associated with the line 1 number
5191      * for a subscription.
5192      * Return null if it is unavailable.
5193      * @param subId whose alphabetic identifier associated with line 1 is returned
5194      * nobody seems to call this.
5195      * @hide
5196      */
5197     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5198     @UnsupportedAppUsage
getLine1AlphaTag(int subId)5199     public String getLine1AlphaTag(int subId) {
5200         String alphaTag = null;
5201         try {
5202             ITelephony telephony = getITelephony();
5203             if (telephony != null)
5204                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
5205                         getOpPackageName(), getAttributionTag());
5206         } catch (RemoteException ex) {
5207         } catch (NullPointerException ex) {
5208         }
5209         if (alphaTag != null) {
5210             return alphaTag;
5211         }
5212         try {
5213             IPhoneSubInfo info = getSubscriberInfoService();
5214             if (info == null)
5215                 return null;
5216             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
5217                     getAttributionTag());
5218         } catch (RemoteException ex) {
5219             return null;
5220         } catch (NullPointerException ex) {
5221             // This could happen before phone restarts due to crashing
5222             return null;
5223         }
5224     }
5225 
5226     /**
5227      * Return the set of subscriber IDs that should be considered "merged together" for data usage
5228      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
5229      * subscribers are sorted in a deterministic order.
5230      * <p>
5231      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
5232      * TelephonyManager's subId.
5233      *
5234      * This is deprecated and {@link #getMergedImsisFromGroup()} should be used for data
5235      * usage merging purpose.
5236      * TODO: remove this API.
5237      *
5238      * @hide
5239      */
5240     @UnsupportedAppUsage
5241     @Deprecated
getMergedSubscriberIds()5242     public @Nullable String[] getMergedSubscriberIds() {
5243         try {
5244             ITelephony telephony = getITelephony();
5245             if (telephony != null)
5246                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
5247                         getAttributionTag());
5248         } catch (RemoteException ex) {
5249         } catch (NullPointerException ex) {
5250         }
5251         return null;
5252     }
5253 
5254     /**
5255      * Return the set of IMSIs that should be considered "merged together" for data usage
5256      * purposes. This API merges IMSIs based on subscription grouping: IMSI of those in the same
5257      * group will all be returned.
5258      * Return the current IMSI if there is no subscription group, see
5259      * {@link SubscriptionManager#createSubscriptionGroup(List)} for the definition of a group,
5260      * otherwise return an empty array if there is a failure.
5261      *
5262      * @hide
5263      */
5264     @SystemApi
5265     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5266     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getMergedImsisFromGroup()5267     public @NonNull String[] getMergedImsisFromGroup() {
5268         try {
5269             ITelephony telephony = getITelephony();
5270             if (telephony != null) {
5271                 return telephony.getMergedImsisFromGroup(getSubId(), getOpPackageName());
5272             }
5273         } catch (RemoteException ex) {
5274         }
5275         return new String[0];
5276     }
5277 
5278     /**
5279      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
5280      *
5281      * <p>Requires Permission:
5282      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5283      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5284      *     that the caller is the default SMS app,
5285      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5286      *     for any API level.
5287      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5288      *     for apps targeting SDK API level 29 and below.
5289      *
5290      * @hide
5291      */
5292     @RequiresPermission(anyOf = {
5293             android.Manifest.permission.READ_PHONE_STATE,
5294             android.Manifest.permission.READ_SMS,
5295             android.Manifest.permission.READ_PHONE_NUMBERS
5296     })
5297     @UnsupportedAppUsage
getMsisdn()5298     public String getMsisdn() {
5299         return getMsisdn(getSubId());
5300     }
5301 
5302     /**
5303      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
5304      *
5305      * @param subId for which msisdn is returned
5306      *
5307      * <p>Requires Permission:
5308      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5309      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5310      *     that the caller is the default SMS app,
5311      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5312      *     for any API level.
5313      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5314      *     for apps targeting SDK API level 29 and below.
5315      *
5316      * @hide
5317      */
5318     @RequiresPermission(anyOf = {
5319             android.Manifest.permission.READ_PHONE_STATE,
5320             android.Manifest.permission.READ_SMS,
5321             android.Manifest.permission.READ_PHONE_NUMBERS
5322     })
5323     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)5324     public String getMsisdn(int subId) {
5325         try {
5326             IPhoneSubInfo info = getSubscriberInfoService();
5327             if (info == null)
5328                 return null;
5329             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
5330         } catch (RemoteException ex) {
5331             return null;
5332         } catch (NullPointerException ex) {
5333             // This could happen before phone restarts due to crashing
5334             return null;
5335         }
5336     }
5337 
5338     /**
5339      * Returns the voice mail number. Return null if it is unavailable.
5340      *
5341      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5342      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5343      */
5344     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5345     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5346     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceMailNumber()5347     public String getVoiceMailNumber() {
5348         return getVoiceMailNumber(getSubId());
5349     }
5350 
5351     /**
5352      * Returns the voice mail number for a subscription.
5353      * Return null if it is unavailable.
5354      * @param subId whose voice mail number is returned
5355      * @hide
5356      */
5357     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5358     @UnsupportedAppUsage
getVoiceMailNumber(int subId)5359     public String getVoiceMailNumber(int subId) {
5360         try {
5361             IPhoneSubInfo info = getSubscriberInfoService();
5362             if (info == null)
5363                 return null;
5364             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
5365                     getAttributionTag());
5366         } catch (RemoteException ex) {
5367             return null;
5368         } catch (NullPointerException ex) {
5369             // This could happen before phone restarts due to crashing
5370             return null;
5371         }
5372     }
5373 
5374     /**
5375      * Sets the voice mail number.
5376      *
5377      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5378      *
5379      * @param alphaTag The alpha tag to display.
5380      * @param number The voicemail number.
5381      */
5382     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoiceMailNumber(String alphaTag, String number)5383     public boolean setVoiceMailNumber(String alphaTag, String number) {
5384         return setVoiceMailNumber(getSubId(), alphaTag, number);
5385     }
5386 
5387     /**
5388      * Sets the voicemail number for the given subscriber.
5389      *
5390      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5391      *
5392      * @param subId The subscription id.
5393      * @param alphaTag The alpha tag to display.
5394      * @param number The voicemail number.
5395      * @hide
5396      */
setVoiceMailNumber(int subId, String alphaTag, String number)5397     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
5398         try {
5399             ITelephony telephony = getITelephony();
5400             if (telephony != null)
5401                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
5402         } catch (RemoteException ex) {
5403         } catch (NullPointerException ex) {
5404         }
5405         return false;
5406     }
5407 
5408     /**
5409      * Enables or disables the visual voicemail client for a phone account.
5410      *
5411      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
5412      * {@link #hasCarrierPrivileges}), or has permission
5413      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
5414      *
5415      * @param phoneAccountHandle the phone account to change the client state
5416      * @param enabled the new state of the client
5417      * @hide
5418      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5419      * be implemented instead.
5420      */
5421     @SystemApi
5422     @Deprecated
5423     @SuppressLint("RequiresPermission")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)5424     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
5425     }
5426 
5427     /**
5428      * Returns whether the visual voicemail client is enabled.
5429      *
5430      * @param phoneAccountHandle the phone account to check for.
5431      * @return {@code true} when the visual voicemail client is enabled for this client
5432      * @hide
5433      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5434      * be implemented instead.
5435      */
5436     @SystemApi
5437     @Deprecated
5438     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5439     @SuppressLint("RequiresPermission")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)5440     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
5441         return false;
5442     }
5443 
5444     /**
5445      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
5446      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
5447      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
5448      * voicemail client in telephony.
5449      *
5450      * <p>Requires the caller to be the system dialer.
5451      *
5452      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
5453      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
5454      *
5455      * @hide
5456      */
5457     @SystemApi
5458     @SuppressLint("RequiresPermission")
5459     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
5460     @Nullable
getVisualVoicemailSettings()5461     public Bundle getVisualVoicemailSettings(){
5462         try {
5463             ITelephony telephony = getITelephony();
5464             if (telephony != null) {
5465                 return telephony
5466                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
5467             }
5468         } catch (RemoteException ex) {
5469         } catch (NullPointerException ex) {
5470         }
5471         return null;
5472     }
5473 
5474     /**
5475      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
5476      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
5477      * processing visual voicemail for the subscription.
5478      *
5479      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5480      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5481      *
5482      * @see #createForSubscriptionId(int)
5483      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
5484      * @see VisualVoicemailService
5485      */
5486     @Nullable
5487     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5488     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5489     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVisualVoicemailPackageName()5490     public String getVisualVoicemailPackageName() {
5491         try {
5492             ITelephony telephony = getITelephony();
5493             if (telephony != null) {
5494                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
5495                         getAttributionTag(), getSubId());
5496             }
5497         } catch (RemoteException ex) {
5498         } catch (NullPointerException ex) {
5499         }
5500         return null;
5501     }
5502 
5503     /**
5504      * Set the visual voicemail SMS filter settings for the subscription ID pinned
5505      * to the TelephonyManager.
5506      * When the filter is enabled, {@link
5507      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
5508      * called when a SMS matching the settings is received. Caller must be the default dialer,
5509      * system dialer, or carrier visual voicemail app.
5510      *
5511      * @param settings The settings for the filter, or {@code null} to disable the filter.
5512      *
5513      * @see TelecomManager#getDefaultDialerPackage()
5514      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
5515      */
5516     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)5517     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
5518         if (settings == null) {
5519             disableVisualVoicemailSmsFilter(mSubId);
5520         } else {
5521             enableVisualVoicemailSmsFilter(mSubId, settings);
5522         }
5523     }
5524 
5525     /**
5526      * Send a visual voicemail SMS. The caller must be the current default dialer.
5527      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
5528      * visual voicemail server.  Some examples for carriers using the OMTP standard include
5529      * activating and deactivating visual voicemail, or requesting the current visual voicemail
5530      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
5531      * format of these SMS messages.
5532      *
5533      * <p>Requires Permission:
5534      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
5535      *
5536      * @param number The destination number.
5537      * @param port The destination port for data SMS, or 0 for text SMS.
5538      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5539      * @param sentIntent The sent intent passed to the {@link SmsManager}
5540      *
5541      * @throws SecurityException if the caller is not the current default dialer
5542      *
5543      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5544      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5545      */
5546     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)5547     public void sendVisualVoicemailSms(String number, int port, String text,
5548             PendingIntent sentIntent) {
5549         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
5550     }
5551 
5552     /**
5553      * Enables the visual voicemail SMS filter for a phone account. When the filter is
5554      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
5555      * visual voicemail client with
5556      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
5557      *
5558      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5559      * settings persist through default dialer changes, but the filter will only honor the setting
5560      * set by the current default dialer.
5561      *
5562      *
5563      * @param subId The subscription id of the phone account.
5564      * @param settings The settings for the filter.
5565      */
5566     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)5567     public void enableVisualVoicemailSmsFilter(int subId,
5568             VisualVoicemailSmsFilterSettings settings) {
5569         if(settings == null){
5570             throw new IllegalArgumentException("Settings cannot be null");
5571         }
5572         try {
5573             ITelephony telephony = getITelephony();
5574             if (telephony != null) {
5575                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
5576                         settings);
5577             }
5578         } catch (RemoteException ex) {
5579         } catch (NullPointerException ex) {
5580         }
5581     }
5582 
5583     /**
5584      * Disables the visual voicemail SMS filter for a phone account.
5585      *
5586      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5587      * settings persist through default dialer changes, but the filter will only honor the setting
5588      * set by the current default dialer.
5589      */
5590     /** @hide */
disableVisualVoicemailSmsFilter(int subId)5591     public void disableVisualVoicemailSmsFilter(int subId) {
5592         try {
5593             ITelephony telephony = getITelephony();
5594             if (telephony != null) {
5595                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
5596             }
5597         } catch (RemoteException ex) {
5598         } catch (NullPointerException ex) {
5599         }
5600     }
5601 
5602     /**
5603      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
5604      * if the filter is disabled.
5605      *
5606      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5607      * settings persist through default dialer changes, but the filter will only honor the setting
5608      * set by the current default dialer.
5609      */
5610     /** @hide */
5611     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)5612     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
5613         try {
5614             ITelephony telephony = getITelephony();
5615             if (telephony != null) {
5616                 return telephony
5617                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
5618             }
5619         } catch (RemoteException ex) {
5620         } catch (NullPointerException ex) {
5621         }
5622 
5623         return null;
5624     }
5625 
5626     /**
5627      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
5628      * current active visual voicemail client, or {@code null} if the filter is disabled.
5629      *
5630      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
5631      */
5632     /** @hide */
5633     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)5634     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
5635         try {
5636             ITelephony telephony = getITelephony();
5637             if (telephony != null) {
5638                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
5639             }
5640         } catch (RemoteException ex) {
5641         } catch (NullPointerException ex) {
5642         }
5643 
5644         return null;
5645     }
5646 
5647     /**
5648      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
5649      *
5650      * @param phoneAccountHandle The account to send the SMS with.
5651      * @param number The destination number.
5652      * @param port The destination port for data SMS, or 0 for text SMS.
5653      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5654      * @param sentIntent The sent intent passed to the {@link SmsManager}
5655      *
5656      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5657      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5658      *
5659      * @hide
5660      */
5661     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)5662     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
5663             String text, PendingIntent sentIntent) {
5664         try {
5665             ITelephony telephony = getITelephony();
5666             if (telephony != null) {
5667                 telephony.sendVisualVoicemailSmsForSubscriber(
5668                         mContext.getOpPackageName(), mContext.getAttributionTag(), subId, number,
5669                         port, text, sentIntent);
5670             }
5671         } catch (RemoteException ex) {
5672         }
5673     }
5674 
5675     /**
5676      * Initial SIM activation state, unknown. Not set by any carrier apps.
5677      * @hide
5678      */
5679     @SystemApi
5680     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
5681 
5682     /**
5683      * indicate SIM is under activation procedure now.
5684      * intermediate state followed by another state update with activation procedure result:
5685      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5686      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5687      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5688      * @hide
5689      */
5690     @SystemApi
5691     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
5692 
5693     /**
5694      * Indicate SIM has been successfully activated with full service
5695      * @hide
5696      */
5697     @SystemApi
5698     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
5699 
5700     /**
5701      * Indicate SIM has been deactivated by the carrier so that service is not available
5702      * and requires activation service to enable services.
5703      * Carrier apps could be signalled to set activation state to deactivated if detected
5704      * deactivated sim state and set it back to activated after successfully run activation service.
5705      * @hide
5706      */
5707     @SystemApi
5708     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
5709 
5710     /**
5711      * Restricted state indicate SIM has been activated but service are restricted.
5712      * note this is currently available for data activation state. For example out of byte sim.
5713      * @hide
5714      */
5715     @SystemApi
5716     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
5717 
5718      /**
5719       * Sets the voice activation state
5720       *
5721       * <p>Requires Permission:
5722       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5723       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5724       *
5725       * @param activationState The voice activation state
5726       * @see #SIM_ACTIVATION_STATE_UNKNOWN
5727       * @see #SIM_ACTIVATION_STATE_ACTIVATING
5728       * @see #SIM_ACTIVATION_STATE_ACTIVATED
5729       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5730       * @hide
5731       */
5732     @SystemApi
5733     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5734     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoiceActivationState(@imActivationState int activationState)5735     public void setVoiceActivationState(@SimActivationState int activationState) {
5736         setVoiceActivationState(getSubId(), activationState);
5737     }
5738 
5739     /**
5740      * Sets the voice activation state for the given subscriber.
5741      *
5742      * <p>Requires Permission:
5743      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5744      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5745      *
5746      * @param subId The subscription id.
5747      * @param activationState The voice activation state of the given subscriber.
5748      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5749      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5750      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5751      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5752      * @hide
5753      */
5754     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)5755     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
5756         try {
5757            ITelephony telephony = getITelephony();
5758            if (telephony != null)
5759                telephony.setVoiceActivationState(subId, activationState);
5760        } catch (RemoteException ex) {
5761        } catch (NullPointerException ex) {
5762        }
5763     }
5764 
5765     /**
5766      * Sets the data activation state
5767      *
5768      * <p>Requires Permission:
5769      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5770      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5771      *
5772      * @param activationState The data activation state
5773      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5774      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5775      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5776      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5777      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5778      * @hide
5779      */
5780     @SystemApi
5781     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5782     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataActivationState(@imActivationState int activationState)5783     public void setDataActivationState(@SimActivationState int activationState) {
5784         setDataActivationState(getSubId(), activationState);
5785     }
5786 
5787     /**
5788      * Sets the data activation state for the given subscriber.
5789      *
5790      * <p>Requires Permission:
5791      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5792      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5793      *
5794      * @param subId The subscription id.
5795      * @param activationState The data activation state of the given subscriber.
5796      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5797      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5798      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5799      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5800      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5801      * @hide
5802      */
5803     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)5804     public void setDataActivationState(int subId, @SimActivationState int activationState) {
5805         try {
5806             ITelephony telephony = getITelephony();
5807             if (telephony != null)
5808                 telephony.setDataActivationState(subId, activationState);
5809         } catch (RemoteException ex) {
5810         } catch (NullPointerException ex) {
5811         }
5812     }
5813 
5814     /**
5815      * Returns the voice activation state
5816      *
5817      * <p>Requires Permission:
5818      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5819      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5820      *
5821      * @return voiceActivationState
5822      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5823      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5824      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5825      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5826      * @hide
5827      */
5828     @SystemApi
5829     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5830     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceActivationState()5831     public @SimActivationState int getVoiceActivationState() {
5832         return getVoiceActivationState(getSubId());
5833     }
5834 
5835     /**
5836      * Returns the voice activation state for the given subscriber.
5837      *
5838      * <p>Requires Permission:
5839      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5840      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5841      *
5842      * @param subId The subscription id.
5843      *
5844      * @return voiceActivationState for the given subscriber
5845      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5846      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5847      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5848      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5849      * @hide
5850      */
5851     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)5852     public @SimActivationState int getVoiceActivationState(int subId) {
5853         try {
5854             ITelephony telephony = getITelephony();
5855             if (telephony != null)
5856                 return telephony.getVoiceActivationState(subId, getOpPackageName());
5857         } catch (RemoteException ex) {
5858         } catch (NullPointerException ex) {
5859         }
5860         return SIM_ACTIVATION_STATE_UNKNOWN;
5861     }
5862 
5863     /**
5864      * Returns the data activation state
5865      *
5866      * <p>Requires Permission:
5867      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5868      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5869      *
5870      * @return dataActivationState for the given subscriber
5871      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5872      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5873      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5874      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5875      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5876      * @hide
5877      */
5878     @SystemApi
5879     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5880     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataActivationState()5881     public @SimActivationState int getDataActivationState() {
5882         return getDataActivationState(getSubId());
5883     }
5884 
5885     /**
5886      * Returns the data activation state for the given subscriber.
5887      *
5888      * <p>Requires Permission:
5889      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5890      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5891      *
5892      * @param subId The subscription id.
5893      *
5894      * @return dataActivationState for the given subscriber
5895      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5896      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5897      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5898      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5899      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5900      * @hide
5901      */
5902     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)5903     public @SimActivationState int getDataActivationState(int subId) {
5904         try {
5905             ITelephony telephony = getITelephony();
5906             if (telephony != null)
5907                 return telephony.getDataActivationState(subId, getOpPackageName());
5908         } catch (RemoteException ex) {
5909         } catch (NullPointerException ex) {
5910         }
5911         return SIM_ACTIVATION_STATE_UNKNOWN;
5912     }
5913 
5914     /**
5915      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
5916      * but the count is unknown.
5917      * @hide
5918      */
5919     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5920     @UnsupportedAppUsage
getVoiceMessageCount()5921     public int getVoiceMessageCount() {
5922         return getVoiceMessageCount(getSubId());
5923     }
5924 
5925     /**
5926      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
5927      * not have the READ_PHONE_STATE permission.
5928      * @param subId whose voice message count is returned
5929      * @hide
5930      */
5931     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5932     @UnsupportedAppUsage
getVoiceMessageCount(int subId)5933     public int getVoiceMessageCount(int subId) {
5934         try {
5935             ITelephony telephony = getITelephony();
5936             if (telephony == null)
5937                 return 0;
5938             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
5939                     getAttributionTag());
5940         } catch (RemoteException ex) {
5941             return 0;
5942         } catch (NullPointerException ex) {
5943             // This could happen before phone restarts due to crashing
5944             return 0;
5945         }
5946     }
5947 
5948     /**
5949      * Retrieves the alphabetic identifier associated with the voice
5950      * mail number.
5951      *
5952      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5953      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5954      */
5955     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5956     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5957     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceMailAlphaTag()5958     public String getVoiceMailAlphaTag() {
5959         return getVoiceMailAlphaTag(getSubId());
5960     }
5961 
5962     /**
5963      * Retrieves the alphabetic identifier associated with the voice
5964      * mail number for a subscription.
5965      * @param subId whose alphabetic identifier associated with the
5966      * voice mail number is returned
5967      * @hide
5968      */
5969     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5970     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)5971     public String getVoiceMailAlphaTag(int subId) {
5972         try {
5973             IPhoneSubInfo info = getSubscriberInfoService();
5974             if (info == null)
5975                 return null;
5976             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
5977                     getAttributionTag());
5978         } catch (RemoteException ex) {
5979             return null;
5980         } catch (NullPointerException ex) {
5981             // This could happen before phone restarts due to crashing
5982             return null;
5983         }
5984     }
5985 
5986     /**
5987      * Send the special dialer code. The IPC caller must be the current default dialer or have
5988      * carrier privileges (see {@link #hasCarrierPrivileges}).
5989      *
5990      * @param inputCode The special dialer code to send
5991      *
5992      * @throws SecurityException if the caller does not have carrier privileges or is not the
5993      *         current default dialer
5994      */
sendDialerSpecialCode(String inputCode)5995     public void sendDialerSpecialCode(String inputCode) {
5996         try {
5997             final ITelephony telephony = getITelephony();
5998             if (telephony == null) {
5999                 return;
6000             }
6001             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
6002         } catch (RemoteException ex) {
6003             Rlog.e(TAG, "Telephony#sendDialerSpecialCode RemoteException" + ex);
6004         }
6005     }
6006 
6007     /**
6008      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
6009      * @return the IMPI, or null if not present or not loaded
6010      * @hide
6011      * @deprecated use {@link #getImsPrivateUserIdentity()}
6012      */
6013     @UnsupportedAppUsage
getIsimImpi()6014     public String getIsimImpi() {
6015         try {
6016             IPhoneSubInfo info = getSubscriberInfoService();
6017             if (info == null)
6018                 return null;
6019             //get the Isim Impi based on subId
6020             return info.getIsimImpi(getSubId());
6021         } catch (RemoteException ex) {
6022             return null;
6023         } catch (NullPointerException ex) {
6024             // This could happen before phone restarts due to crashing
6025             return null;
6026         }
6027     }
6028 
6029     /**
6030      * Returns the IMS private user identity (IMPI) of the subscription that was loaded from the
6031      * ISIM records {@link #APPTYPE_ISIM}. This value is fetched from the Elementary file EF_IMPI.
6032      * The contents of the file is a <b>Ip Multimedia Service Private User Identity</b> of the user
6033      * as defined in the section 4.2.2 of 3GPP TS 131 103.
6034      *
6035      * @return IMPI (IMS private user identity) of type string.
6036      * @throws IllegalStateException in case the ISIM has’t been loaded
6037      * @throws SecurityException if the caller does not have the required permission/privileges
6038      * @hide
6039      */
6040     @NonNull
6041     @RequiresPermission(android.Manifest.permission.USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER)
6042     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getImsPrivateUserIdentity()6043     public String getImsPrivateUserIdentity() {
6044         try {
6045             IPhoneSubInfo info = getSubscriberInfoService();
6046             if (info == null) {
6047                 Rlog.e(TAG, "getImsPrivateUserIdentity(): IPhoneSubInfo instance is NULL");
6048                 throw new RuntimeException("IMPI error: Subscriber Info is null");
6049             }
6050             return info.getImsPrivateUserIdentity(getSubId(), getOpPackageName(),
6051                     getAttributionTag());
6052         } catch (RemoteException | NullPointerException | IllegalArgumentException ex) {
6053             Rlog.e(TAG, "getImsPrivateUserIdentity() Exception = " + ex);
6054             throw new RuntimeException(ex.getMessage());
6055         }
6056     }
6057 
6058     /**
6059      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
6060      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
6061      * hasn't been loaded or isn't present on the ISIM.
6062      *
6063      * <p>Requires Permission:
6064      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6065      * @hide
6066      */
6067     @Nullable
6068     @SystemApi
6069     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6070     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIsimDomain()6071     public String getIsimDomain() {
6072         try {
6073             IPhoneSubInfo info = getSubscriberInfoService();
6074             if (info == null)
6075                 return null;
6076             //get the Isim Domain based on subId
6077             return info.getIsimDomain(getSubId());
6078         } catch (RemoteException ex) {
6079             return null;
6080         } catch (NullPointerException ex) {
6081             // This could happen before phone restarts due to crashing
6082             return null;
6083         }
6084     }
6085 
6086     /**
6087      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
6088      * @return an array of IMPU strings, with one IMPU per string, or null if
6089      *      not present or not loaded
6090      * @hide
6091      * @deprecated use {@link #getImsPublicUserIdentities()}
6092      */
6093     @UnsupportedAppUsage
6094     @Nullable
6095     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()6096     public String[] getIsimImpu() {
6097         try {
6098             IPhoneSubInfo info = getSubscriberInfoService();
6099             if (info == null)
6100                 return null;
6101             //get the Isim Impu based on subId
6102             return info.getIsimImpu(getSubId());
6103         } catch (RemoteException ex) {
6104             return null;
6105         } catch (NullPointerException ex) {
6106             // This could happen before phone restarts due to crashing
6107             return null;
6108         }
6109     }
6110 
6111     /**
6112      * Returns the IMS public user identities (IMPU) of the subscription that was loaded from the
6113      * ISIM records {@link #APPTYPE_ISIM}. This value is fetched from the Elementary file EF_IMPU.
6114      * The contents of the file are <b>Ip Multimedia Service Public User Identities</b> of the user
6115      * as defined in the section 4.2.4 of 3GPP TS 131 103. It contains one or more records.
6116      *
6117      * @return List of public user identities of type android.net.Uri or empty list  if
6118      *         EF_IMPU is not available.
6119      * @throws IllegalStateException in case the ISIM hasn’t been loaded
6120      * @throws SecurityException if the caller does not have the required permission/privilege
6121      * @hide
6122      */
6123     @NonNull
6124     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PHONE_NUMBERS,
6125             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
6126     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getImsPublicUserIdentities()6127     public List<Uri> getImsPublicUserIdentities() {
6128         try {
6129             IPhoneSubInfo info = getSubscriberInfoService();
6130             if (info == null) {
6131                 throw new RuntimeException("IMPU error: Subscriber Info is null");
6132             }
6133             return info.getImsPublicUserIdentities(getSubId(), getOpPackageName(),
6134                     getAttributionTag());
6135         } catch (IllegalArgumentException | NullPointerException ex) {
6136             Rlog.e(TAG, "getImsPublicUserIdentities Exception = " + ex);
6137         } catch (RemoteException ex) {
6138             Rlog.e(TAG, "getImsPublicUserIdentities Exception = " + ex);
6139             ex.rethrowAsRuntimeException();
6140         }
6141         return Collections.EMPTY_LIST;
6142     }
6143 
6144     /**
6145      * Device call state: No activity.
6146      */
6147     public static final int CALL_STATE_IDLE = 0;
6148     /**
6149      * Device call state: Ringing. A new call arrived and is
6150      *  ringing or waiting. In the latter case, another call is
6151      *  already active.
6152      */
6153     public static final int CALL_STATE_RINGING = 1;
6154     /**
6155      * Device call state: Off-hook. At least one call exists
6156      * that is dialing, active, or on hold, and no calls are ringing
6157      * or waiting.
6158      */
6159     public static final int CALL_STATE_OFFHOOK = 2;
6160 
6161     /**
6162      * Returns the state of all calls on the device.
6163      * <p>
6164      * This method considers not only calls in the Telephony stack, but also calls via other
6165      * {@link android.telecom.ConnectionService} implementations.
6166      * <p>
6167      * Note: The call state returned via this method may differ from what is reported by
6168      * {@link PhoneStateListener#onCallStateChanged(int, String)}, as that callback only considers
6169      * Telephony (mobile) calls.
6170      * <p>
6171      * Requires Permission:
6172      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
6173      * targeting API level 31+.
6174      *
6175      * @return the current call state.
6176      * @deprecated Use {@link #getCallStateForSubscription} to retrieve the call state for a
6177      * specific telephony subscription (which allows carrier privileged apps),
6178      * {@link TelephonyCallback.CallStateListener} for real-time call state updates, or
6179      * {@link TelecomManager#isInCall()}, which supplies an aggregate "in call" state for the entire
6180      * device.
6181      */
6182     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
6183     @Deprecated
getCallState()6184     public @CallState int getCallState() {
6185         if (mContext != null) {
6186             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
6187             if (telecomManager != null) {
6188                 return telecomManager.getCallState();
6189             }
6190         }
6191         return CALL_STATE_IDLE;
6192     }
6193 
6194     /**
6195      * Retrieve the call state for a specific subscription that was specified when this
6196      * TelephonyManager instance was created.
6197      * <p>Requires Permission:
6198      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the calling
6199      * application has carrier privileges (see {@link #hasCarrierPrivileges}).
6200      * @see TelephonyManager#createForSubscriptionId(int)
6201      * @see TelephonyManager#createForPhoneAccountHandle(PhoneAccountHandle)
6202      * @return The call state of the subscription associated with this TelephonyManager instance.
6203      */
6204     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6205     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallStateForSubscription()6206     public @CallState int getCallStateForSubscription() {
6207         return getCallState(getSubId());
6208     }
6209 
6210     /**
6211      * Returns the Telephony call state for calls on a specific subscription.
6212      * <p>
6213      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
6214      * considers the state of calls from other {@link android.telecom.ConnectionService}
6215      * implementations.
6216      * <p>
6217      * Requires Permission:
6218      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
6219      * targeting API level 31+ or that the calling application has carrier privileges
6220      * (see {@link #hasCarrierPrivileges()}).
6221      *
6222      * @param subId the subscription to check call state for.
6223      * @hide
6224      */
6225     @UnsupportedAppUsage
6226     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
getCallState(int subId)6227     public @CallState int getCallState(int subId) {
6228         ITelephony telephony = getITelephony();
6229         if (telephony == null) {
6230             return CALL_STATE_IDLE;
6231         }
6232         try {
6233             return telephony.getCallStateForSubscription(subId, mContext.getPackageName(),
6234                     mContext.getAttributionTag());
6235         } catch (RemoteException e) {
6236             return CALL_STATE_IDLE;
6237         }
6238     }
6239 
6240     /** Data connection activity: No traffic. */
6241     public static final int DATA_ACTIVITY_NONE = 0x00000000;
6242     /** Data connection activity: Currently receiving IP PPP traffic. */
6243     public static final int DATA_ACTIVITY_IN = 0x00000001;
6244     /** Data connection activity: Currently sending IP PPP traffic. */
6245     public static final int DATA_ACTIVITY_OUT = 0x00000002;
6246     /** Data connection activity: Currently both sending and receiving
6247      *  IP PPP traffic. */
6248     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
6249     /**
6250      * Data connection is active, but physical link is down
6251      */
6252     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
6253 
6254     /**
6255      * Returns a constant indicating the type of activity on a data connection
6256      * (cellular).
6257      *
6258      * @see #DATA_ACTIVITY_NONE
6259      * @see #DATA_ACTIVITY_IN
6260      * @see #DATA_ACTIVITY_OUT
6261      * @see #DATA_ACTIVITY_INOUT
6262      * @see #DATA_ACTIVITY_DORMANT
6263      */
6264     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataActivity()6265     public int getDataActivity() {
6266         try {
6267             ITelephony telephony = getITelephony();
6268             if (telephony == null)
6269                 return DATA_ACTIVITY_NONE;
6270             return telephony.getDataActivityForSubId(
6271                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
6272         } catch (RemoteException ex) {
6273             // the phone process is restarting.
6274             return DATA_ACTIVITY_NONE;
6275         } catch (NullPointerException ex) {
6276           // the phone process is restarting.
6277           return DATA_ACTIVITY_NONE;
6278       }
6279     }
6280 
6281     /** @hide */
6282     @IntDef(prefix = {"DATA_"}, value = {
6283             DATA_UNKNOWN,
6284             DATA_DISCONNECTED,
6285             DATA_CONNECTING,
6286             DATA_CONNECTED,
6287             DATA_SUSPENDED,
6288             DATA_DISCONNECTING,
6289             DATA_HANDOVER_IN_PROGRESS,
6290     })
6291     @Retention(RetentionPolicy.SOURCE)
6292     public @interface DataState{}
6293 
6294     /** Data connection state: Unknown.  Used before we know the state. */
6295     public static final int DATA_UNKNOWN        = -1;
6296     /** Data connection state: Disconnected. IP traffic not available. */
6297     public static final int DATA_DISCONNECTED   = 0;
6298     /** Data connection state: Currently setting up a data connection. */
6299     public static final int DATA_CONNECTING     = 1;
6300     /** Data connection state: Connected. IP traffic should be available. */
6301     public static final int DATA_CONNECTED      = 2;
6302     /** Data connection state: Suspended. The connection is up, but IP
6303      * traffic is temporarily unavailable. For example, in a 2G network,
6304      * data activity may be suspended when a voice call arrives. */
6305     public static final int DATA_SUSPENDED      = 3;
6306     /**
6307      * Data connection state: Disconnecting.
6308      *
6309      * IP traffic may be available but will cease working imminently.
6310      */
6311     public static final int DATA_DISCONNECTING = 4;
6312 
6313     /**
6314      * Data connection state: Handover in progress. The connection is being transited from cellular
6315      * network to IWLAN, or from IWLAN to cellular network.
6316      */
6317     public static final int DATA_HANDOVER_IN_PROGRESS = 5;
6318 
6319     /**
6320      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
6321      */
6322     @ChangeId
6323     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
6324     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
6325 
6326     /**
6327      * Returns a constant indicating the current data connection state
6328      * (cellular).
6329      *
6330      * @see #DATA_DISCONNECTED
6331      * @see #DATA_CONNECTING
6332      * @see #DATA_CONNECTED
6333      * @see #DATA_SUSPENDED
6334      * @see #DATA_DISCONNECTING
6335      * @see #DATA_HANDOVER_IN_PROGRESS
6336      */
6337     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataState()6338     public int getDataState() {
6339         try {
6340             ITelephony telephony = getITelephony();
6341             if (telephony == null)
6342                 return DATA_DISCONNECTED;
6343             int state = telephony.getDataStateForSubId(
6344                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
6345             if (state == TelephonyManager.DATA_DISCONNECTING
6346                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
6347                 return TelephonyManager.DATA_CONNECTED;
6348             }
6349 
6350             return state;
6351         } catch (RemoteException ex) {
6352             // the phone process is restarting.
6353             return DATA_DISCONNECTED;
6354         } catch (NullPointerException ex) {
6355             return DATA_DISCONNECTED;
6356         }
6357     }
6358 
6359     /**
6360      * @hide
6361      */
6362     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getITelephony()6363     private ITelephony getITelephony() {
6364         // Keeps cache disabled until test fixes are checked into AOSP.
6365         if (!sServiceHandleCacheEnabled) {
6366             return ITelephony.Stub.asInterface(
6367                     TelephonyFrameworkInitializer
6368                             .getTelephonyServiceManager()
6369                             .getTelephonyServiceRegisterer()
6370                             .get());
6371         }
6372 
6373         if (sITelephony == null) {
6374             ITelephony temp = ITelephony.Stub.asInterface(
6375                     TelephonyFrameworkInitializer
6376                             .getTelephonyServiceManager()
6377                             .getTelephonyServiceRegisterer()
6378                             .get());
6379             synchronized (sCacheLock) {
6380                 if (sITelephony == null && temp != null) {
6381                     try {
6382                         sITelephony = temp;
6383                         sITelephony.asBinder().linkToDeath(sServiceDeath, 0);
6384                     } catch (Exception e) {
6385                         // something has gone horribly wrong
6386                         sITelephony = null;
6387                     }
6388                 }
6389             }
6390         }
6391         return sITelephony;
6392     }
6393 
getIOns()6394     private IOns getIOns() {
6395         return IOns.Stub.asInterface(
6396                 TelephonyFrameworkInitializer
6397                         .getTelephonyServiceManager()
6398                         .getOpportunisticNetworkServiceRegisterer()
6399                         .get());
6400     }
6401 
6402     //
6403     //
6404     // PhoneStateListener
6405     //
6406     //
6407 
6408     /**
6409      * Registers a listener object to receive notification of changes
6410      * in specified telephony states.
6411      * <p>
6412      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
6413      * state of interest in the events argument.
6414      *
6415      * At registration, and when a specified telephony state changes, the telephony manager invokes
6416      * the appropriate callback method on the listener object and passes the current (updated)
6417      * values.
6418      * <p>
6419      * To un-register a listener, pass the listener object and set the events argument to
6420      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
6421      *
6422      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
6423      * applies to the given subId. Otherwise, applies to
6424      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
6425      * pass a separate listener object to each TelephonyManager object created with
6426      * {@link #createForSubscriptionId}.
6427      *
6428      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
6429      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
6430      * {@link SecurityException} will be thrown otherwise.
6431      *
6432      * This API should be used sparingly -- large numbers of listeners will cause system
6433      * instability. If a process has registered too many listeners without unregistering them, it
6434      * may encounter an {@link IllegalStateException} when trying to register more listeners.
6435      *
6436      * @param listener The {@link PhoneStateListener} object to register
6437      *                 (or unregister)
6438      * @param events The telephony state(s) of interest to the listener,
6439      *               as a bitwise-OR combination of {@link PhoneStateListener}
6440      *               LISTEN_ flags.
6441      * @deprecated Use {@link #registerTelephonyCallback(Executor, TelephonyCallback)}.
6442      */
6443     @Deprecated
listen(PhoneStateListener listener, int events)6444     public void listen(PhoneStateListener listener, int events) {
6445         if (mContext == null) return;
6446         boolean notifyNow = (getITelephony() != null);
6447         TelephonyRegistryManager telephonyRegistry =
6448                 (TelephonyRegistryManager)
6449                         mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
6450         if (telephonyRegistry != null) {
6451             Set<String> renouncedPermissions = getRenouncedPermissions();
6452             boolean renounceFineLocationAccess = renouncedPermissions
6453                     .contains(Manifest.permission.ACCESS_FINE_LOCATION);
6454             boolean renounceCoarseLocationAccess = renouncedPermissions
6455                     .contains(Manifest.permission.ACCESS_COARSE_LOCATION);
6456             telephonyRegistry.listenFromListener(mSubId, renounceFineLocationAccess,
6457                     renounceCoarseLocationAccess, getOpPackageName(), getAttributionTag(),
6458                     listener, events, notifyNow);
6459         } else {
6460             Rlog.w(TAG, "telephony registry not ready.");
6461         }
6462     }
6463 
6464     /** @hide */
6465     @Retention(RetentionPolicy.SOURCE)
6466     @IntDef(prefix = {"ERI_"}, value = {
6467             ERI_ON,
6468             ERI_OFF,
6469             ERI_FLASH
6470     })
6471     public @interface EriIconIndex {}
6472 
6473     /**
6474      * ERI (Enhanced Roaming Indicator) is ON i.e value 0 defined by
6475      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6476      */
6477     public static final int ERI_ON = 0;
6478 
6479     /**
6480      * ERI (Enhanced Roaming Indicator) is OFF i.e value 1 defined by
6481      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6482      */
6483     public static final int ERI_OFF = 1;
6484 
6485     /**
6486      * ERI (Enhanced Roaming Indicator) is FLASH i.e value 2 defined by
6487      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6488      */
6489     public static final int ERI_FLASH = 2;
6490 
6491     /** @hide */
6492     @Retention(RetentionPolicy.SOURCE)
6493     @IntDef(prefix = {"ERI_ICON_MODE_"}, value = {
6494             ERI_ICON_MODE_NORMAL,
6495             ERI_ICON_MODE_FLASH
6496     })
6497     public @interface EriIconMode {}
6498 
6499     /**
6500      * ERI (Enhanced Roaming Indicator) icon mode is normal. This constant represents that
6501      * the ERI icon should be displayed normally.
6502      *
6503      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6504      * @hide
6505      */
6506     public static final int ERI_ICON_MODE_NORMAL = 0;
6507 
6508     /**
6509      * ERI (Enhanced Roaming Indicator) icon mode flash. This constant represents that
6510      * the ERI icon should be flashing.
6511      *
6512      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6513      * @hide
6514      */
6515     public static final int ERI_ICON_MODE_FLASH = 1;
6516 
6517     /**
6518      * Returns the CDMA ERI icon display number. The number is assigned by
6519      * 3GPP2 C.R1001-H v1.0 Table 8.1-1. Additionally carriers define their own ERI display numbers.
6520      * Defined values are {@link #ERI_ON}, {@link #ERI_OFF}, and {@link #ERI_FLASH}.
6521      * @hide
6522      */
6523     @SystemApi
6524     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaEnhancedRoamingIndicatorDisplayNumber()6525     public @EriIconIndex int getCdmaEnhancedRoamingIndicatorDisplayNumber() {
6526         return getCdmaEriIconIndex(getSubId());
6527     }
6528 
6529     /**
6530      * Returns the CDMA ERI icon index to display for a subscription.
6531      * @hide
6532      */
6533     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6534     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)6535     public @EriIconIndex int getCdmaEriIconIndex(int subId) {
6536         try {
6537             ITelephony telephony = getITelephony();
6538             if (telephony == null)
6539                 return -1;
6540             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
6541                     getAttributionTag());
6542         } catch (RemoteException ex) {
6543             // the phone process is restarting.
6544             return -1;
6545         } catch (NullPointerException ex) {
6546             return -1;
6547         }
6548     }
6549 
6550     /**
6551      * Returns the CDMA ERI icon mode for a subscription.
6552      * 0 - ON
6553      * 1 - FLASHING
6554      *
6555      * @hide
6556      */
6557     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6558     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)6559     public @EriIconMode int getCdmaEriIconMode(int subId) {
6560         try {
6561             ITelephony telephony = getITelephony();
6562             if (telephony == null)
6563                 return -1;
6564             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
6565                     getAttributionTag());
6566         } catch (RemoteException ex) {
6567             // the phone process is restarting.
6568             return -1;
6569         } catch (NullPointerException ex) {
6570             return -1;
6571         }
6572     }
6573 
6574     /**
6575      * Returns the CDMA ERI text,
6576      *
6577      * @hide
6578      */
6579     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()6580     public String getCdmaEriText() {
6581         return getCdmaEriText(getSubId());
6582     }
6583 
6584     /**
6585      * Returns the CDMA ERI text, of a subscription
6586      *
6587      * @hide
6588      */
6589     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6590     @UnsupportedAppUsage
getCdmaEriText(int subId)6591     public String getCdmaEriText(int subId) {
6592         try {
6593             ITelephony telephony = getITelephony();
6594             if (telephony == null)
6595                 return null;
6596             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
6597                     getAttributionTag());
6598         } catch (RemoteException ex) {
6599             // the phone process is restarting.
6600             return null;
6601         } catch (NullPointerException ex) {
6602             return null;
6603         }
6604     }
6605 
6606     /**
6607      * @return true if the current device is "voice capable".
6608      * <p>
6609      * "Voice capable" means that this device supports circuit-switched
6610      * (i.e. voice) phone calls over the telephony network, and is allowed
6611      * to display the in-call UI while a cellular voice call is active.
6612      * This will be false on "data only" devices which can't make voice
6613      * calls and don't support any in-call UI.
6614      * <p>
6615      * Note: the meaning of this flag is subtly different from the
6616      * PackageManager.FEATURE_TELEPHONY system feature, which is available
6617      * on any device with a telephony radio, even if the device is
6618      * data-only.
6619      */
6620     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isVoiceCapable()6621     public boolean isVoiceCapable() {
6622         if (mContext == null) return true;
6623         return mContext.getResources().getBoolean(
6624                 com.android.internal.R.bool.config_voice_capable);
6625     }
6626 
6627     /**
6628      * @return true if the current device supports sms service.
6629      * <p>
6630      * If true, this means that the device supports both sending and
6631      * receiving sms via the telephony network.
6632      * <p>
6633      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
6634      *       disabled when device doesn't support sms.
6635      */
6636     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
isSmsCapable()6637     public boolean isSmsCapable() {
6638         if (mContext == null) return true;
6639         return mContext.getResources().getBoolean(
6640                 com.android.internal.R.bool.config_sms_capable);
6641     }
6642 
6643     /**
6644      * Requests all available cell information from all radios on the device including the
6645      * camped/registered, serving, and neighboring cells.
6646      *
6647      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
6648      * {@link android.telephony.CellInfoCdma CellInfoCdma},
6649      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
6650      * {@link android.telephony.CellInfoLte CellInfoLte}, and
6651      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
6652      * It is typical to see instances of one or more of any these in the list. In addition, zero
6653      * or more of the returned objects may be considered registered; that is, their
6654      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
6655      * methods may return true, indicating that the cell is being used or would be used for
6656      * signaling communication if necessary.
6657      *
6658      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
6659      * if this API results in a change of the cached CellInfo, that change will be reported via
6660      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}.
6661      *
6662      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
6663      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
6664      * will receive the latest cached results, which may not be current. Apps targeting
6665      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
6666      * CellInfo should call
6667      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
6668      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
6669      * recency of CellInfo data, callers should check
6670      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
6671      *
6672      * <p>This method returns valid data for devices with
6673      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
6674      * where only partial information is available for a particular CellInfo entry, unavailable
6675      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
6676      * cells will include at least a valid set of technology-specific identification info and a
6677      * power level measurement.
6678      *
6679      * <p>This method is preferred over using {@link
6680      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
6681      *
6682      * @return List of {@link android.telephony.CellInfo}; null if cell
6683      * information is unavailable.
6684      */
6685     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
6686     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getAllCellInfo()6687     public List<CellInfo> getAllCellInfo() {
6688         try {
6689             ITelephony telephony = getITelephony();
6690             if (telephony == null)
6691                 return null;
6692             return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
6693         } catch (RemoteException ex) {
6694         } catch (NullPointerException ex) {
6695         }
6696         return null;
6697     }
6698 
6699     /** Callback for providing asynchronous {@link CellInfo} on request */
6700     public abstract static class CellInfoCallback {
6701         /**
6702          * Success response to
6703          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
6704          *
6705          * Invoked when there is a response to
6706          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
6707          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
6708          * list will be provided. If an error occurs, null will be provided unless the onError
6709          * callback is overridden.
6710          *
6711          * @param cellInfo a list of {@link CellInfo} or an empty list.
6712          *
6713          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
6714          */
onCellInfo(@onNull List<CellInfo> cellInfo)6715         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
6716 
6717         /** @hide */
6718         @Retention(RetentionPolicy.SOURCE)
6719         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
6720         public @interface CellInfoCallbackError {}
6721 
6722         /**
6723          * The system timed out waiting for a response from the Radio.
6724          */
6725         public static final int ERROR_TIMEOUT = 1;
6726 
6727         /**
6728          * The modem returned a failure.
6729          */
6730         public static final int ERROR_MODEM_ERROR = 2;
6731 
6732         /**
6733          * Error response to
6734          * {@link TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
6735          *
6736          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
6737          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
6738          * function to receive detailed status information in the event of an error. By default,
6739          * this function will invoke onCellInfo() with null.
6740          *
6741          * @param errorCode an error code indicating the type of failure.
6742          * @param detail a Throwable object with additional detail regarding the failure if
6743          *     available, otherwise null.
6744          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)6745         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
6746             // By default, simply invoke the success callback with an empty list.
6747             onCellInfo(new ArrayList<CellInfo>());
6748         }
6749     };
6750 
6751     /**
6752      * Used for checking if the target SDK version for the current process is S or above.
6753      *
6754      * <p> Applies to the following methods:
6755      * {@link #requestCellInfoUpdate},
6756      * {@link #setPreferredOpportunisticDataSubscription},
6757      * {@link #updateAvailableNetworks},
6758      * requestNumberVerification(),
6759      * setSimPowerStateForSlot(),
6760      */
6761     @ChangeId
6762     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.R)
6763     private static final long NULL_TELEPHONY_THROW_NO_CB = 182185642L;
6764 
6765     /**
6766      * Requests all available cell information from the current subscription for observed
6767      * camped/registered, serving, and neighboring cells.
6768      *
6769      * <p>Any available results from this request will be provided by calls to
6770      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
6771      * for each active subscription.
6772      *
6773      * <p>This method returns valid data for devices with
6774      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
6775      * that do not implement this feature, the behavior is not reliable.
6776      *
6777      * @param executor the executor on which callback will be invoked.
6778      * @param callback a callback to receive CellInfo.
6779      */
6780     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
6781     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)6782     public void requestCellInfoUpdate(
6783             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
6784         try {
6785             ITelephony telephony = getITelephony();
6786             if (telephony == null) {
6787                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
6788                     throw new IllegalStateException("Telephony is null");
6789                 } else {
6790                     return;
6791                 }
6792             }
6793 
6794             telephony.requestCellInfoUpdate(
6795                     getSubId(),
6796                     new ICellInfoCallback.Stub() {
6797                         @Override
6798                         public void onCellInfo(List<CellInfo> cellInfo) {
6799                             final long identity = Binder.clearCallingIdentity();
6800                             try {
6801                                 executor.execute(() -> callback.onCellInfo(cellInfo));
6802                             } finally {
6803                                 Binder.restoreCallingIdentity(identity);
6804                             }
6805                         }
6806 
6807                         @Override
6808                         public void onError(int errorCode, String exceptionName, String message) {
6809                             final long identity = Binder.clearCallingIdentity();
6810                             try {
6811                                 executor.execute(() -> callback.onError(
6812                                         errorCode,
6813                                         createThrowableByClassName(exceptionName, message)));
6814                             } finally {
6815                                 Binder.restoreCallingIdentity(identity);
6816                             }
6817                         }
6818                     }, getOpPackageName(), getAttributionTag());
6819         } catch (RemoteException ex) {
6820             runOnBackgroundThread(() -> executor.execute(
6821                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
6822         }
6823     }
6824 
6825     /**
6826      * Requests all available cell information from the current subscription for observed
6827      * camped/registered, serving, and neighboring cells.
6828      *
6829      * <p>Any available results from this request will be provided by calls to
6830      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
6831      * for each active subscription.
6832      *
6833      * <p>This method returns valid data for devices with
6834      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
6835      * that do not implement this feature, the behavior is not reliable.
6836      *
6837      * @param workSource the requestor to whom the power consumption for this should be attributed.
6838      * @param executor the executor on which callback will be invoked.
6839      * @param callback a callback to receive CellInfo.
6840      * @hide
6841      */
6842     @SystemApi
6843     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
6844             android.Manifest.permission.MODIFY_PHONE_STATE})
6845     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)6846     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
6847             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
6848         try {
6849             ITelephony telephony = getITelephony();
6850             if (telephony == null) {
6851                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
6852                     throw new IllegalStateException("Telephony is null");
6853                 } else {
6854                     return;
6855                 }
6856             }
6857 
6858             telephony.requestCellInfoUpdateWithWorkSource(
6859                     getSubId(),
6860                     new ICellInfoCallback.Stub() {
6861                         @Override
6862                         public void onCellInfo(List<CellInfo> cellInfo) {
6863                             final long identity = Binder.clearCallingIdentity();
6864                             try {
6865                                 executor.execute(() -> callback.onCellInfo(cellInfo));
6866                             } finally {
6867                                 Binder.restoreCallingIdentity(identity);
6868                             }
6869 
6870                         }
6871 
6872                         @Override
6873                         public void onError(int errorCode, String exceptionName, String message) {
6874                             final long identity = Binder.clearCallingIdentity();
6875                             try {
6876                                 executor.execute(() -> callback.onError(
6877                                         errorCode,
6878                                         createThrowableByClassName(exceptionName, message)));
6879                             } finally {
6880                                 Binder.restoreCallingIdentity(identity);
6881                             }
6882                         }
6883                     }, getOpPackageName(), getAttributionTag(), workSource);
6884         } catch (RemoteException ex) {
6885             runOnBackgroundThread(() -> executor.execute(
6886                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
6887         }
6888     }
6889 
createThrowableByClassName(String className, String message)6890     private static Throwable createThrowableByClassName(String className, String message) {
6891         if (className == null) {
6892             return null;
6893         }
6894         try {
6895             Class<?> c = Class.forName(className);
6896             return (Throwable) c.getConstructor(String.class).newInstance(message);
6897         } catch (ReflectiveOperationException | ClassCastException e) {
6898         }
6899         return new RuntimeException(className + ": " + message);
6900     }
6901 
6902     /**
6903      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
6904      * PhoneStateListener.onCellInfoChanged} will be invoked.
6905      *<p>
6906      * The default, 0, means invoke onCellInfoChanged when any of the reported
6907      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
6908      * A onCellInfoChanged.
6909      *<p>
6910      * @param rateInMillis the rate
6911      *
6912      * @hide
6913      */
setCellInfoListRate(int rateInMillis, int subId)6914     public void setCellInfoListRate(int rateInMillis, int subId) {
6915         try {
6916             ITelephony telephony = getITelephony();
6917             if (telephony != null)
6918                 telephony.setCellInfoListRate(rateInMillis, subId);
6919         } catch (RemoteException ex) {
6920         } catch (NullPointerException ex) {
6921         }
6922     }
6923 
6924     /**
6925      * Returns the MMS user agent.
6926      */
6927     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getMmsUserAgent()6928     public String getMmsUserAgent() {
6929         try {
6930             ITelephony telephony = getITelephony();
6931             if (telephony != null) {
6932                 return telephony.getMmsUserAgent(getSubId());
6933             }
6934         } catch (RemoteException ex) {
6935         } catch (NullPointerException ex) {
6936         }
6937         return null;
6938     }
6939 
6940     /**
6941      * Returns the MMS user agent profile URL.
6942      */
6943     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getMmsUAProfUrl()6944     public String getMmsUAProfUrl() {
6945         try {
6946             ITelephony telephony = getITelephony();
6947             if (telephony != null) {
6948                 return telephony.getMmsUAProfUrl(getSubId());
6949             }
6950         } catch (RemoteException ex) {
6951         } catch (NullPointerException ex) {
6952         }
6953         return null;
6954     }
6955 
6956     /**
6957      * Get the first active portIndex from the corresponding physical slot index.
6958      * @param physicalSlotIndex physical slot index
6959      * @return first active port index or INVALID_PORT_INDEX if no port is active
6960      */
getFirstActivePortIndex(int physicalSlotIndex)6961     private int getFirstActivePortIndex(int physicalSlotIndex) {
6962         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
6963         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length
6964                 && slotInfos[physicalSlotIndex] != null) {
6965             Optional<UiccPortInfo> result =  slotInfos[physicalSlotIndex].getPorts().stream()
6966                     .filter(portInfo -> portInfo.isActive()).findFirst();
6967             if (result.isPresent()) {
6968                 return result.get().getPortIndex();
6969             }
6970         }
6971         return INVALID_PORT_INDEX;
6972     }
6973 
6974     /**
6975      * Opens a logical channel to the ICC card.
6976      *
6977      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6978      *
6979      * <p>Requires Permission:
6980      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6981      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6982      *
6983      * @param AID Application id. See ETSI 102.221 and 101.220.
6984      * @return an IccOpenLogicalChannelResponse object.
6985      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
6986      */
6987     @Deprecated
iccOpenLogicalChannel(String AID)6988     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
6989         return iccOpenLogicalChannel(getSubId(), AID, -1);
6990     }
6991 
6992     /**
6993      * Opens a logical channel to the ICC card using the physical slot index.
6994      *
6995      * Use this method when no subscriptions are available on the SIM and the operation must be
6996      * performed using the physical slot index.
6997      *
6998      * This operation wraps two APDU instructions:
6999      * <ul>
7000      *     <li>MANAGE CHANNEL to open a logical channel</li>
7001      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7002      * </ul>
7003      *
7004      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7005      * and 0x0C are guaranteed to be supported.
7006      *
7007      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7008      * considered an error and the channel shall not be opened.
7009      *
7010      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7011      *
7012      * <p>Requires Permission:
7013      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7014      *
7015      * @param slotIndex the physical slot index of the ICC card
7016      * @param aid Application id. See ETSI 102.221 and 101.220.
7017      * @param p2 P2 parameter (described in ISO 7816-4).
7018      * @return an IccOpenLogicalChannelResponse object.
7019      * @hide
7020      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7021      * instead use {@link #iccOpenLogicalChannelByPort(int, int, String, int)}
7022      */
7023     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7024     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7025     @SystemApi
7026     @Nullable
7027     @Deprecated
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)7028     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
7029             @Nullable String aid, int p2) {
7030         try {
7031             ITelephony telephony = getITelephony();
7032             if (telephony != null) {
7033                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7034                 request.slotIndex = slotIndex;
7035                 request.portIndex = getFirstActivePortIndex(slotIndex);
7036                 request.aid = aid;
7037                 request.p2 = p2;
7038                 request.callingPackage = getOpPackageName();
7039                 request.binder = new Binder();
7040                 return telephony.iccOpenLogicalChannel(request);
7041             }
7042         } catch (RemoteException ex) {
7043         } catch (NullPointerException ex) {
7044         }
7045         return null;
7046     }
7047 
7048     /**
7049      * Opens a logical channel to the ICC card using the physical slot index and port index.
7050      *
7051      * Use this method when no subscriptions are available on the SIM and the operation must be
7052      * performed using the physical slot index and port index.
7053      *
7054      * This operation wraps two APDU instructions:
7055      * <ul>
7056      *     <li>MANAGE CHANNEL to open a logical channel</li>
7057      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7058      * </ul>
7059      *
7060      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7061      * and 0x0C are guaranteed to be supported.
7062      *
7063      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7064      * considered an error and the channel shall not be opened.
7065      *
7066      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7067      *
7068      * @param slotIndex the physical slot index of the ICC card
7069      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7070      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7071      * @param aid Application id. See ETSI 102.221 and 101.220.
7072      * @param p2 P2 parameter (described in ISO 7816-4).
7073      * @return an IccOpenLogicalChannelResponse object.
7074      * @hide
7075      */
7076     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7077     @SystemApi
7078     @NonNull
iccOpenLogicalChannelByPort(int slotIndex, int portIndex, @Nullable String aid, int p2)7079     public IccOpenLogicalChannelResponse iccOpenLogicalChannelByPort(int slotIndex,
7080             int portIndex, @Nullable String aid, int p2) {
7081         try {
7082             ITelephony telephony = getITelephony();
7083             if (telephony != null) {
7084                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7085                 request.slotIndex = slotIndex;
7086                 request.portIndex = portIndex;
7087                 request.aid = aid;
7088                 request.p2 = p2;
7089                 request.callingPackage = getOpPackageName();
7090                 request.binder = new Binder();
7091                 return telephony.iccOpenLogicalChannel(request);
7092             } else {
7093                 throw new IllegalStateException("telephony service is null.");
7094             }
7095         } catch (RemoteException ex) {
7096             throw ex.rethrowAsRuntimeException();
7097         }
7098     }
7099 
7100     /**
7101      * Opens a logical channel to the ICC card.
7102      *
7103      * This operation wraps two APDU instructions:
7104      * <ul>
7105      *     <li>MANAGE CHANNEL to open a logical channel</li>
7106      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7107      * </ul>
7108      *
7109      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7110      * and 0x0C are guaranteed to be supported.
7111      *
7112      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7113      * considered an error and the channel shall not be opened.
7114      *
7115      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7116      *
7117      * It is strongly recommended that callers of this should firstly create a new TelephonyManager
7118      * instance by calling {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so
7119      * can result in unpredictable and detrimental behavior like callers can end up talking to the
7120      * wrong SIM card.
7121      *
7122      * <p>Requires Permission:
7123      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7124      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7125      *
7126      * @param AID Application id. See ETSI 102.221 and 101.220.
7127      * @param p2 P2 parameter (described in ISO 7816-4).
7128      * @return an IccOpenLogicalChannelResponse object.
7129      */
7130     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccOpenLogicalChannel(String AID, int p2)7131     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
7132         return iccOpenLogicalChannel(getSubId(), AID, p2);
7133     }
7134 
7135     /**
7136      * Opens a logical channel to the ICC card.
7137      *
7138      * This operation wraps two APDU instructions:
7139      * <ul>
7140      *     <li>MANAGE CHANNEL to open a logical channel</li>
7141      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7142      * </ul>
7143      *
7144      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7145      * and 0x0C are guaranteed to be supported.
7146      *
7147      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7148      * considered an error and the channel shall not be opened.
7149      *
7150      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7151      *
7152      * <p>Requires Permission:
7153      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7154      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7155      *
7156      * @param subId The subscription to use.
7157      * @param AID Application id. See ETSI 102.221 and 101.220.
7158      * @param p2 P2 parameter (described in ISO 7816-4).
7159      * @return an IccOpenLogicalChannelResponse object.
7160      * @hide
7161      */
iccOpenLogicalChannel(int subId, String AID, int p2)7162     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
7163         try {
7164             ITelephony telephony = getITelephony();
7165             if (telephony != null) {
7166                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7167                 request.subId = subId;
7168                 request.callingPackage = getOpPackageName();
7169                 request.aid = AID;
7170                 request.p2 = p2;
7171                 request.binder = new Binder();
7172                 return telephony.iccOpenLogicalChannel(request);
7173             }
7174         } catch (RemoteException ex) {
7175         } catch (NullPointerException ex) {
7176         }
7177         return null;
7178     }
7179 
7180     /**
7181      * Closes a previously opened logical channel to the ICC card using the physical slot index.
7182      *
7183      * Use this method when no subscriptions are available on the SIM and the operation must be
7184      * performed using the physical slot index.
7185      *
7186      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7187      *
7188      * <p>Requires Permission:
7189      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7190      *
7191      * @param slotIndex the physical slot index of the ICC card
7192      * @param channel is the channel id to be closed as returned by a successful
7193      *            iccOpenLogicalChannel.
7194      * @return true if the channel was closed successfully.
7195      * @hide
7196      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7197      * instead use {@link #iccCloseLogicalChannelByPort(int, int, int)}
7198      */
7199     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7200     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7201     @SystemApi
7202     @Deprecated
iccCloseLogicalChannelBySlot(int slotIndex, int channel)7203     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
7204         try {
7205             ITelephony telephony = getITelephony();
7206             if (telephony != null) {
7207                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7208                 request.slotIndex = slotIndex;
7209                 request.portIndex = getFirstActivePortIndex(slotIndex);
7210                 request.channel = channel;
7211                 return telephony.iccCloseLogicalChannel(request);
7212             }
7213         } catch (RemoteException ex) {
7214         } catch (NullPointerException ex) {
7215         } catch (IllegalStateException ex) {
7216             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7217         }
7218         return false;
7219     }
7220 
7221     /**
7222      * Closes a previously opened logical channel to the ICC card using the physical slot index and
7223      * port index.
7224      *
7225      * Use this method when no subscriptions are available on the SIM and the operation must be
7226      * performed using the physical slot index and port index.
7227      *
7228      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7229      *
7230      * @param slotIndex the physical slot index of the ICC card
7231      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7232      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7233      * @param channel is the channel id to be closed as returned by a successful
7234      *            iccOpenLogicalChannel.
7235      *
7236      * @throws IllegalStateException if the Telephony process is not currently available or modem
7237      *                               currently can't process this command.
7238      * @throws IllegalArgumentException if invalid arguments are passed.
7239      * @hide
7240      */
7241     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7242     @SystemApi
iccCloseLogicalChannelByPort(int slotIndex, int portIndex, int channel)7243     public void iccCloseLogicalChannelByPort(int slotIndex, int portIndex, int channel) {
7244         try {
7245             ITelephony telephony = getITelephony();
7246             if (telephony != null) {
7247                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7248                 request.slotIndex = slotIndex;
7249                 request.portIndex = portIndex;
7250                 request.channel = channel;
7251                 telephony.iccCloseLogicalChannel(request);
7252             } else {
7253                 throw new IllegalStateException("telephony service is null.");
7254             }
7255         } catch (RemoteException ex) {
7256             throw ex.rethrowAsRuntimeException();
7257         }
7258     }
7259 
7260     /**
7261      * Closes a previously opened logical channel to the ICC card.
7262      *
7263      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7264      * It is strongly recommended that callers of this API should firstly create
7265      * new TelephonyManager instance by calling
7266      * {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so can result in
7267      * unpredictable and detrimental behavior like callers can end up talking to the wrong SIM card.
7268      *
7269      * <p>Requires Permission:
7270      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7271      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7272      *
7273      * @param channel is the channel id to be closed as returned by a successful
7274      *            iccOpenLogicalChannel.
7275      * @return true if the channel was closed successfully.
7276      * @throws IllegalArgumentException if input parameters are wrong. e.g., invalid channel
7277      */
7278     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccCloseLogicalChannel(int channel)7279     public boolean iccCloseLogicalChannel(int channel) {
7280         try {
7281             return iccCloseLogicalChannel(getSubId(), channel);
7282         } catch (IllegalStateException ex) {
7283             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7284         }
7285         return false;
7286     }
7287 
7288     /**
7289      * Closes a previously opened logical channel to the ICC card.
7290      *
7291      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7292      *
7293      * <p>Requires Permission:
7294      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7295      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7296      *
7297      * @param subId The subscription to use.
7298      * @param channel is the channel id to be closed as returned by a successful
7299      *            iccOpenLogicalChannel.
7300      * @return true if the channel was closed successfully.
7301      * @hide
7302      */
iccCloseLogicalChannel(int subId, int channel)7303     public boolean iccCloseLogicalChannel(int subId, int channel) {
7304         try {
7305             ITelephony telephony = getITelephony();
7306             if (telephony != null) {
7307                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7308                 request.subId = subId;
7309                 request.channel = channel;
7310                 return telephony.iccCloseLogicalChannel(request);
7311             }
7312         } catch (RemoteException ex) {
7313         } catch (NullPointerException ex) {
7314         } catch (IllegalStateException ex) {
7315             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7316         }
7317         return false;
7318     }
7319 
7320     /**
7321      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
7322      *
7323      * Use this method when no subscriptions are available on the SIM and the operation must be
7324      * performed using the physical slot index.
7325      *
7326      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7327      *
7328      * <p>Requires Permission:
7329      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7330      *
7331      * @param slotIndex the physical slot index of the ICC card
7332      * @param channel is the channel id to be closed as returned by a successful
7333      *            iccOpenLogicalChannel.
7334      * @param cla Class of the APDU command.
7335      * @param instruction Instruction of the APDU command.
7336      * @param p1 P1 value of the APDU command.
7337      * @param p2 P2 value of the APDU command.
7338      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7339      *            is sent to the SIM.
7340      * @param data Data to be sent with the APDU.
7341      * @return The APDU response from the ICC card with the status appended at the end, or null if
7342      * there is an issue connecting to the Telephony service.
7343      * @hide
7344      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7345      * instead use
7346      * {@link #iccTransmitApduLogicalChannelByPort(int, int, int, int, int, int, int, int, String)}
7347      */
7348     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7349     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7350     @SystemApi
7351     @Nullable
7352     @Deprecated
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7353     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
7354             int instruction, int p1, int p2, int p3, @Nullable String data) {
7355         try {
7356             ITelephony telephony = getITelephony();
7357             if (telephony != null) {
7358                 return telephony.iccTransmitApduLogicalChannelByPort(slotIndex,
7359                         getFirstActivePortIndex(slotIndex), channel, cla, instruction,
7360                         p1, p2, p3, data);
7361             }
7362         } catch (RemoteException ex) {
7363         } catch (NullPointerException ex) {
7364         }
7365         return null;
7366     }
7367 
7368     /**
7369      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
7370      *
7371      * Use this method when no subscriptions are available on the SIM and the operation must be
7372      * performed using the physical slot index.
7373      *
7374      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7375      *
7376      * @param slotIndex the physical slot index of the ICC card
7377      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7378      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7379      * @param channel is the channel id to be closed as returned by a successful
7380      *            iccOpenLogicalChannel.
7381      * @param cla Class of the APDU command.
7382      * @param instruction Instruction of the APDU command.
7383      * @param p1 P1 value of the APDU command.
7384      * @param p2 P2 value of the APDU command.
7385      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7386      *            is sent to the SIM.
7387      * @param data Data to be sent with the APDU.
7388      * @return The APDU response from the ICC card with the status appended at the end, or null if
7389      * there is an issue connecting to the Telephony service.
7390      * @hide
7391      */
7392     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7393     @SystemApi
7394     @NonNull
iccTransmitApduLogicalChannelByPort(int slotIndex, int portIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7395     public String iccTransmitApduLogicalChannelByPort(int slotIndex, int portIndex, int channel,
7396             int cla, int instruction, int p1, int p2, int p3, @Nullable String data) {
7397         String response;
7398         try {
7399             ITelephony telephony = getITelephony();
7400             if (telephony != null) {
7401                 response = telephony.iccTransmitApduLogicalChannelByPort(slotIndex, portIndex,
7402                         channel, cla, instruction, p1, p2, p3, data);
7403             } else {
7404                 throw new IllegalStateException("telephony service is null.");
7405             }
7406         } catch (RemoteException ex) {
7407             throw ex.rethrowAsRuntimeException();
7408         }
7409         return response;
7410     }
7411 
7412     /**
7413      * Transmit an APDU to the ICC card over a logical channel.
7414      *
7415      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7416      *
7417      * It is strongly recommended that callers of this API should firstly create a new
7418      * TelephonyManager instance by calling
7419      * {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so can result in
7420      * unpredictable and detrimental behavior like callers can end up talking to the wrong SIM card.
7421      *
7422      * <p>Requires Permission:
7423      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7424      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7425      *
7426      * @param channel is the channel id to be closed as returned by a successful
7427      *            iccOpenLogicalChannel.
7428      * @param cla Class of the APDU command.
7429      * @param instruction Instruction of the APDU command.
7430      * @param p1 P1 value of the APDU command.
7431      * @param p2 P2 value of the APDU command.
7432      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7433      *            is sent to the SIM.
7434      * @param data Data to be sent with the APDU.
7435      * @return The APDU response from the ICC card with the status appended at
7436      *            the end.
7437      */
7438     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)7439     public String iccTransmitApduLogicalChannel(int channel, int cla,
7440             int instruction, int p1, int p2, int p3, String data) {
7441         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
7442                     instruction, p1, p2, p3, data);
7443     }
7444 
7445     /**
7446      * Transmit an APDU to the ICC card over a logical channel.
7447      *
7448      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7449      *
7450      * <p>Requires Permission:
7451      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7452      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7453      *
7454      * @param subId The subscription to use.
7455      * @param channel is the channel id to be closed as returned by a successful
7456      *            iccOpenLogicalChannel.
7457      * @param cla Class of the APDU command.
7458      * @param instruction Instruction of the APDU command.
7459      * @param p1 P1 value of the APDU command.
7460      * @param p2 P2 value of the APDU command.
7461      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7462      *            is sent to the SIM.
7463      * @param data Data to be sent with the APDU.
7464      * @return The APDU response from the ICC card with the status appended at
7465      *            the end.
7466      * @hide
7467      */
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)7468     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
7469             int instruction, int p1, int p2, int p3, String data) {
7470         try {
7471             ITelephony telephony = getITelephony();
7472             if (telephony != null)
7473                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
7474                     instruction, p1, p2, p3, data);
7475         } catch (RemoteException ex) {
7476         } catch (NullPointerException ex) {
7477         }
7478         return "";
7479     }
7480 
7481     /**
7482      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
7483      *
7484      * Use this method when no subscriptions are available on the SIM and the operation must be
7485      * performed using the physical slot index.
7486      *
7487      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7488      *
7489      * <p>Requires Permission:
7490      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7491      *
7492      * @param slotIndex the physical slot index of the ICC card to target
7493      * @param cla Class of the APDU command.
7494      * @param instruction Instruction of the APDU command.
7495      * @param p1 P1 value of the APDU command.
7496      * @param p2 P2 value of the APDU command.
7497      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7498      *            is sent to the SIM.
7499      * @param data Data to be sent with the APDU.
7500      * @return The APDU response from the ICC card with the status appended at
7501      *            the end.
7502      * @hide
7503      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7504      * instead use
7505      * {@link #iccTransmitApduBasicChannelByPort(int, int, int, int, int, int, int, String)}
7506      */
7507     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7508     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7509     @SystemApi
7510     @NonNull
7511     @Deprecated
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7512     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
7513             int p2, int p3, @Nullable String data) {
7514         try {
7515             ITelephony telephony = getITelephony();
7516             if (telephony != null) {
7517                 return telephony.iccTransmitApduBasicChannelByPort(slotIndex,
7518                         getFirstActivePortIndex(slotIndex), getOpPackageName(),
7519                         cla, instruction, p1, p2, p3, data);
7520             }
7521         } catch (RemoteException ex) {
7522         } catch (NullPointerException ex) {
7523         }
7524         return null;
7525     }
7526 
7527     /**
7528      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
7529      *
7530      * Use this method when no subscriptions are available on the SIM and the operation must be
7531      * performed using the physical slot index.
7532      *
7533      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7534      *
7535      * @param slotIndex the physical slot index of the ICC card to target
7536      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7537      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7538      * @param cla Class of the APDU command.
7539      * @param instruction Instruction of the APDU command.
7540      * @param p1 P1 value of the APDU command.
7541      * @param p2 P2 value of the APDU command.
7542      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7543      *            is sent to the SIM.
7544      * @param data Data to be sent with the APDU.
7545      * @return The APDU response from the ICC card with the status appended at
7546      *            the end.
7547      * @hide
7548      */
7549     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7550     @SystemApi
7551     @NonNull
iccTransmitApduBasicChannelByPort(int slotIndex, int portIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7552     public String iccTransmitApduBasicChannelByPort(int slotIndex, int portIndex, int cla,
7553             int instruction, int p1, int p2, int p3, @Nullable String data) {
7554         String response;
7555         try {
7556             ITelephony telephony = getITelephony();
7557             if (telephony != null) {
7558                 response = telephony.iccTransmitApduBasicChannelByPort(slotIndex, portIndex,
7559                         getOpPackageName(), cla, instruction, p1, p2, p3, data);
7560             } else {
7561                 throw new IllegalStateException("telephony service is null.");
7562             }
7563         } catch (RemoteException ex) {
7564             throw ex.rethrowAsRuntimeException();
7565         }
7566         return response;
7567     }
7568     /**
7569      * Transmit an APDU to the ICC card over the basic channel.
7570      *
7571      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7572      *
7573      * <p>Requires Permission:
7574      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7575      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7576      *
7577      * @param cla Class of the APDU command.
7578      * @param instruction Instruction of the APDU command.
7579      * @param p1 P1 value of the APDU command.
7580      * @param p2 P2 value of the APDU command.
7581      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7582      *            is sent to the SIM.
7583      * @param data Data to be sent with the APDU.
7584      * @return The APDU response from the ICC card with the status appended at
7585      *            the end.
7586      */
7587     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)7588     public String iccTransmitApduBasicChannel(int cla,
7589             int instruction, int p1, int p2, int p3, String data) {
7590         return iccTransmitApduBasicChannel(getSubId(), cla,
7591                     instruction, p1, p2, p3, data);
7592     }
7593 
7594     /**
7595      * Transmit an APDU to the ICC card over the basic channel.
7596      *
7597      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7598      *
7599      * <p>Requires Permission:
7600      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7601      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7602      *
7603      * @param subId The subscription to use.
7604      * @param cla Class of the APDU command.
7605      * @param instruction Instruction of the APDU command.
7606      * @param p1 P1 value of the APDU command.
7607      * @param p2 P2 value of the APDU command.
7608      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7609      *            is sent to the SIM.
7610      * @param data Data to be sent with the APDU.
7611      * @return The APDU response from the ICC card with the status appended at
7612      *            the end.
7613      * @hide
7614      */
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)7615     public String iccTransmitApduBasicChannel(int subId, int cla,
7616             int instruction, int p1, int p2, int p3, String data) {
7617         try {
7618             ITelephony telephony = getITelephony();
7619             if (telephony != null)
7620                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
7621                     instruction, p1, p2, p3, data);
7622         } catch (RemoteException ex) {
7623         } catch (NullPointerException ex) {
7624         }
7625         return "";
7626     }
7627 
7628     /**
7629      * Returns the response APDU for a command APDU sent through SIM_IO.
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      * @param fileID
7636      * @param command
7637      * @param p1 P1 value of the APDU command.
7638      * @param p2 P2 value of the APDU command.
7639      * @param p3 P3 value of the APDU command.
7640      * @param filePath
7641      * @return The APDU response.
7642      */
7643     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)7644     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
7645             String filePath) {
7646         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
7647     }
7648 
7649     /**
7650      * Returns the response APDU for a command APDU sent through SIM_IO.
7651      *
7652      * <p>Requires Permission:
7653      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7654      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7655      *
7656      * @param subId The subscription to use.
7657      * @param fileID
7658      * @param command
7659      * @param p1 P1 value of the APDU command.
7660      * @param p2 P2 value of the APDU command.
7661      * @param p3 P3 value of the APDU command.
7662      * @param filePath
7663      * @return The APDU response.
7664      * @hide
7665      */
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)7666     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
7667             int p3, String filePath) {
7668         try {
7669             ITelephony telephony = getITelephony();
7670             if (telephony != null)
7671                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
7672         } catch (RemoteException ex) {
7673         } catch (NullPointerException ex) {
7674         }
7675         return null;
7676     }
7677 
7678     /**
7679      * Send ENVELOPE to the SIM and return the response.
7680      *
7681      * <p>Requires Permission:
7682      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7683      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7684      *
7685      * @param content String containing SAT/USAT response in hexadecimal
7686      *                format starting with command tag. See TS 102 223 for
7687      *                details.
7688      * @return The APDU response from the ICC card in hexadecimal format
7689      *         with the last 4 bytes being the status word. If the command fails,
7690      *         returns an empty string.
7691      */
7692     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
sendEnvelopeWithStatus(String content)7693     public String sendEnvelopeWithStatus(String content) {
7694         return sendEnvelopeWithStatus(getSubId(), content);
7695     }
7696 
7697     /**
7698      * Send ENVELOPE to the SIM and return the response.
7699      *
7700      * <p>Requires Permission:
7701      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7702      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7703      *
7704      * @param subId The subscription to use.
7705      * @param content String containing SAT/USAT response in hexadecimal
7706      *                format starting with command tag. See TS 102 223 for
7707      *                details.
7708      * @return The APDU response from the ICC card in hexadecimal format
7709      *         with the last 4 bytes being the status word. If the command fails,
7710      *         returns an empty string.
7711      * @hide
7712      */
sendEnvelopeWithStatus(int subId, String content)7713     public String sendEnvelopeWithStatus(int subId, String content) {
7714         try {
7715             ITelephony telephony = getITelephony();
7716             if (telephony != null)
7717                 return telephony.sendEnvelopeWithStatus(subId, content);
7718         } catch (RemoteException ex) {
7719         } catch (NullPointerException ex) {
7720         }
7721         return "";
7722     }
7723 
7724     /**
7725      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
7726      * Used for device configuration by some CDMA operators.
7727      *
7728      * <p>Requires Permission:
7729      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7730      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7731      *
7732      * @param itemID the ID of the item to read.
7733      * @return the NV item as a String, or null on any failure.
7734      *
7735      * @hide
7736      */
7737     @UnsupportedAppUsage
nvReadItem(int itemID)7738     public String nvReadItem(int itemID) {
7739         try {
7740             ITelephony telephony = getITelephony();
7741             if (telephony != null)
7742                 return telephony.nvReadItem(itemID);
7743         } catch (RemoteException ex) {
7744             Rlog.e(TAG, "nvReadItem RemoteException", ex);
7745         } catch (NullPointerException ex) {
7746             Rlog.e(TAG, "nvReadItem NPE", ex);
7747         }
7748         return "";
7749     }
7750 
7751     /**
7752      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
7753      * Used for device configuration by some CDMA operators.
7754      *
7755      * <p>Requires Permission:
7756      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7757      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7758      *
7759      * @param itemID the ID of the item to read.
7760      * @param itemValue the value to write, as a String.
7761      * @return true on success; false on any failure.
7762      *
7763      * @hide
7764      */
nvWriteItem(int itemID, String itemValue)7765     public boolean nvWriteItem(int itemID, String itemValue) {
7766         try {
7767             ITelephony telephony = getITelephony();
7768             if (telephony != null)
7769                 return telephony.nvWriteItem(itemID, itemValue);
7770         } catch (RemoteException ex) {
7771             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
7772         } catch (NullPointerException ex) {
7773             Rlog.e(TAG, "nvWriteItem NPE", ex);
7774         }
7775         return false;
7776     }
7777 
7778     /**
7779      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
7780      * Used for device configuration by some CDMA operators.
7781      *
7782      * <p>Requires Permission:
7783      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7784      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7785      *
7786      * @param preferredRoamingList byte array containing the new PRL.
7787      * @return true on success; false on any failure.
7788      *
7789      * @hide
7790      */
nvWriteCdmaPrl(byte[] preferredRoamingList)7791     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
7792         try {
7793             ITelephony telephony = getITelephony();
7794             if (telephony != null)
7795                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
7796         } catch (RemoteException ex) {
7797             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
7798         } catch (NullPointerException ex) {
7799             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
7800         }
7801         return false;
7802     }
7803 
7804     /**
7805      * Perform the specified type of NV config reset. The radio will be taken offline
7806      * and the device must be rebooted after the operation. Used for device
7807      * configuration by some CDMA operators.
7808      *
7809      * <p>Requires Permission:
7810      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7811      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7812      *
7813      * TODO: remove this one. use {@link #rebootModem()} for reset type 1 and
7814      * {@link #resetRadioConfig()} for reset type 3 (b/116476729)
7815      *
7816      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
7817      * @return true on success; false on any failure.
7818      *
7819      * @hide
7820      */
7821     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
nvResetConfig(int resetType)7822     public boolean nvResetConfig(int resetType) {
7823         try {
7824             ITelephony telephony = getITelephony();
7825             if (telephony != null) {
7826                 if (resetType == 1 /*1: reload NV reset */) {
7827                     return telephony.rebootModem(getSlotIndex());
7828                 } else if (resetType == 3 /*3: factory NV reset */) {
7829                     return telephony.resetModemConfig(getSlotIndex());
7830                 } else {
7831                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
7832                 }
7833             }
7834         } catch (RemoteException ex) {
7835             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
7836         } catch (NullPointerException ex) {
7837             Rlog.e(TAG, "nvResetConfig NPE", ex);
7838         }
7839         return false;
7840     }
7841 
7842     /**
7843      * Rollback modem configurations to factory default except some config which are in whitelist.
7844      * Used for device configuration by some carriers.
7845      *
7846      * <p>Requires Permission:
7847      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7848      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7849      *
7850      * @return {@code true} on success; {@code false} on any failure.
7851      *
7852      * @hide
7853      */
7854     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7855     @SystemApi
7856     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
resetRadioConfig()7857     public boolean resetRadioConfig() {
7858         try {
7859             ITelephony telephony = getITelephony();
7860             if (telephony != null) {
7861                 return telephony.resetModemConfig(getSlotIndex());
7862             }
7863         } catch (RemoteException ex) {
7864             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
7865         } catch (NullPointerException ex) {
7866             Rlog.e(TAG, "resetRadioConfig NPE", ex);
7867         }
7868         return false;
7869     }
7870 
7871     /**
7872      * Generate a radio modem reset. Used for device configuration by some carriers.
7873      *
7874      * <p>Requires Permission:
7875      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7876      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7877      *
7878      * @return {@code true} on success; {@code false} on any failure.
7879      *
7880      * @deprecated  Using {@link #rebootModem()} instead.
7881      *
7882      * @hide
7883      */
7884     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7885     @SystemApi
7886     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
rebootRadio()7887     public boolean rebootRadio() {
7888         try {
7889             ITelephony telephony = getITelephony();
7890             if (telephony != null) {
7891                 return telephony.rebootModem(getSlotIndex());
7892             }
7893         } catch (RemoteException ex) {
7894             Rlog.e(TAG, "rebootRadio RemoteException", ex);
7895         } catch (NullPointerException ex) {
7896             Rlog.e(TAG, "rebootRadio NPE", ex);
7897         }
7898         return false;
7899     }
7900 
7901     /**
7902      * Generate a radio modem reset. Used for device configuration by some carriers.
7903      *
7904      * <p>Requires Permission:
7905      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7906      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7907      * @throws IllegalStateException if the Telephony process is not currently available.
7908      * @throws RuntimeException
7909      */
7910     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7911     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
rebootModem()7912     public void rebootModem() {
7913         try {
7914             ITelephony telephony = getITelephony();
7915             if (telephony == null) {
7916                 throw new IllegalStateException("telephony service is null.");
7917             }
7918             telephony.rebootModem(getSlotIndex());
7919         } catch (RemoteException ex) {
7920             Rlog.e(TAG, "rebootRadio RemoteException", ex);
7921             throw ex.rethrowAsRuntimeException();
7922         }
7923     }
7924 
7925     /**
7926      * Return an appropriate subscription ID for any situation.
7927      *
7928      * If this object has been created with {@link #createForSubscriptionId}, then the provided
7929      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
7930      *
7931      */
7932     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriptionId()7933     public int getSubscriptionId() {
7934         return getSubId();
7935     }
7936 
7937     /**
7938      * Return an appropriate subscription ID for any situation.
7939      *
7940      * If this object has been created with {@link #createForSubscriptionId}, then the provided
7941      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
7942      *
7943      */
getSubId()7944     private int getSubId() {
7945       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
7946         return mSubId;
7947       }
7948       return SubscriptionManager.getDefaultSubscriptionId();
7949     }
7950 
7951     /**
7952      * Return an appropriate subscription ID for any situation.
7953      *
7954      * If this object has been created with {@link #createForSubscriptionId}, then the provided
7955      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
7956      * returned.
7957      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
7958      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
7959      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
7960      */
7961     @UnsupportedAppUsage
getSubId(int preferredSubId)7962     private int getSubId(int preferredSubId) {
7963         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
7964             return mSubId;
7965         }
7966         return preferredSubId;
7967     }
7968 
7969     /**
7970      * Return an appropriate phone ID for any situation.
7971      *
7972      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
7973      * associated with the provided subId is returned. Otherwise, the default phoneId associated
7974      * with the default subId will be returned.
7975      */
getPhoneId()7976     private int getPhoneId() {
7977         return SubscriptionManager.getPhoneId(getSubId());
7978     }
7979 
7980     /**
7981      * Return an appropriate phone ID for any situation.
7982      *
7983      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
7984      * associated with the provided subId is returned. Otherwise, return the phoneId associated
7985      * with the preferred subId based on caller's context.
7986      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
7987      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
7988      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
7989      */
7990     @UnsupportedAppUsage
getPhoneId(int preferredSubId)7991     private int getPhoneId(int preferredSubId) {
7992         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
7993     }
7994 
7995     /**
7996      * Return an appropriate slot index for any situation.
7997      *
7998      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
7999      * associated with the provided subId is returned. Otherwise, return the slot index associated
8000      * with the default subId.
8001      * If SIM is not inserted, return default SIM slot index.
8002      *
8003      * {@hide}
8004      */
8005     @VisibleForTesting
8006     @UnsupportedAppUsage
getSlotIndex()8007     public int getSlotIndex() {
8008         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
8009         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
8010             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
8011         }
8012         return slotIndex;
8013     }
8014 
8015     /**
8016      * Request that the next incoming call from a number matching {@code range} be intercepted.
8017      *
8018      * This API is intended for OEMs to provide a service for apps to verify the device's phone
8019      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
8020      * intercept the next incoming call from a number that lies within the range, within a timeout
8021      * specified by {@code timeoutMillis}.
8022      *
8023      * If such a phone call is received, the caller will be notified via
8024      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
8025      * If verification fails for any reason, the caller will be notified via
8026      * {@link NumberVerificationCallback#onVerificationFailed(int)}
8027      * on the provided {@link Executor}.
8028      *
8029      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
8030      * API must also be listed in the device configuration as an authorized app in
8031      * {@code packages/services/Telephony/res/values/config.xml} under the
8032      * {@code config_number_verification_package_name} key.
8033      *
8034      * @hide
8035      * @param range The range of phone numbers the caller expects a phone call from.
8036      * @param timeoutMillis The amount of time to wait for such a call, or the value of
8037      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
8038      * @param executor The {@link Executor} that callbacks should be executed on.
8039      * @param callback The callback to use for delivering results.
8040      */
8041     @SystemApi
8042     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8043     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)8044     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
8045             @NonNull @CallbackExecutor Executor executor,
8046             @NonNull NumberVerificationCallback callback) {
8047         if (executor == null) {
8048             throw new NullPointerException("Executor must be non-null");
8049         }
8050         if (callback == null) {
8051             throw new NullPointerException("Callback must be non-null");
8052         }
8053 
8054         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
8055             @Override
8056             public void onCallReceived(String phoneNumber) {
8057                 final long identity = Binder.clearCallingIdentity();
8058                 try {
8059                     executor.execute(() ->
8060                             callback.onCallReceived(phoneNumber));
8061                 } finally {
8062                     Binder.restoreCallingIdentity(identity);
8063                 }
8064             }
8065 
8066             @Override
8067             public void onVerificationFailed(int reason) {
8068                 final long identity = Binder.clearCallingIdentity();
8069                 try {
8070                     executor.execute(() ->
8071                             callback.onVerificationFailed(reason));
8072                 } finally {
8073                     Binder.restoreCallingIdentity(identity);
8074                 }
8075             }
8076         };
8077 
8078         try {
8079             ITelephony telephony = getITelephony();
8080             if (telephony == null) {
8081                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
8082                     throw new IllegalStateException("Telephony is null");
8083                 } else {
8084                     return;
8085                 }
8086             }
8087 
8088             telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
8089                     getOpPackageName());
8090         } catch (RemoteException ex) {
8091             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
8092             runOnBackgroundThread(() -> executor.execute(
8093                     () -> callback.onVerificationFailed(
8094                             NumberVerificationCallback.REASON_UNSPECIFIED)));
8095         }
8096     }
8097 
8098     /**
8099      * Inserts or updates a list property. Expands the list if its length is not enough.
8100      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)8101     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
8102         List<T> ret = new ArrayList<>(prop);
8103         while (ret.size() <= phoneId) ret.add(null);
8104         ret.set(phoneId, value);
8105         return ret;
8106     }
8107     /**
8108      * Convenience function for retrieving a value from the secure settings
8109      * value list as an integer.  Note that internally setting values are
8110      * always stored as strings; this function converts the string to an
8111      * integer for you.
8112      * <p>
8113      * This version does not take a default value.  If the setting has not
8114      * been set, or the string value is not a number,
8115      * it throws {@link SettingNotFoundException}.
8116      *
8117      * @param cr The ContentResolver to access.
8118      * @param name The name of the setting to retrieve.
8119      * @param index The index of the list
8120      *
8121      * @throws SettingNotFoundException Thrown if a setting by the given
8122      * name can't be found or the setting value is not an integer.
8123      *
8124      * @return The value at the given index of settings.
8125      * @hide
8126      */
8127     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getIntAtIndex(android.content.ContentResolver cr, String name, int index)8128     public static int getIntAtIndex(android.content.ContentResolver cr,
8129             String name, int index)
8130             throws android.provider.Settings.SettingNotFoundException {
8131         String v = android.provider.Settings.Global.getString(cr, name);
8132         if (v != null) {
8133             String valArray[] = v.split(",");
8134             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
8135                 try {
8136                     return Integer.parseInt(valArray[index]);
8137                 } catch (NumberFormatException e) {
8138                     //Log.e(TAG, "Exception while parsing Integer: ", e);
8139                 }
8140             }
8141         }
8142         throw new android.provider.Settings.SettingNotFoundException(name);
8143     }
8144 
8145     /**
8146      * Convenience function for updating settings value as coma separated
8147      * integer values. This will either create a new entry in the table if the
8148      * given name does not exist, or modify the value of the existing row
8149      * with that name.  Note that internally setting values are always
8150      * stored as strings, so this function converts the given value to a
8151      * string before storing it.
8152      *
8153      * @param cr The ContentResolver to access.
8154      * @param name The name of the setting to modify.
8155      * @param index The index of the list
8156      * @param value The new value for the setting to be added to the list.
8157      * @return true if the value was set, false on database errors
8158      * @hide
8159      */
8160     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)8161     public static boolean putIntAtIndex(android.content.ContentResolver cr,
8162             String name, int index, int value) {
8163         String data = "";
8164         String valArray[] = null;
8165         String v = android.provider.Settings.Global.getString(cr, name);
8166 
8167         if (index == Integer.MAX_VALUE) {
8168             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
8169         }
8170         if (index < 0) {
8171             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
8172         }
8173         if (v != null) {
8174             valArray = v.split(",");
8175         }
8176 
8177         // Copy the elements from valArray till index
8178         for (int i = 0; i < index; i++) {
8179             String str = "";
8180             if ((valArray != null) && (i < valArray.length)) {
8181                 str = valArray[i];
8182             }
8183             data = data + str + ",";
8184         }
8185 
8186         data = data + value;
8187 
8188         // Copy the remaining elements from valArray if any.
8189         if (valArray != null) {
8190             for (int i = index+1; i < valArray.length; i++) {
8191                 data = data + "," + valArray[i];
8192             }
8193         }
8194         return android.provider.Settings.Global.putString(cr, name, data);
8195     }
8196 
8197     /**
8198      * Gets a per-phone telephony property from a property name.
8199      *
8200      * @hide
8201      */
8202     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)8203     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
8204         String propVal = null;
8205         String prop = SystemProperties.get(property);
8206         if ((prop != null) && (prop.length() > 0)) {
8207             String values[] = prop.split(",");
8208             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
8209                 propVal = values[phoneId];
8210             }
8211         }
8212         return propVal == null ? defaultVal : propVal;
8213     }
8214 
8215     /**
8216      * Gets a typed per-phone telephony property from a schematized list property.
8217      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)8218     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
8219         T ret = null;
8220         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
8221         return ret != null ? ret : defaultValue;
8222     }
8223 
8224     /**
8225      * Gets a global telephony property.
8226      *
8227      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
8228      * per-phone.
8229      *
8230      * @hide
8231      */
8232     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getTelephonyProperty(String property, String defaultVal)8233     public static String getTelephonyProperty(String property, String defaultVal) {
8234         String propVal = SystemProperties.get(property);
8235         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
8236     }
8237 
8238     /** @hide */
8239     @UnsupportedAppUsage
getSimCount()8240     public int getSimCount() {
8241         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
8242         // and then this method shouldn't be used at all!
8243         return getPhoneCount();
8244     }
8245 
8246     /**
8247      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
8248      *
8249      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
8250      *
8251      * @return IMS Service Table or null if not present or not loaded
8252      * @hide
8253      */
8254     @Nullable
8255     @SystemApi
8256     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8257     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIsimIst()8258     public String getIsimIst() {
8259         try {
8260             IPhoneSubInfo info = getSubscriberInfoService();
8261             if (info == null)
8262                 return null;
8263             //get the Isim Ist based on subId
8264             return info.getIsimIst(getSubId());
8265         } catch (RemoteException ex) {
8266             return null;
8267         } catch (NullPointerException ex) {
8268             // This could happen before phone restarts due to crashing
8269             return null;
8270         }
8271     }
8272 
8273     /**
8274      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
8275      * @return an array of PCSCF strings with one PCSCF per string, or null if
8276      *         not present or not loaded
8277      * @hide
8278      */
8279     @UnsupportedAppUsage
getIsimPcscf()8280     public String[] getIsimPcscf() {
8281         try {
8282             IPhoneSubInfo info = getSubscriberInfoService();
8283             if (info == null)
8284                 return null;
8285             //get the Isim Pcscf based on subId
8286             return info.getIsimPcscf(getSubId());
8287         } catch (RemoteException ex) {
8288             return null;
8289         } catch (NullPointerException ex) {
8290             // This could happen before phone restarts due to crashing
8291             return null;
8292         }
8293     }
8294 
8295     /** UICC application type is unknown or not specified */
8296     public static final int APPTYPE_UNKNOWN = PhoneConstants.APPTYPE_UNKNOWN;
8297     /** UICC application type is SIM */
8298     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
8299     /** UICC application type is USIM */
8300     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
8301     /** UICC application type is RUIM */
8302     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
8303     /** UICC application type is CSIM */
8304     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
8305     /** UICC application type is ISIM */
8306     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
8307 
8308     // authContext (parameter P2) when doing UICC challenge,
8309     // per 3GPP TS 31.102 (Section 7.1.2)
8310     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
8311     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
8312     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
8313     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
8314     /**
8315      * Authentication type for GBA Bootstrap Challenge.
8316      * Pass this authentication type into the {@link #getIccAuthentication} API to perform a GBA
8317      * Bootstrap challenge (BSF), with {@code data} (generated according to the procedure defined in
8318      * 3GPP 33.220 Section 5.3.2 step.4) in base64 encoding.
8319      * This method will return the Bootstrapping response in base64 encoding when ICC authentication
8320      * is completed.
8321      * Ref 3GPP 33.220 Section 5.3.2.
8322      */
8323     public static final int AUTHTYPE_GBA_BOOTSTRAP = PhoneConstants.AUTH_CONTEXT_GBA_BOOTSTRAP;
8324     /**
8325      * Authentication type for GBA Network Application Functions (NAF) key External Challenge.
8326      * Pass this authentication type into the {@link #getIccAuthentication} API to perform a GBA
8327      * Network Applications Functions (NAF) key External challenge using the NAF_ID parameter
8328      * as the {@code data} in base64 encoding.
8329      * This method will return the Ks_Ext_Naf key in base64 encoding when ICC authentication
8330      * is completed.
8331      * Ref 3GPP 33.220 Section 5.3.2.
8332      */
8333     public static final int AUTHTYPE_GBA_NAF_KEY_EXTERNAL =
8334             PhoneConstants.AUTHTYPE_GBA_NAF_KEY_EXTERNAL;
8335 
8336     /** @hide */
8337     @Retention(RetentionPolicy.SOURCE)
8338     @IntDef({
8339             AUTHTYPE_EAP_SIM,
8340             AUTHTYPE_EAP_AKA,
8341             AUTHTYPE_GBA_BOOTSTRAP,
8342             AUTHTYPE_GBA_NAF_KEY_EXTERNAL
8343     })
8344     public @interface AuthType {}
8345 
8346     /**
8347      * Returns the response of authentication for the default subscription.
8348      * Returns null if the authentication hasn't been successful
8349      *
8350      * <p>Requires one of the following permissions:
8351      * <ul>
8352      *     <li>READ_PRIVILEGED_PHONE_STATE
8353      *     <li>the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8354      *     <li>the calling app has been granted the
8355      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
8356      * </ul>
8357      *
8358      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8359      * @param authType the authentication type, any one of {@link #AUTHTYPE_EAP_AKA} or
8360      * {@link #AUTHTYPE_EAP_SIM} or {@link #AUTHTYPE_GBA_BOOTSTRAP} or
8361      * {@link #AUTHTYPE_GBA_NAF_KEY_EXTERNAL}
8362      * @param data authentication challenge data, base64 encoded.
8363      * See 3GPP TS 31.102 7.1.2 for more details.
8364      * @return the response of authentication. This value will be null in the following cases:
8365      *   Authentication error, incorrect MAC
8366      *   Authentication error, security context not supported
8367      *   Key freshness failure
8368      *   Authentication error, no memory space available
8369      *   Authentication error, no memory space available in EFMUK
8370      */
8371     // TODO(b/73660190): This should probably require MODIFY_PHONE_STATE, not
8372     // READ_PRIVILEGED_PHONE_STATE. It certainly shouldn't reference the permission in Javadoc since
8373     // it's not public API.
8374     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIccAuthentication(int appType,@AuthType int authType, String data)8375     public String getIccAuthentication(int appType,@AuthType int authType, String data) {
8376         return getIccAuthentication(getSubId(), appType, authType, data);
8377     }
8378 
8379     /**
8380      * Returns the response of USIM Authentication for specified subId.
8381      * Returns null if the authentication hasn't been successful
8382      *
8383      * <p>See {@link #getIccAuthentication(int, int, String)} for details on the required
8384      * permissions.
8385      *
8386      * @param subId subscription ID used for authentication
8387      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8388      * @param authType the authentication type, any one of {@link #AUTHTYPE_EAP_AKA} or
8389      * {@link #AUTHTYPE_EAP_SIM} or {@link #AUTHTYPE_GBA_BOOTSTRAP} or
8390      * {@link #AUTHTYPE_GBA_NAF_KEY_EXTERNAL}
8391      * @param data authentication challenge data, base64 encoded.
8392      * See 3GPP TS 31.102 7.1.2 for more details.
8393      * @return the response of authentication. This value will be null in the following cases only
8394      * (see 3GPP TS 31.102 7.3.1):
8395      *   Authentication error, incorrect MAC
8396      *   Authentication error, security context not supported
8397      *   Key freshness failure
8398      *   Authentication error, no memory space available
8399      *   Authentication error, no memory space available in EFMUK
8400      * @hide
8401      */
8402     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType,@AuthType int authType, String data)8403     public String getIccAuthentication(int subId, int appType,@AuthType int authType, String data) {
8404         try {
8405             IPhoneSubInfo info = getSubscriberInfoService();
8406             if (info == null)
8407                 return null;
8408             return info.getIccSimChallengeResponse(subId, appType, authType, data,
8409                     getOpPackageName(), getAttributionTag());
8410         } catch (RemoteException ex) {
8411             return null;
8412         } catch (NullPointerException ex) {
8413             // This could happen before phone starts
8414             return null;
8415         }
8416     }
8417 
8418     /**
8419      * Returns an array of Forbidden PLMNs from the USIM App
8420      * Returns null if the query fails.
8421      *
8422      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
8423      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8424      *
8425      * @return an array of forbidden PLMNs or null if not available
8426      */
8427     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8428     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
8429     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getForbiddenPlmns()8430     public String[] getForbiddenPlmns() {
8431       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
8432     }
8433 
8434     /**
8435      * Returns an array of Forbidden PLMNs from the specified SIM App
8436      * Returns null if the query fails.
8437      *
8438      * @param subId subscription ID used for authentication
8439      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8440      * @return fplmns an array of forbidden PLMNs
8441      * @hide
8442      */
8443     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)8444     public String[] getForbiddenPlmns(int subId, int appType) {
8445         try {
8446             ITelephony telephony = getITelephony();
8447             if (telephony == null)
8448                 return null;
8449             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
8450                     getAttributionTag());
8451         } catch (RemoteException ex) {
8452             return null;
8453         } catch (NullPointerException ex) {
8454             // This could happen before phone starts
8455             return null;
8456         }
8457     }
8458 
8459     /**
8460      * Replace the contents of the forbidden PLMN SIM file with the provided values.
8461      * Passing an empty list will clear the contents of the EFfplmn file.
8462      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
8463      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
8464      * If the list is longer than the size of EFfplmn, then the file will be written from the
8465      * beginning of the list up to the file size.
8466      *
8467      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
8468      * MODIFY_PHONE_STATE}
8469      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8470      *
8471      * @param fplmns a list of PLMNs to be forbidden.
8472      *
8473      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
8474      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
8475      * room for all of the values passed in. Return -1 in the event of an unexpected failure
8476      */
8477     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8478     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8479     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setForbiddenPlmns(@onNull List<String> fplmns)8480     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
8481         try {
8482             ITelephony telephony = getITelephony();
8483             if (telephony == null) return -1;
8484             return telephony.setForbiddenPlmns(
8485                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
8486         } catch (RemoteException ex) {
8487             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
8488         } catch (NullPointerException ex) {
8489             // This could happen before phone starts
8490             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
8491         }
8492         return -1;
8493     }
8494 
8495     /**
8496      * Fetches the sim service table from the EFUST/EFIST based on the application type
8497      * {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}. The return value is hexaString format
8498      * representing X bytes (x >= 1). Each bit of every byte indicates which optional services
8499      * are available for the given application type.
8500      * The USIM service table EF is described in as per Section 4.2.8 of 3GPP TS 31.102.
8501      * The ISIM service table EF is described in as per Section 4.2.7 of 3GPP TS 31.103.
8502      * The list of services mapped to the exact nth byte of response as mentioned in Section 4.2
8503      * .7 of 3GPP TS 31.103. Eg. Service n°1: Local Phone Book, Service n°2: Fixed Dialling
8504      * Numbers (FDN) - Bit 1 and 2 of the 1st Byte represent service Local Phone Book and Fixed
8505      * Dialling Numbers (FDN)respectively. The coding format for each service type  should be
8506      * interpreted as bit = 1: service available;bit = 0:service not available.
8507      *
8508      * @param appType of type int of either {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}.
8509      * @return HexString represents sim service table else null.
8510      * @throws SecurityException if the caller does not have the required permission/privileges
8511      * @hide
8512      */
8513 
8514     @Nullable
8515     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8516     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimServiceTable(int appType)8517     public String getSimServiceTable(int appType) {
8518         try {
8519             IPhoneSubInfo info = getSubscriberInfoService();
8520             if (info == null) {
8521                 Rlog.e(TAG, "getSimServiceTable(): IPhoneSubInfo is null");
8522                 return null;
8523             }
8524             //Fetches the sim service table based on subId and appType
8525             if (appType == APPTYPE_ISIM) {
8526                 return info.getIsimIst(getSubId());
8527             } else if ((appType == APPTYPE_USIM)) {
8528                 return info.getSimServiceTable(getSubId(), APPTYPE_USIM);
8529             } else {
8530                 return null;
8531             }
8532         } catch (RemoteException ex) {
8533             Rlog.e(TAG, "getSimServiceTable(): RemoteException=" + ex.getMessage());
8534         } catch (NullPointerException ex) {
8535             Rlog.e(TAG, "getSimServiceTable(): NullPointerException=" + ex.getMessage());
8536         }
8537         return null;
8538     }
8539 
8540     /**
8541      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
8542      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
8543      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
8544      * state.
8545      *
8546      * @param slotIndex the sim slot to reset the IMS stack on.
8547      * @hide */
8548     @SystemApi
8549     @WorkerThread
8550     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8551     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
resetIms(int slotIndex)8552     public void resetIms(int slotIndex) {
8553         try {
8554             ITelephony telephony = getITelephony();
8555             if (telephony != null) {
8556                 telephony.resetIms(slotIndex);
8557             }
8558         } catch (RemoteException e) {
8559             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
8560                     + e.getMessage());
8561         }
8562     }
8563 
8564     /**
8565      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
8566      * status updates, if not already enabled.
8567      * @hide
8568      */
enableIms(int slotId)8569     public void enableIms(int slotId) {
8570         try {
8571             ITelephony telephony = getITelephony();
8572             if (telephony != null) {
8573                 telephony.enableIms(slotId);
8574             }
8575         } catch (RemoteException e) {
8576             Rlog.e(TAG, "enableIms, RemoteException: "
8577                     + e.getMessage());
8578         }
8579     }
8580 
8581     /**
8582      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
8583      * status updates to disabled.
8584      * @hide
8585      */
disableIms(int slotId)8586     public void disableIms(int slotId) {
8587         try {
8588             ITelephony telephony = getITelephony();
8589             if (telephony != null) {
8590                 telephony.disableIms(slotId);
8591             }
8592         } catch (RemoteException e) {
8593             Rlog.e(TAG, "disableIms, RemoteException: "
8594                     + e.getMessage());
8595         }
8596     }
8597 
8598     /**
8599      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
8600      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
8601      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
8602      * Corresponds to features defined in ImsFeature.
8603      * @hide
8604      */
8605     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsRegistration(int slotIndex, int feature)8606     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
8607         try {
8608             ITelephony telephony = getITelephony();
8609             if (telephony != null) {
8610                 return telephony.getImsRegistration(slotIndex, feature);
8611             }
8612         } catch (RemoteException e) {
8613             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
8614         }
8615         return null;
8616     }
8617 
8618     /**
8619      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
8620      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
8621      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
8622      * Corresponds to features defined in ImsFeature.
8623      * @hide
8624      */
8625     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsConfig(int slotIndex, int feature)8626     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
8627         try {
8628             ITelephony telephony = getITelephony();
8629             if (telephony != null) {
8630                 return telephony.getImsConfig(slotIndex, feature);
8631             }
8632         } catch (RemoteException e) {
8633             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
8634         }
8635         return null;
8636     }
8637 
8638     /**
8639      * Set IMS registration state on all active subscriptions.
8640      * <p/>
8641      * Use {@link android.telephony.ims.stub.ImsRegistrationImplBase#onRegistered} and
8642      * {@link android.telephony.ims.stub.ImsRegistrationImplBase#onDeregistered} to set Ims
8643      * registration state instead.
8644      *
8645      * @param registered whether ims is registered
8646      *
8647      * @hide
8648      */
8649     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setImsRegistrationState(final boolean registered)8650     public void setImsRegistrationState(final boolean registered) {
8651         try {
8652             final ITelephony telephony = getITelephony();
8653             if (telephony != null)
8654                 telephony.setImsRegistrationState(registered);
8655         } catch (final RemoteException e) {
8656         }
8657     }
8658 
8659     /** @hide */
8660     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
8661             NETWORK_MODE_WCDMA_PREF,
8662             NETWORK_MODE_GSM_ONLY,
8663             NETWORK_MODE_WCDMA_ONLY,
8664             NETWORK_MODE_GSM_UMTS,
8665             NETWORK_MODE_CDMA_EVDO,
8666             NETWORK_MODE_CDMA_NO_EVDO,
8667             NETWORK_MODE_EVDO_NO_CDMA,
8668             NETWORK_MODE_GLOBAL,
8669             NETWORK_MODE_LTE_CDMA_EVDO,
8670             NETWORK_MODE_LTE_GSM_WCDMA,
8671             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
8672             NETWORK_MODE_LTE_ONLY,
8673             NETWORK_MODE_LTE_WCDMA,
8674             NETWORK_MODE_TDSCDMA_ONLY,
8675             NETWORK_MODE_TDSCDMA_WCDMA,
8676             NETWORK_MODE_LTE_TDSCDMA,
8677             NETWORK_MODE_TDSCDMA_GSM,
8678             NETWORK_MODE_LTE_TDSCDMA_GSM,
8679             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
8680             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
8681             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
8682             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
8683             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
8684             NETWORK_MODE_NR_ONLY,
8685             NETWORK_MODE_NR_LTE,
8686             NETWORK_MODE_NR_LTE_CDMA_EVDO,
8687             NETWORK_MODE_NR_LTE_GSM_WCDMA,
8688             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
8689             NETWORK_MODE_NR_LTE_WCDMA,
8690             NETWORK_MODE_NR_LTE_TDSCDMA,
8691             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
8692             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
8693             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
8694             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
8695     })
8696     @Retention(RetentionPolicy.SOURCE)
8697     public @interface PrefNetworkMode{}
8698 
8699     /**
8700      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
8701      * @hide
8702      */
8703     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
8704 
8705     /**
8706      * Preferred network mode is GSM only.
8707      * @hide
8708      */
8709     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
8710 
8711     /**
8712      * Preferred network mode is WCDMA only.
8713      * @hide
8714      */
8715     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
8716 
8717     /**
8718      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
8719      * @hide
8720      */
8721     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
8722 
8723     /**
8724      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
8725      * @hide
8726      */
8727     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
8728 
8729     /**
8730      * Preferred network mode is CDMA only.
8731      * @hide
8732      */
8733     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
8734 
8735     /**
8736      * Preferred network mode is EvDo only.
8737      * @hide
8738      */
8739     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
8740 
8741     /**
8742      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
8743      * @hide
8744      */
8745     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
8746 
8747     /**
8748      * Preferred network mode is LTE, CDMA and EvDo.
8749      * @hide
8750      */
8751     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
8752 
8753     /**
8754      * Preferred network mode is LTE, GSM/WCDMA.
8755      * @hide
8756      */
8757     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
8758 
8759     /**
8760      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
8761      * @hide
8762      */
8763     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
8764             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
8765 
8766     /**
8767      * Preferred network mode is LTE Only.
8768      * @hide
8769      */
8770     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
8771 
8772     /**
8773      * Preferred network mode is LTE/WCDMA.
8774      * @hide
8775      */
8776     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
8777 
8778     /**
8779      * Preferred network mode is TD-SCDMA only.
8780      * @hide
8781      */
8782     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
8783 
8784     /**
8785      * Preferred network mode is TD-SCDMA and WCDMA.
8786      * @hide
8787      */
8788     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
8789 
8790     /**
8791      * Preferred network mode is TD-SCDMA and LTE.
8792      * @hide
8793      */
8794     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
8795 
8796     /**
8797      * Preferred network mode is TD-SCDMA and GSM.
8798      * @hide
8799      */
8800     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
8801 
8802     /**
8803      * Preferred network mode is TD-SCDMA,GSM and LTE.
8804      * @hide
8805      */
8806     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
8807             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
8808 
8809     /**
8810      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
8811      * @hide
8812      */
8813     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
8814             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
8815 
8816     /**
8817      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
8818      * @hide
8819      */
8820     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
8821             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
8822 
8823     /**
8824      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
8825      * @hide
8826      */
8827     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
8828             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
8829 
8830     /**
8831      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
8832      * @hide
8833      */
8834     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
8835             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
8836     /**
8837      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
8838      * @hide
8839      */
8840     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
8841             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
8842 
8843     /**
8844      * Preferred network mode is NR 5G only.
8845      * @hide
8846      */
8847     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
8848 
8849     /**
8850      * Preferred network mode is NR 5G, LTE.
8851      * @hide
8852      */
8853     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
8854 
8855     /**
8856      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
8857      * @hide
8858      */
8859     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
8860             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
8861 
8862     /**
8863      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
8864      * @hide
8865      */
8866     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
8867             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
8868 
8869     /**
8870      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
8871      * @hide
8872      */
8873     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
8874             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
8875 
8876     /**
8877      * Preferred network mode is NR 5G, LTE and WCDMA.
8878      * @hide
8879      */
8880     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
8881 
8882     /**
8883      * Preferred network mode is NR 5G, LTE and TDSCDMA.
8884      * @hide
8885      */
8886     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
8887 
8888     /**
8889      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
8890      * @hide
8891      */
8892     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
8893             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
8894 
8895     /**
8896      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
8897      * @hide
8898      */
8899     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
8900             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
8901 
8902     /**
8903      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
8904      * @hide
8905      */
8906     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
8907             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
8908 
8909     /**
8910      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
8911      * @hide
8912      */
8913     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
8914             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
8915 
8916     /**
8917      * The default preferred network mode constant.
8918      *
8919      * <p> This constant is used in case of nothing is set in
8920      * TelephonyProperties#default_network().
8921      *
8922      * @hide
8923      */
8924     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
8925             RILConstants.PREFERRED_NETWORK_MODE;
8926 
8927     /**
8928      * Get the preferred network type.
8929      * Used for device configuration by some CDMA operators.
8930      *
8931      * <p>Requires Permission:
8932      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8933      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8934      *
8935      * @return the preferred network type.
8936      * @hide
8937      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
8938      */
8939     @Deprecated
8940     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
8941     @UnsupportedAppUsage
getPreferredNetworkType(int subId)8942     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
8943         return RadioAccessFamily.getNetworkTypeFromRaf((int) getAllowedNetworkTypesBitmask());
8944     }
8945 
8946     /**
8947      * Get the preferred network type bitmask.
8948      *
8949      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8950      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8951      *
8952      * <p>Requires Permission:
8953      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8954      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8955      *
8956      * @return The bitmask of preferred network types.
8957      *
8958      * @hide
8959      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
8960      */
8961     @Deprecated
8962     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8963     @SystemApi
getPreferredNetworkTypeBitmask()8964     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
8965         return getAllowedNetworkTypesBitmask();
8966     }
8967 
8968     /**
8969      * Get the allowed network type bitmask.
8970      * Note that the device can only register on the network of {@link NetworkTypeBitmask}
8971      * (except for emergency call cases).
8972      *
8973      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8974      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8975      *
8976      * <p>Requires Permission:
8977      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8978      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8979      *
8980      * @return The bitmask of allowed network types.
8981      *
8982      * @hide
8983      */
8984     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8985     @SystemApi
8986     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getAllowedNetworkTypesBitmask()8987     public @NetworkTypeBitMask long getAllowedNetworkTypesBitmask() {
8988         try {
8989             ITelephony telephony = getITelephony();
8990             if (telephony != null) {
8991                 return (long) telephony.getAllowedNetworkTypesBitmask(getSubId());
8992             }
8993         } catch (RemoteException ex) {
8994             Rlog.e(TAG, "getAllowedNetworkTypesBitmask RemoteException", ex);
8995         }
8996         return 0;
8997     }
8998 
8999     /**
9000      * Get the allowed network types by carriers.
9001      *
9002      * <p>Requires Permission:
9003      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9004      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9005      *
9006      * @return the allowed network type bitmask
9007      * @hide
9008      * @deprecated Use {@link #getAllowedNetworkTypesForReason} instead.
9009      */
9010     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9011     @SystemApi
9012     @Deprecated
getAllowedNetworkTypes()9013     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
9014         try {
9015             ITelephony telephony = getITelephony();
9016             if (telephony != null) {
9017                 return telephony.getAllowedNetworkTypesForReason(getSubId(),
9018                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER);
9019             }
9020         } catch (RemoteException ex) {
9021             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
9022         }
9023         return -1;
9024     }
9025 
9026     /**
9027      * Sets the network selection mode to automatic.
9028      *
9029      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9030      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9031      *
9032      * <p>Requires Permission:
9033      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9034      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9035      */
9036     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9037     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9038     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeAutomatic()9039     public void setNetworkSelectionModeAutomatic() {
9040         try {
9041             ITelephony telephony = getITelephony();
9042             if (telephony != null) {
9043                 telephony.setNetworkSelectionModeAutomatic(getSubId());
9044             }
9045         } catch (RemoteException ex) {
9046             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
9047         } catch (NullPointerException ex) {
9048             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
9049         }
9050     }
9051 
9052     /**
9053      * Perform a radio scan and return the list of available networks.
9054      *
9055      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9056      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9057      *
9058      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
9059      *
9060      * <p>Requires Permissions:
9061      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
9062      * privileges (see {@link #hasCarrierPrivileges})
9063      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
9064      *
9065      * @return {@link CellNetworkScanResult} with the status
9066      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
9067      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
9068      * caused will be included in the result.
9069      *
9070      * @hide
9071      */
9072     @RequiresPermission(allOf = {
9073             android.Manifest.permission.MODIFY_PHONE_STATE,
9074             Manifest.permission.ACCESS_COARSE_LOCATION
9075     })
getAvailableNetworks()9076     public CellNetworkScanResult getAvailableNetworks() {
9077         try {
9078             ITelephony telephony = getITelephony();
9079             if (telephony != null) {
9080                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
9081                         getAttributionTag());
9082             }
9083         } catch (RemoteException ex) {
9084             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
9085         } catch (NullPointerException ex) {
9086             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
9087         }
9088         return new CellNetworkScanResult(
9089                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
9090     }
9091 
9092     /**
9093      * Request a network scan.
9094      *
9095      * This method is asynchronous, so the network scan results will be returned by callback.
9096      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
9097      *
9098      * <p>Requires Permission:
9099      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9100      * app has carrier privileges (see {@link #hasCarrierPrivileges})
9101      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
9102      *
9103      * If the system-wide location switch is off, apps may still call this API, with the
9104      * following constraints:
9105      * <ol>
9106      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
9107      *     <li>The app must not supply any specific bands or channels to scan.</li>
9108      *     <li>The app must only specify MCC/MNC pairs that are
9109      *     associated to a SIM in the device.</li>
9110      *     <li>Returned results will have no meaningful info other than signal strength
9111      *     and MCC/MNC info.</li>
9112      * </ol>
9113      *
9114      * @param request Contains all the RAT with bands/channels that need to be scanned.
9115      * @param executor The executor through which the callback should be invoked. Since the scan
9116      *        request may trigger multiple callbacks and they must be invoked in the same order as
9117      *        they are received by the platform, the user should provide an executor which executes
9118      *        tasks one at a time in serial order.
9119      * @param callback Returns network scan results or errors.
9120      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
9121      */
9122     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9123     @RequiresPermission(allOf = {
9124             android.Manifest.permission.MODIFY_PHONE_STATE,
9125             Manifest.permission.ACCESS_FINE_LOCATION
9126     })
9127     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)9128     public NetworkScan requestNetworkScan(
9129             NetworkScanRequest request, Executor executor,
9130             TelephonyScanManager.NetworkScanCallback callback) {
9131         return requestNetworkScan(INCLUDE_LOCATION_DATA_FINE, request, executor, callback);
9132     }
9133 
9134     /**
9135      * Request a network scan.
9136      *
9137      * This method is asynchronous, so the network scan results will be returned by callback.
9138      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
9139      *
9140      * <p>Requires Permission:
9141      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9142      * app has carrier privileges (see {@link #hasCarrierPrivileges})
9143      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION} if includeLocationData is
9144      * set to {@link #INCLUDE_LOCATION_DATA_FINE}.
9145      *
9146      * If the system-wide location switch is off, apps may still call this API, with the
9147      * following constraints:
9148      * <ol>
9149      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
9150      *     <li>The app must not supply any specific bands or channels to scan.</li>
9151      *     <li>The app must only specify MCC/MNC pairs that are
9152      *     associated to a SIM in the device.</li>
9153      *     <li>Returned results will have no meaningful info other than signal strength
9154      *     and MCC/MNC info.</li>
9155      * </ol>
9156      *
9157      * @param includeLocationData Specifies if the caller would like to receive
9158      * location related information. If this parameter is set to
9159      * {@link #INCLUDE_LOCATION_DATA_FINE} then the application will be checked for
9160      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission and available
9161      * location related information received during network scan will be sent to the caller.
9162      * @param request Contains all the RAT with bands/channels that need to be scanned.
9163      * @param executor The executor through which the callback should be invoked. Since the scan
9164      *        request may trigger multiple callbacks and they must be invoked in the same order as
9165      *        they are received by the platform, the user should provide an executor which executes
9166      *        tasks one at a time in serial order.
9167      * @param callback Returns network scan results or errors.
9168      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
9169      */
9170     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9171     @RequiresPermission(allOf = {
9172             android.Manifest.permission.MODIFY_PHONE_STATE
9173     })
requestNetworkScan( @ncludeLocationData int includeLocationData, @NonNull NetworkScanRequest request, @NonNull Executor executor, @NonNull TelephonyScanManager.NetworkScanCallback callback)9174     public @Nullable NetworkScan requestNetworkScan(
9175             @IncludeLocationData int includeLocationData,
9176             @NonNull NetworkScanRequest request,
9177             @NonNull Executor executor,
9178             @NonNull TelephonyScanManager.NetworkScanCallback callback) {
9179         synchronized (sCacheLock) {
9180             if (mTelephonyScanManager == null) {
9181                 mTelephonyScanManager = new TelephonyScanManager();
9182             }
9183         }
9184         return mTelephonyScanManager.requestNetworkScan(getSubId(),
9185                 includeLocationData != INCLUDE_LOCATION_DATA_FINE,
9186                 request, executor, callback,
9187                 getOpPackageName(), getAttributionTag());
9188     }
9189 
9190     /**
9191      * @deprecated
9192      * Use {@link
9193      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
9194      * @removed
9195      */
9196     @Deprecated
9197     @RequiresPermission(allOf = {
9198             android.Manifest.permission.MODIFY_PHONE_STATE,
9199             Manifest.permission.ACCESS_FINE_LOCATION
9200     })
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)9201     public NetworkScan requestNetworkScan(
9202         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
9203         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
9204     }
9205 
9206     /**
9207      * Ask the radio to connect to the input network and change selection mode to manual.
9208      *
9209      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9210      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9211      *
9212      * <p>Requires Permission:
9213      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9214      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9215      *
9216      * @param operatorNumeric the PLMN ID of the network to select.
9217      * @param persistSelection whether the selection will persist until reboot. If true, only allows
9218      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
9219      * normal network selection next time.
9220      * @return {@code true} on success; {@code false} on any failure.
9221      */
9222     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9223     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9224     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)9225     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
9226         return setNetworkSelectionModeManual(
9227                 new OperatorInfo(
9228                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
9229                 persistSelection);
9230     }
9231 
9232     /**
9233      * Ask the radio to connect to the input network and change selection mode to manual.
9234      *
9235      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9236      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9237      *
9238      * <p>Requires Permission:
9239      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9240      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9241      *
9242      * @param operatorNumeric the PLMN ID of the network to select.
9243      * @param persistSelection whether the selection will persist until reboot.
9244      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
9245      *         attach to the chosen PLMN and resume normal network selection next time.
9246      * @param ran the initial suggested radio access network type.
9247      *         If registration fails, the RAN is not available after, the RAN is not within the
9248      *         network types specified by the preferred network types, or the value is
9249      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
9250      *         the next best RAN for network registration.
9251      * @return {@code true} on success; {@code false} on any failure.
9252      */
9253     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9254     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)9255     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
9256             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
9257         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
9258                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
9259     }
9260 
9261     /**
9262      * Ask the radio to connect to the input network and change selection mode to manual.
9263      *
9264      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9265      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9266      *
9267      * <p>Requires Permission:
9268      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9269      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9270      *
9271      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
9272      * @param persistSelection whether the selection will persist until reboot. If true, only allows
9273      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
9274      * normal network selection next time.
9275      * @return {@code true} on success; {@code true} on any failure.
9276      *
9277      * @hide
9278      */
9279     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)9280     public boolean setNetworkSelectionModeManual(
9281             OperatorInfo operatorInfo, boolean persistSelection) {
9282         try {
9283             ITelephony telephony = getITelephony();
9284             if (telephony != null) {
9285                 return telephony.setNetworkSelectionModeManual(
9286                         getSubId(), operatorInfo, persistSelection);
9287             }
9288         } catch (RemoteException ex) {
9289             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
9290         }
9291         return false;
9292     }
9293 
9294     /**
9295      * Get the network selection mode.
9296      *
9297      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9298      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9299      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
9300      * READ_PRECISE_PHONE_STATE}
9301      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9302      *
9303      * @return the network selection mode.
9304      */
9305     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
9306     @RequiresPermission(anyOf = {
9307             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9308             android.Manifest.permission.READ_PRECISE_PHONE_STATE
9309     })
9310     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkSelectionMode()9311     public @NetworkSelectionMode int getNetworkSelectionMode() {
9312         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
9313         try {
9314             ITelephony telephony = getITelephony();
9315             if (telephony != null) {
9316                 mode = telephony.getNetworkSelectionMode(getSubId());
9317             }
9318         } catch (RemoteException ex) {
9319             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
9320         }
9321         return mode;
9322     }
9323 
9324     /**
9325      * Get the PLMN chosen for Manual Network Selection if active.
9326      * Return empty string if in automatic selection.
9327      *
9328      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
9329      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
9330      * (see {@link #hasCarrierPrivileges})
9331      *
9332      * @return manually selected network info on success or empty string on failure
9333      */
9334     @SuppressAutoDoc // No support carrier privileges (b/72967236).
9335     @RequiresPermission(android.Manifest.permission.READ_PRECISE_PHONE_STATE)
9336     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getManualNetworkSelectionPlmn()9337     public @NonNull String getManualNetworkSelectionPlmn() {
9338         try {
9339             ITelephony telephony = getITelephony();
9340             if (telephony != null && isManualNetworkSelectionAllowed()) {
9341                 return telephony.getManualNetworkSelectionPlmn(getSubId());
9342             }
9343         } catch (RemoteException ex) {
9344             Rlog.e(TAG, "getManualNetworkSelectionPlmn RemoteException", ex);
9345         }
9346         return "";
9347     }
9348 
9349     /**
9350      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
9351      * user and we are still within the time interval after the emergency SMS was sent that we are
9352      * considered in Emergency SMS mode.
9353      *
9354      * <p>This mode is used by other applications to allow them to perform special functionality,
9355      * such as allow the GNSS service to provide user location to the carrier network for emergency
9356      * when an emergency SMS is sent. This interval is set by
9357      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
9358      * the carrier does not support this mode, this function will always return false.
9359      *
9360      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
9361      *
9362      * @hide
9363      */
9364     @SystemApi
9365     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9366     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
isInEmergencySmsMode()9367     public boolean isInEmergencySmsMode() {
9368         try {
9369             ITelephony telephony = getITelephony();
9370             if (telephony != null) {
9371                 return telephony.isInEmergencySmsMode();
9372             }
9373         } catch (RemoteException ex) {
9374             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
9375         }
9376         return false;
9377     }
9378 
9379     /**
9380      * Set the preferred network type.
9381      *
9382      * <p>Requires Permission:
9383      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9384      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9385      * <p>
9386      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
9387      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
9388      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
9389      * setPreferredNetworkTypesBitmap is used instead.
9390      *
9391      * @param subId the id of the subscription to set the preferred network type for.
9392      * @param networkType the preferred network type
9393      * @return true on success; false on any failure.
9394      * @hide
9395      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
9396      */
9397     @Deprecated
9398     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)9399     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
9400         try {
9401             ITelephony telephony = getITelephony();
9402             if (telephony != null) {
9403                 return telephony.setAllowedNetworkTypesForReason(subId,
9404                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
9405                         RadioAccessFamily.getRafFromNetworkType(networkType));
9406             }
9407         } catch (RemoteException ex) {
9408             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
9409         }
9410         return false;
9411     }
9412 
9413     /**
9414      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
9415      * only the allowed network type will set to the modem.
9416      *
9417      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9418      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9419      *
9420      * <p>Requires Permission:
9421      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9422      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9423      * <p>
9424      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
9425      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
9426      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
9427      * setPreferredNetworkTypesBitmap is used instead.
9428      *
9429      * @param networkTypeBitmask The bitmask of preferred network types.
9430      * @return true on success; false on any failure.
9431      * @hide
9432      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
9433      */
9434     @Deprecated
9435     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9436     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)9437     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
9438         try {
9439             ITelephony telephony = getITelephony();
9440             if (telephony != null) {
9441                 networkTypeBitmask = checkNetworkTypeBitmask(networkTypeBitmask);
9442                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
9443                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER, networkTypeBitmask);
9444             }
9445         } catch (RemoteException ex) {
9446             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
9447         }
9448         return false;
9449     }
9450 
9451     /**
9452      * If {@link #NETWORK_TYPE_BITMASK_LTE_CA} bit is set, convert it to NETWORK_TYPE_BITMASK_LTE.
9453      *
9454      * @param networkTypeBitmask The networkTypeBitmask being checked
9455      * @return The checked/converted networkTypeBitmask
9456      */
checkNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)9457     private long checkNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
9458         if ((networkTypeBitmask & NETWORK_TYPE_BITMASK_LTE_CA) != 0) {
9459             networkTypeBitmask ^= NETWORK_TYPE_BITMASK_LTE_CA;
9460             networkTypeBitmask |= NETWORK_TYPE_BITMASK_LTE;
9461         }
9462         return networkTypeBitmask;
9463     }
9464 
9465     /**
9466      * Set the allowed network types of the device. This is for carrier or privileged apps to
9467      * enable/disable certain network types on the device. The user preferred network types should
9468      * be set through {@link #setPreferredNetworkTypeBitmask}.
9469      * <p>
9470      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
9471      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
9472      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
9473      * setPreferredNetworkTypesBitmap is used instead.
9474      *
9475      * @param allowedNetworkTypes The bitmask of allowed network types.
9476      * @return true on success; false on any failure.
9477      * @hide
9478      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead with reason
9479      * {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}.
9480      */
9481     @Deprecated
9482     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9483     @RequiresFeature(
9484             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
9485             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
9486     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)9487     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
9488         try {
9489             ITelephony telephony = getITelephony();
9490             if (telephony != null) {
9491                 allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
9492                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
9493                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER, allowedNetworkTypes);
9494             }
9495         } catch (RemoteException ex) {
9496             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
9497         }
9498         return false;
9499     }
9500 
9501     /** @hide */
9502     @IntDef({
9503             ALLOWED_NETWORK_TYPES_REASON_USER,
9504             ALLOWED_NETWORK_TYPES_REASON_POWER,
9505             ALLOWED_NETWORK_TYPES_REASON_CARRIER,
9506             ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G,
9507     })
9508     @Retention(RetentionPolicy.SOURCE)
9509     public @interface AllowedNetworkTypesReason {
9510     }
9511 
9512     /**
9513      * To indicate allowed network type change is requested by user.
9514      */
9515     public static final int ALLOWED_NETWORK_TYPES_REASON_USER = 0;
9516 
9517     /**
9518      * To indicate allowed network type change is requested by power manager.
9519      * Power Manger configuration won't affect the settings configured through
9520      * other reasons and will result in allowing network types that are in both
9521      * configurations (i.e intersection of both sets).
9522      *
9523      * @hide
9524      */
9525     @SystemApi
9526     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 1;
9527 
9528     /**
9529      * To indicate allowed network type change is requested by carrier.
9530      * Carrier configuration won't affect the settings configured through
9531      * other reasons and will result in allowing network types that are in both
9532      * configurations (i.e intersection of both sets).
9533      */
9534     public static final int ALLOWED_NETWORK_TYPES_REASON_CARRIER = 2;
9535 
9536     /**
9537      * To indicate allowed network type change is requested by the user via the 2G toggle.
9538      *
9539      * @hide
9540      */
9541     @SystemApi
9542     public static final int ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G = 3;
9543 
9544     /**
9545      * Set the allowed network types of the device and provide the reason triggering the allowed
9546      * network change.
9547      * <p>Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
9548      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9549      *
9550      * This can be called for following reasons:
9551      * <ol>
9552      * <li>Allowed network types control by USER
9553      * {@link TelephonyManager#ALLOWED_NETWORK_TYPES_REASON_USER}
9554      * <li>Allowed network types control by carrier {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}
9555      * </ol>
9556      * This API will result in allowing an intersection of allowed network types for all reasons,
9557      * including the configuration done through other reasons.
9558      *
9559      * @param reason the reason the allowed network type change is taking place
9560      * @param allowedNetworkTypes The bitmask of allowed network type
9561      * @throws IllegalStateException if the Telephony process is not currently available.
9562      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
9563      * @throws SecurityException if the caller does not have the required privileges or if the
9564      * caller tries to use one of the following security-based reasons without
9565      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} permissions.
9566      * <ol>
9567      *     <li>{@code TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G}</li>
9568      * </ol>
9569      */
9570     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9571     @RequiresFeature(
9572             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
9573             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)9574     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
9575             @NetworkTypeBitMask long allowedNetworkTypes) {
9576         if (!isValidAllowedNetworkTypesReason(reason)) {
9577             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
9578         }
9579 
9580         try {
9581             ITelephony telephony = getITelephony();
9582             if (telephony != null) {
9583                 allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
9584                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
9585                         allowedNetworkTypes);
9586             } else {
9587                 throw new IllegalStateException("telephony service is null.");
9588             }
9589         } catch (RemoteException ex) {
9590             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
9591             ex.rethrowFromSystemServer();
9592         }
9593     }
9594 
9595     /**
9596      * Get the allowed network types for certain reason.
9597      *
9598      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
9599      * specific reason.
9600      * <p>Requires permission: android.Manifest.READ_PRIVILEGED_PHONE_STATE or
9601      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9602      *
9603      * @param reason the reason the allowed network type change is taking place
9604      * @return the allowed network type bitmask
9605      * @throws IllegalStateException    if the Telephony process is not currently available.
9606      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
9607      * @throws SecurityException if the caller does not have the required permission/privileges
9608      */
9609     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9610     @RequiresFeature(
9611             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
9612             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)9613     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
9614             @AllowedNetworkTypesReason int reason) {
9615         if (!isValidAllowedNetworkTypesReason(reason)) {
9616             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
9617         }
9618 
9619         try {
9620             ITelephony telephony = getITelephony();
9621             if (telephony != null) {
9622                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
9623             } else {
9624                 throw new IllegalStateException("telephony service is null.");
9625             }
9626         } catch (RemoteException ex) {
9627             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
9628             ex.rethrowFromSystemServer();
9629         }
9630         return -1;
9631     }
9632     /**
9633      * Verifies that the reason provided is valid.
9634      * @hide
9635      */
isValidAllowedNetworkTypesReason(@llowedNetworkTypesReason int reason)9636     public static boolean isValidAllowedNetworkTypesReason(@AllowedNetworkTypesReason int reason) {
9637         switch (reason) {
9638             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER:
9639             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER:
9640             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER:
9641             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G:
9642                 return true;
9643         }
9644         return false;
9645     }
9646     /**
9647      * Get bit mask of all network types.
9648      *
9649      * @return bit mask of all network types
9650      * @hide
9651      */
getAllNetworkTypesBitmask()9652     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
9653         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
9654     }
9655 
9656     /**
9657      * Returns a string representation of the allowed network types{@link NetworkTypeBitMask}.
9658      *
9659      * @param networkTypeBitmask The bitmask of allowed network types.
9660      * @return the name of the allowed network types
9661      * @hide
9662      */
convertNetworkTypeBitmaskToString( @etworkTypeBitMask long networkTypeBitmask)9663     public static String convertNetworkTypeBitmaskToString(
9664             @NetworkTypeBitMask long networkTypeBitmask) {
9665         String networkTypeName = IntStream.rangeClosed(NETWORK_TYPE_GPRS, NETWORK_TYPE_NR)
9666                 .filter(x -> {
9667                     return (networkTypeBitmask & getBitMaskForNetworkType(x))
9668                             == getBitMaskForNetworkType(x);
9669                 })
9670                 .mapToObj(x -> getNetworkTypeName(x))
9671                 .collect(Collectors.joining("|"));
9672         return TextUtils.isEmpty(networkTypeName) ? "UNKNOWN" : networkTypeName;
9673     }
9674 
9675     /**
9676      * Set the preferred network type to global mode which includes NR, LTE, CDMA, EvDo
9677      * and GSM/WCDMA.
9678      *
9679      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9680      *
9681      * @return true on success; false on any failure.
9682      */
9683     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setPreferredNetworkTypeToGlobal()9684     public boolean setPreferredNetworkTypeToGlobal() {
9685         return setPreferredNetworkTypeToGlobal(getSubId());
9686     }
9687 
9688     /**
9689      * Set the preferred network type to global mode which includes NR, LTE, CDMA, EvDo
9690      * and GSM/WCDMA.
9691      *
9692      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9693      *
9694      * @return true on success; false on any failure.
9695      * @hide
9696      */
setPreferredNetworkTypeToGlobal(int subId)9697     public boolean setPreferredNetworkTypeToGlobal(int subId) {
9698         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA);
9699     }
9700 
9701     /**
9702      * Check whether DUN APN is required for tethering.
9703      * <p>
9704      * Requires Permission: MODIFY_PHONE_STATE.
9705      *
9706      * @return {@code true} if DUN APN is required for tethering.
9707      * @hide
9708      */
9709     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9710     @SystemApi
9711     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isTetheringApnRequired()9712     public boolean isTetheringApnRequired() {
9713         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
9714     }
9715 
9716     /**
9717      * Check whether DUN APN is required for tethering with subId.
9718      *
9719      * @param subId the id of the subscription to require tethering.
9720      * @return {@code true} if DUN APN is required for tethering.
9721      * @hide
9722      */
isTetheringApnRequired(int subId)9723     public boolean isTetheringApnRequired(int subId) {
9724         try {
9725             ITelephony telephony = getITelephony();
9726             if (telephony != null)
9727                 return telephony.isTetheringApnRequiredForSubscriber(subId);
9728         } catch (RemoteException ex) {
9729             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
9730         } catch (NullPointerException ex) {
9731             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
9732         }
9733         return false;
9734     }
9735 
9736 
9737     /**
9738      * Values used to return status for hasCarrierPrivileges call.
9739      */
9740     /** @hide */ @SystemApi
9741     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
9742     /** @hide */ @SystemApi
9743     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
9744     /** @hide */ @SystemApi
9745     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
9746     /** @hide */ @SystemApi
9747     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
9748 
9749     /**
9750      * Has the calling application been granted carrier privileges by the carrier.
9751      *
9752      * If any of the packages in the calling UID has carrier privileges, the
9753      * call will return true. This access is granted by the owner of the UICC
9754      * card and does not depend on the registered carrier.
9755      *
9756      * Note that this API applies to both physical and embedded subscriptions and
9757      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
9758      *
9759      * @return true if the app has carrier privileges.
9760      */
9761     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
hasCarrierPrivileges()9762     public boolean hasCarrierPrivileges() {
9763         return hasCarrierPrivileges(getSubId());
9764     }
9765 
9766     /**
9767      * Has the calling application been granted carrier privileges by the carrier.
9768      *
9769      * If any of the packages in the calling UID has carrier privileges, the
9770      * call will return true. This access is granted by the owner of the UICC
9771      * card and does not depend on the registered carrier.
9772      *
9773      * Note that this API applies to both physical and embedded subscriptions and
9774      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
9775      *
9776      * @param subId The subscription to use.
9777      * @return true if the app has carrier privileges.
9778      * @hide
9779      */
hasCarrierPrivileges(int subId)9780     public boolean hasCarrierPrivileges(int subId) {
9781         try {
9782             ITelephony telephony = getITelephony();
9783             if (telephony != null) {
9784                 return telephony.getCarrierPrivilegeStatus(subId)
9785                         == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
9786             }
9787         } catch (RemoteException ex) {
9788             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
9789         } catch (NullPointerException ex) {
9790             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
9791         }
9792         return false;
9793     }
9794 
9795     /**
9796      * Override the branding for the current ICCID.
9797      *
9798      * Once set, whenever the SIM is present in the device, the service
9799      * provider name (SPN) and the operator name will both be replaced by the
9800      * brand value input. To unset the value, the same function should be
9801      * called with a null brand value.
9802      *
9803      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9804      *
9805      * @param brand The brand name to display/set.
9806      * @return true if the operation was executed correctly.
9807      */
9808     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setOperatorBrandOverride(String brand)9809     public boolean setOperatorBrandOverride(String brand) {
9810         return setOperatorBrandOverride(getSubId(), brand);
9811     }
9812 
9813     /**
9814      * Override the branding for the current ICCID.
9815      *
9816      * Once set, whenever the SIM is present in the device, the service
9817      * provider name (SPN) and the operator name will both be replaced by the
9818      * brand value input. To unset the value, the same function should be
9819      * called with a null brand value.
9820      *
9821      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9822      *
9823      * @param subId The subscription to use.
9824      * @param brand The brand name to display/set.
9825      * @return true if the operation was executed correctly.
9826      * @hide
9827      */
setOperatorBrandOverride(int subId, String brand)9828     public boolean setOperatorBrandOverride(int subId, String brand) {
9829         try {
9830             ITelephony telephony = getITelephony();
9831             if (telephony != null)
9832                 return telephony.setOperatorBrandOverride(subId, brand);
9833         } catch (RemoteException ex) {
9834             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
9835         } catch (NullPointerException ex) {
9836             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
9837         }
9838         return false;
9839     }
9840 
9841     /**
9842      * Override the roaming preference for the current ICCID.
9843      *
9844      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
9845      * the platform's notion of a network operator being considered roaming or not.
9846      * The change only affects the ICCID that was active when this call was made.
9847      *
9848      * If null is passed as any of the input, the corresponding value is deleted.
9849      *
9850      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
9851      *
9852      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
9853      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
9854      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
9855      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
9856      * @return true if the operation was executed correctly.
9857      *
9858      * @hide
9859      */
9860     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)9861     public boolean setRoamingOverride(List<String> gsmRoamingList,
9862             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
9863             List<String> cdmaNonRoamingList) {
9864         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
9865                 cdmaRoamingList, cdmaNonRoamingList);
9866     }
9867 
9868     /**
9869      * Override the roaming preference for the current ICCID.
9870      *
9871      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
9872      * the platform's notion of a network operator being considered roaming or not.
9873      * The change only affects the ICCID that was active when this call was made.
9874      *
9875      * If null is passed as any of the input, the corresponding value is deleted.
9876      *
9877      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
9878      *
9879      * @param subId for which the roaming overrides apply.
9880      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
9881      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
9882      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
9883      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
9884      * @return true if the operation was executed correctly.
9885      *
9886      * @hide
9887      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)9888     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
9889             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
9890             List<String> cdmaNonRoamingList) {
9891         try {
9892             ITelephony telephony = getITelephony();
9893             if (telephony != null)
9894                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
9895                         cdmaRoamingList, cdmaNonRoamingList);
9896         } catch (RemoteException ex) {
9897             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
9898         } catch (NullPointerException ex) {
9899             Rlog.e(TAG, "setRoamingOverride NPE", ex);
9900         }
9901         return false;
9902     }
9903 
9904     /**
9905      * Expose the rest of ITelephony to @SystemApi
9906      */
9907 
9908     /** @hide */
9909     @SystemApi
9910     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9911     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMdn()9912     public String getCdmaMdn() {
9913         return getCdmaMdn(getSubId());
9914     }
9915 
9916     /** @hide */
9917     @SystemApi
9918     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9919     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMdn(int subId)9920     public String getCdmaMdn(int subId) {
9921         try {
9922             ITelephony telephony = getITelephony();
9923             if (telephony == null)
9924                 return null;
9925             return telephony.getCdmaMdn(subId);
9926         } catch (RemoteException ex) {
9927             return null;
9928         } catch (NullPointerException ex) {
9929             return null;
9930         }
9931     }
9932 
9933     /** @hide */
9934     @SystemApi
9935     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9936     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMin()9937     public String getCdmaMin() {
9938         return getCdmaMin(getSubId());
9939     }
9940 
9941     /** @hide */
9942     @SystemApi
9943     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9944     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMin(int subId)9945     public String getCdmaMin(int subId) {
9946         try {
9947             ITelephony telephony = getITelephony();
9948             if (telephony == null)
9949                 return null;
9950             return telephony.getCdmaMin(subId);
9951         } catch (RemoteException ex) {
9952             return null;
9953         } catch (NullPointerException ex) {
9954             return null;
9955         }
9956     }
9957 
9958     /** @hide */
9959     @SystemApi
9960     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9961     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
checkCarrierPrivilegesForPackage(String pkgName)9962     public int checkCarrierPrivilegesForPackage(String pkgName) {
9963         try {
9964             ITelephony telephony = getITelephony();
9965             if (telephony != null)
9966                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
9967         } catch (RemoteException ex) {
9968             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
9969         } catch (NullPointerException ex) {
9970             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
9971         }
9972         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
9973     }
9974 
9975     /** @hide */
9976     @SystemApi
9977     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9978     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)9979     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
9980         try {
9981             ITelephony telephony = getITelephony();
9982             if (telephony != null)
9983                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
9984         } catch (RemoteException ex) {
9985             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
9986         } catch (NullPointerException ex) {
9987             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
9988         }
9989         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
9990     }
9991 
9992     /** @hide */
9993     @SystemApi
9994     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPackageNamesForIntent(Intent intent)9995     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
9996         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
9997     }
9998 
9999     /** @hide */
10000     @SystemApi
10001     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10002     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)10003     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
10004         try {
10005             ITelephony telephony = getITelephony();
10006             if (telephony != null)
10007                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
10008         } catch (RemoteException ex) {
10009             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
10010         } catch (NullPointerException ex) {
10011             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
10012         }
10013         return null;
10014     }
10015 
10016     /**
10017      * Returns the package name that provides the {@link CarrierService} implementation for the
10018      * current subscription, or {@code null} if no package with carrier privileges declares one.
10019      *
10020      * <p>If this object has been created with {@link #createForSubscriptionId}, then the provided
10021      * subscription ID is used. Otherwise, the default subscription ID will be used.
10022      *
10023      * @return The system-selected package that provides the {@link CarrierService} implementation
10024      * for the current subscription, or {@code null} if none is resolved
10025      *
10026      * @hide
10027      */
10028     @SystemApi
10029     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierServicePackageName()10030     public @Nullable String getCarrierServicePackageName() {
10031         return getCarrierServicePackageNameForLogicalSlot(getPhoneId());
10032     }
10033 
10034     /**
10035      * Returns the package name that provides the {@link CarrierService} implementation for the
10036      * specified {@code logicalSlotIndex}, or {@code null} if no package with carrier privileges
10037      * declares one.
10038      *
10039      * @param logicalSlotIndex The slot index to fetch the {@link CarrierService} package for
10040      * @return The system-selected package that provides the {@link CarrierService} implementation
10041      * for the slot, or {@code null} if none is resolved
10042      *
10043      * @hide
10044      */
10045     @SystemApi
10046     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex)10047     public @Nullable String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex) {
10048         try {
10049             ITelephony telephony = getITelephony();
10050             if (telephony != null) {
10051                 return telephony.getCarrierServicePackageNameForLogicalSlot(logicalSlotIndex);
10052             }
10053         } catch (RemoteException ex) {
10054             Rlog.e(TAG, "getCarrierServicePackageNameForLogicalSlot RemoteException", ex);
10055         } catch (NullPointerException ex) {
10056             Rlog.e(TAG, "getCarrierServicePackageNameForLogicalSlot NPE", ex);
10057         }
10058         return null;
10059     }
10060 
10061     /** @hide */
10062     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPackagesWithCarrierPrivileges()10063     public List<String> getPackagesWithCarrierPrivileges() {
10064         try {
10065             ITelephony telephony = getITelephony();
10066             if (telephony != null) {
10067                 return telephony.getPackagesWithCarrierPrivileges(getPhoneId());
10068             }
10069         } catch (RemoteException ex) {
10070             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
10071         } catch (NullPointerException ex) {
10072             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
10073         }
10074         return Collections.EMPTY_LIST;
10075     }
10076 
10077     /**
10078      * Get the names of packages with carrier privileges for all the active subscriptions.
10079      *
10080      * @hide
10081      */
10082     @SystemApi
10083     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10084     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
10085     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()10086     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
10087         try {
10088             ITelephony telephony = getITelephony();
10089             if (telephony != null) {
10090                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
10091             }
10092         } catch (RemoteException ex) {
10093             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
10094                     ex);
10095         } catch (NullPointerException ex) {
10096             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
10097         }
10098         return Collections.EMPTY_LIST;
10099     }
10100 
10101     /**
10102      * Call composer status OFF from user setting.
10103      */
10104     public static final int CALL_COMPOSER_STATUS_OFF = 0;
10105 
10106     /**
10107      * Call composer status ON from user setting.
10108      */
10109     public static final int CALL_COMPOSER_STATUS_ON = 1;
10110 
10111     /** @hide */
10112     @IntDef(prefix = {"CALL_COMPOSER_STATUS_"},
10113             value = {
10114                 CALL_COMPOSER_STATUS_ON,
10115                 CALL_COMPOSER_STATUS_OFF,
10116             })
10117     public @interface CallComposerStatus {}
10118 
10119     /**
10120      * Set the user-set status for enriched calling with call composer.
10121      *
10122      * @param status user-set status for enriched calling with call composer.
10123      *
10124      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10125      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10126      *
10127      * @throws IllegalArgumentException if requested state is invalid.
10128      * @throws SecurityException if the caller does not have the permission.
10129      */
10130     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10131     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallComposerStatus(@allComposerStatus int status)10132     public void setCallComposerStatus(@CallComposerStatus int status) {
10133         if (status > CALL_COMPOSER_STATUS_ON
10134                 || status < CALL_COMPOSER_STATUS_OFF) {
10135             throw new IllegalArgumentException("requested status is invalid");
10136         }
10137         try {
10138             ITelephony telephony = getITelephony();
10139             if (telephony != null) {
10140                 telephony.setCallComposerStatus(getSubId(), status);
10141             }
10142         } catch (RemoteException ex) {
10143             Log.e(TAG, "Error calling ITelephony#setCallComposerStatus", ex);
10144             ex.rethrowFromSystemServer();
10145         }
10146     }
10147 
10148     /**
10149      * Get the user-set status for enriched calling with call composer.
10150      *
10151      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10152      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10153      *
10154      * @throws SecurityException if the caller does not have the permission.
10155      *
10156      * @return the user-set status for enriched calling with call composer, either of
10157      * {@link #CALL_COMPOSER_STATUS_ON} or {@link #CALL_COMPOSER_STATUS_OFF}.
10158      */
10159     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10160     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallComposerStatus()10161     public @CallComposerStatus int getCallComposerStatus() {
10162         try {
10163             ITelephony telephony = getITelephony();
10164             if (telephony != null) {
10165                 return telephony.getCallComposerStatus(getSubId());
10166             }
10167         } catch (RemoteException ex) {
10168             Log.e(TAG, "Error calling ITelephony#getCallComposerStatus", ex);
10169             ex.rethrowFromSystemServer();
10170         }
10171         return CALL_COMPOSER_STATUS_OFF;
10172     }
10173 
10174     /** @hide */
10175     @SystemApi
10176     @SuppressLint("RequiresPermission")
10177     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
dial(String number)10178     public void dial(String number) {
10179         try {
10180             ITelephony telephony = getITelephony();
10181             if (telephony != null)
10182                 telephony.dial(number);
10183         } catch (RemoteException e) {
10184             Log.e(TAG, "Error calling ITelephony#dial", e);
10185         }
10186     }
10187 
10188     /**
10189      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
10190      * Bundle extras)} instead.
10191      * @hide
10192      */
10193     @Deprecated
10194     @SystemApi
10195     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
call(String callingPackage, String number)10196     public void call(String callingPackage, String number) {
10197         try {
10198             ITelephony telephony = getITelephony();
10199             if (telephony != null)
10200                 telephony.call(callingPackage, number);
10201         } catch (RemoteException e) {
10202             Log.e(TAG, "Error calling ITelephony#call", e);
10203         }
10204     }
10205 
10206     /**
10207      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
10208      * @hide
10209      * @removed
10210      */
10211     @Deprecated
10212     @SystemApi
10213     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()10214     public boolean endCall() {
10215         return false;
10216     }
10217 
10218     /**
10219      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
10220      * @hide
10221      * @removed
10222      */
10223     @Deprecated
10224     @SystemApi
10225     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()10226     public void answerRingingCall() {
10227         // No-op
10228     }
10229 
10230     /**
10231      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
10232      * @hide
10233      */
10234     @Deprecated
10235     @SystemApi
10236     @SuppressLint("RequiresPermission")
silenceRinger()10237     public void silenceRinger() {
10238         // No-op
10239     }
10240 
10241     /**
10242      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
10243      * @hide
10244      */
10245     @Deprecated
10246     @SystemApi
10247     @RequiresPermission(anyOf = {
10248             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10249             android.Manifest.permission.READ_PHONE_STATE
10250     })
isOffhook()10251     public boolean isOffhook() {
10252         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
10253         return tm.isInCall();
10254     }
10255 
10256     /**
10257      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
10258      * @hide
10259      */
10260     @Deprecated
10261     @SystemApi
10262     @RequiresPermission(anyOf = {
10263             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10264             android.Manifest.permission.READ_PHONE_STATE
10265     })
isRinging()10266     public boolean isRinging() {
10267         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
10268         return tm.isRinging();
10269     }
10270 
10271     /**
10272      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
10273      * @hide
10274      */
10275     @Deprecated
10276     @SystemApi
10277     @RequiresPermission(anyOf = {
10278             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10279             android.Manifest.permission.READ_PHONE_STATE
10280     })
isIdle()10281     public boolean isIdle() {
10282         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
10283         return !tm.isInCall();
10284     }
10285 
10286     /**
10287      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
10288      * @hide
10289      */
10290     @Deprecated
10291     @SystemApi
10292     @RequiresPermission(anyOf = {
10293             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10294             android.Manifest.permission.READ_PHONE_STATE
10295     })
isRadioOn()10296     public boolean isRadioOn() {
10297         try {
10298             ITelephony telephony = getITelephony();
10299             if (telephony != null)
10300                 return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
10301         } catch (RemoteException e) {
10302             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
10303         }
10304         return false;
10305     }
10306 
10307     /** @hide */
10308     @SystemApi
10309     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10310     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyPin(String pin)10311     public boolean supplyPin(String pin) {
10312         try {
10313             ITelephony telephony = getITelephony();
10314             if (telephony != null)
10315                 return telephony.supplyPinForSubscriber(getSubId(), pin);
10316         } catch (RemoteException e) {
10317             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
10318         }
10319         return false;
10320     }
10321 
10322     /** @hide */
10323     @SystemApi
10324     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10325     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyPuk(String puk, String pin)10326     public boolean supplyPuk(String puk, String pin) {
10327         try {
10328             ITelephony telephony = getITelephony();
10329             if (telephony != null)
10330                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
10331         } catch (RemoteException e) {
10332             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
10333         }
10334         return false;
10335     }
10336 
10337     /**
10338      * @deprecated use {@link #supplyIccLockPin(String)} instead.
10339      * @hide
10340      */
10341     @SystemApi
10342     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10343     @Deprecated
supplyPinReportResult(String pin)10344     public int[] supplyPinReportResult(String pin) {
10345         try {
10346             ITelephony telephony = getITelephony();
10347             if (telephony != null)
10348                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
10349         } catch (RemoteException e) {
10350             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
10351         }
10352         return new int[0];
10353     }
10354 
10355     /**
10356      * @deprecated use {@link #supplyIccLockPuk(String, String)} instead.
10357      * @hide
10358      */
10359     @SystemApi
10360     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10361     @Deprecated
supplyPukReportResult(String puk, String pin)10362     public int[] supplyPukReportResult(String puk, String pin) {
10363         try {
10364             ITelephony telephony = getITelephony();
10365             if (telephony != null)
10366                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
10367         } catch (RemoteException e) {
10368             Log.e(TAG, "Error calling ITelephony#supplyPukReportResultForSubscriber", e);
10369         }
10370         return new int[0];
10371     }
10372 
10373     /**
10374      * Supplies a PIN to unlock the ICC and returns the corresponding {@link PinResult}.
10375      * Used when the user enters their ICC unlock PIN to attempt an unlock.
10376      *
10377      * @param pin The user entered PIN.
10378      * @return The result of the PIN.
10379      * @throws SecurityException if the caller doesn't have the permission.
10380      * @throws IllegalStateException if the Telephony process is not currently available.
10381      *
10382      * <p>Requires Permission:
10383      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10384      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10385      *
10386      * @hide
10387      */
10388     @SystemApi
10389     @NonNull
10390     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10391     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyIccLockPin(@onNull String pin)10392     public PinResult supplyIccLockPin(@NonNull String pin) {
10393         try {
10394             ITelephony telephony = getITelephony();
10395             if (telephony != null) {
10396                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
10397                 return new PinResult(result[0], result[1]);
10398             } else {
10399                 throw new IllegalStateException("telephony service is null.");
10400             }
10401         } catch (RemoteException e) {
10402             Log.e(TAG, "Error calling ITelephony#supplyIccLockPin", e);
10403             e.rethrowFromSystemServer();
10404         }
10405         return PinResult.getDefaultFailedResult();
10406     }
10407 
10408     /**
10409      * Supplies a PUK and PIN to unlock the ICC and returns the corresponding {@link PinResult}.
10410      * Used when the user enters their ICC unlock PUK and PIN to attempt an unlock.
10411      *
10412      * @param puk The product unlocking key.
10413      * @param pin The user entered PIN.
10414      * @return The result of the PUK and PIN.
10415      * @throws SecurityException if the caller doesn't have the permission.
10416      * @throws IllegalStateException if the Telephony process is not currently available.
10417      *
10418      * <p>Requires Permission:
10419      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10420      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10421      *
10422      * @hide
10423      */
10424     @SystemApi
10425     @NonNull
10426     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10427     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyIccLockPuk(@onNull String puk, @NonNull String pin)10428     public PinResult supplyIccLockPuk(@NonNull String puk, @NonNull String pin) {
10429         try {
10430             ITelephony telephony = getITelephony();
10431             if (telephony != null) {
10432                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
10433                 return new PinResult(result[0], result[1]);
10434             } else {
10435                 throw new IllegalStateException("telephony service is null.");
10436             }
10437         } catch (RemoteException e) {
10438             Log.e(TAG, "Error calling ITelephony#supplyIccLockPuk", e);
10439             e.rethrowFromSystemServer();
10440         }
10441         return PinResult.getDefaultFailedResult();
10442     }
10443 
10444     /**
10445      * Used to notify callers of
10446      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
10447      * network either successfully executes a USSD request, or if there was a failure while
10448      * executing the request.
10449      * <p>
10450      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
10451      * USSD request has succeeded.
10452      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
10453      * USSD request has failed.
10454      */
10455     public static abstract class UssdResponseCallback {
10456        /**
10457         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
10458         * response received from the network.  The calling app can choose to either display the
10459         * response to the user or perform some operation based on the response.
10460         * <p>
10461         * USSD responses are unstructured text and their content is determined by the mobile network
10462         * operator.
10463         *
10464         * @param telephonyManager the TelephonyManager the callback is registered to.
10465         * @param request the USSD request sent to the mobile network.
10466         * @param response the response to the USSD request provided by the mobile network.
10467         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)10468        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
10469                                          String request, CharSequence response) {};
10470 
10471        /**
10472         * Called when a USSD request has failed to complete.
10473         *
10474         * @param telephonyManager the TelephonyManager the callback is registered to.
10475         * @param request the USSD request sent to the mobile network.
10476         * @param failureCode failure code indicating why the request failed.  Will be either
10477         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
10478         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
10479         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)10480        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
10481                                                String request, int failureCode) {};
10482     }
10483 
10484     /**
10485      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
10486      * informs the caller of the response via the supplied {@code callback}.
10487      * <p>Carriers define USSD codes which can be sent by the user to request information such as
10488      * the user's current data balance or minutes balance.
10489      * <p>Requires permission:
10490      * {@link android.Manifest.permission#CALL_PHONE}
10491      * @param ussdRequest the USSD command to be executed.
10492      * @param callback called by the framework to inform the caller of the result of executing the
10493      *                 USSD request (see {@link UssdResponseCallback}).
10494      * @param handler the {@link Handler} to run the request on.
10495      */
10496     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
10497     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)10498     public void sendUssdRequest(String ussdRequest,
10499                                 final UssdResponseCallback callback, Handler handler) {
10500         checkNotNull(callback, "UssdResponseCallback cannot be null.");
10501         final TelephonyManager telephonyManager = this;
10502 
10503         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
10504             @Override
10505             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
10506                 Rlog.d(TAG, "USSD:" + resultCode);
10507                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
10508                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE, android.telephony.UssdResponse.class);
10509 
10510                 if (resultCode == USSD_RETURN_SUCCESS) {
10511                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
10512                             response.getReturnMessage());
10513                 } else {
10514                     callback.onReceiveUssdResponseFailed(telephonyManager,
10515                             response.getUssdRequest(), resultCode);
10516                 }
10517             }
10518         };
10519 
10520         try {
10521             ITelephony telephony = getITelephony();
10522             if (telephony != null) {
10523                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
10524             }
10525         } catch (RemoteException e) {
10526             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
10527             UssdResponse response = new UssdResponse(ussdRequest, "");
10528             Bundle returnData = new Bundle();
10529             returnData.putParcelable(USSD_RESPONSE, response);
10530             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
10531         }
10532     }
10533 
10534     /**
10535      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
10536      * voice and data simultaneously. This can change based on location or network condition.
10537      *
10538      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
10539      */
10540     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isConcurrentVoiceAndDataSupported()10541     public boolean isConcurrentVoiceAndDataSupported() {
10542         try {
10543             ITelephony telephony = getITelephony();
10544             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
10545                     getSubId()));
10546         } catch (RemoteException e) {
10547             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
10548         }
10549         return false;
10550     }
10551 
10552     /** @hide */
10553     @SystemApi
10554     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmi(String dialString)10555     public boolean handlePinMmi(String dialString) {
10556         try {
10557             ITelephony telephony = getITelephony();
10558             if (telephony != null)
10559                 return telephony.handlePinMmi(dialString);
10560         } catch (RemoteException e) {
10561             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
10562         }
10563         return false;
10564     }
10565 
10566     /** @hide */
10567     @SystemApi
10568     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmiForSubscriber(int subId, String dialString)10569     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
10570         try {
10571             ITelephony telephony = getITelephony();
10572             if (telephony != null)
10573                 return telephony.handlePinMmiForSubscriber(subId, dialString);
10574         } catch (RemoteException e) {
10575             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
10576         }
10577         return false;
10578     }
10579 
10580     /** @hide */
10581     @SystemApi
10582     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10583     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
toggleRadioOnOff()10584     public void toggleRadioOnOff() {
10585         try {
10586             ITelephony telephony = getITelephony();
10587             if (telephony != null)
10588                 telephony.toggleRadioOnOff();
10589         } catch (RemoteException e) {
10590             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
10591         }
10592     }
10593 
10594     /**
10595      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
10596      * {@link clearRadioPowerOffForReason}.
10597      *
10598      * @hide
10599      */
10600     @Deprecated
10601     @SystemApi
10602     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10603     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadio(boolean turnOn)10604     public boolean setRadio(boolean turnOn) {
10605         boolean result = true;
10606         try {
10607             if (turnOn) {
10608                 clearRadioPowerOffForReason(RADIO_POWER_REASON_USER);
10609             } else {
10610                 requestRadioPowerOffForReason(RADIO_POWER_REASON_USER);
10611             }
10612         } catch (Exception e) {
10613             String calledFunction =
10614                     turnOn ? "clearRadioPowerOffForReason" : "requestRadioPowerOffForReason";
10615             Log.e(TAG, "Error calling " + calledFunction, e);
10616             result = false;
10617         }
10618         return result;
10619     }
10620 
10621     /**
10622      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
10623      * {@link clearRadioPowerOffForReason}.
10624      *
10625      * @hide
10626      */
10627     @Deprecated
10628     @SystemApi
10629     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10630     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadioPower(boolean turnOn)10631     public boolean setRadioPower(boolean turnOn) {
10632         boolean result = true;
10633         try {
10634             if (turnOn) {
10635                 clearRadioPowerOffForReason(RADIO_POWER_REASON_USER);
10636             } else {
10637                 requestRadioPowerOffForReason(RADIO_POWER_REASON_USER);
10638             }
10639         } catch (Exception e) {
10640             String calledFunction =
10641                     turnOn ? "clearRadioPowerOffForReason" : "requestRadioPowerOffForReason";
10642             Log.e(TAG, "Error calling " + calledFunction, e);
10643             result = false;
10644         }
10645         return result;
10646     }
10647 
10648     /**
10649      * Vote on powering off the radio for a reason. The radio will be turned on only when there is
10650      * no reason to power it off. When any of the voters want to power it off, it will be turned
10651      * off. In case of emergency, the radio will be turned on even if there are some reasons for
10652      * powering it off, and these radio off votes will be cleared.
10653      * Multiple apps can vote for the same reason and the last vote will take effect. Each app is
10654      * responsible for its vote. A powering-off vote of a reason will be maintained until it is
10655      * cleared by calling {@link clearRadioPowerOffForReason} for that reason, or an emergency call
10656      * is made, or the device is rebooted. When an app comes backup from a crash, it needs to make
10657      * sure if its vote is as expected. An app can use the API {@link getRadioPowerOffReasons} to
10658      * check its vote.
10659      *
10660      * @param reason The reason for powering off radio.
10661      * @throws SecurityException if the caller does not have MODIFY_PHONE_STATE permission.
10662      * @throws IllegalStateException if the Telephony service is not currently available.
10663      *
10664      * @hide
10665      */
10666     @SystemApi
10667     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10668     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestRadioPowerOffForReason(@adioPowerReason int reason)10669     public void requestRadioPowerOffForReason(@RadioPowerReason int reason) {
10670         try {
10671             ITelephony telephony = getITelephony();
10672             if (telephony != null) {
10673                 if (!telephony.requestRadioPowerOffForReason(getSubId(), reason)) {
10674                     throw new IllegalStateException("Telephony service is not available.");
10675                 }
10676             } else {
10677                 throw new IllegalStateException("Telephony service is null.");
10678             }
10679         } catch (RemoteException e) {
10680             Log.e(TAG, "Error calling ITelephony#requestRadioPowerOffForReason", e);
10681             e.rethrowAsRuntimeException();
10682         }
10683     }
10684 
10685     /**
10686      * Remove the vote on powering off the radio for a reason, as requested by
10687      * {@link requestRadioPowerOffForReason}.
10688      *
10689      * @param reason The reason for powering off radio.
10690      * @throws SecurityException if the caller does not have MODIFY_PHONE_STATE permission.
10691      * @throws IllegalStateException if the Telephony service is not currently available.
10692      *
10693      * @hide
10694      */
10695     @SystemApi
10696     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10697     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
clearRadioPowerOffForReason(@adioPowerReason int reason)10698     public void clearRadioPowerOffForReason(@RadioPowerReason int reason) {
10699         try {
10700             ITelephony telephony = getITelephony();
10701             if (telephony != null) {
10702                 if (!telephony.clearRadioPowerOffForReason(getSubId(), reason)) {
10703                     throw new IllegalStateException("Telephony service is not available.");
10704                 }
10705             } else {
10706                 throw new IllegalStateException("Telephony service is null.");
10707             }
10708         } catch (RemoteException e) {
10709             Log.e(TAG, "Error calling ITelephony#clearRadioPowerOffForReason", e);
10710             e.rethrowAsRuntimeException();
10711         }
10712     }
10713 
10714     /**
10715      * Get reasons for powering off radio, as requested by {@link requestRadioPowerOffForReason}.
10716      * If the reason set is empty, the radio is on in all cases.
10717      *
10718      * @return Set of reasons for powering off radio.
10719      * @throws SecurityException if the caller does not have READ_PRIVILEGED_PHONE_STATE permission.
10720      * @throws IllegalStateException if the Telephony service is not currently available.
10721      *
10722      * @hide
10723      */
10724     @SystemApi
10725     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10726     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
10727     @NonNull
getRadioPowerOffReasons()10728     public Set<Integer> getRadioPowerOffReasons() {
10729         Set<Integer> result = new HashSet<>();
10730         try {
10731             ITelephony telephony = getITelephony();
10732             if (telephony != null) {
10733                 result.addAll(telephony.getRadioPowerOffReasons(getSubId(),
10734                         mContext.getOpPackageName(), mContext.getAttributionTag()));
10735             } else {
10736                 throw new IllegalStateException("Telephony service is null.");
10737             }
10738         } catch (RemoteException e) {
10739             Log.e(TAG, "Error calling ITelephony#getRadioPowerOffReasons", e);
10740             e.rethrowAsRuntimeException();
10741         }
10742         return result;
10743     }
10744 
10745     /**
10746      * Shut down all the live radios over all the slot indexes.
10747      *
10748      * <p>To know when the radio has completed powering off, use
10749      * {@link PhoneStateListener#LISTEN_SERVICE_STATE LISTEN_SERVICE_STATE}.
10750      *
10751      * @hide
10752      */
10753     @SystemApi
10754     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10755     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
shutdownAllRadios()10756     public void shutdownAllRadios() {
10757         try {
10758             ITelephony telephony = getITelephony();
10759             if (telephony != null) {
10760                 telephony.shutdownMobileRadios();
10761             }
10762         } catch (RemoteException e) {
10763             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
10764             e.rethrowAsRuntimeException();
10765         }
10766     }
10767 
10768     /**
10769      * Check if any radio is on over all the slot indexes.
10770      *
10771      * @return {@code true} if any radio is on over any slot index.
10772      * @hide
10773      */
10774     @SystemApi
10775     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10776     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isAnyRadioPoweredOn()10777     public boolean isAnyRadioPoweredOn() {
10778         try {
10779             ITelephony telephony = getITelephony();
10780             if (telephony != null) {
10781                 return telephony.needMobileRadioShutdown();
10782             }
10783         } catch (RemoteException e) {
10784             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
10785             e.rethrowAsRuntimeException();
10786         }
10787         return false;
10788     }
10789 
10790     /**
10791      * Radio explicitly powered off (e.g, airplane mode).
10792      * @hide
10793      */
10794     @SystemApi
10795     public static final int RADIO_POWER_OFF = 0;
10796 
10797     /**
10798      * Radio power is on.
10799      * @hide
10800      */
10801     @SystemApi
10802     public static final int RADIO_POWER_ON = 1;
10803 
10804     /**
10805      * Radio power unavailable (eg, modem resetting or not booted).
10806      * @hide
10807      */
10808     @SystemApi
10809     public static final int RADIO_POWER_UNAVAILABLE = 2;
10810 
10811     /**
10812      * @return current modem radio state.
10813      *
10814      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
10815      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
10816      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10817      *
10818      * @hide
10819      */
10820     @SystemApi
10821     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10822             android.Manifest.permission.READ_PHONE_STATE})
10823     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getRadioPowerState()10824     public @RadioPowerState int getRadioPowerState() {
10825         try {
10826             ITelephony telephony = getITelephony();
10827             if (telephony != null) {
10828                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
10829                         mContext.getAttributionTag());
10830             }
10831         } catch (RemoteException ex) {
10832             // This could happen if binder process crashes.
10833         }
10834         return RADIO_POWER_UNAVAILABLE;
10835     }
10836 
10837     /**
10838      * This method should not be used due to privacy and stability concerns.
10839      *
10840      * @hide
10841      */
10842     @SystemApi
updateServiceLocation()10843     public void updateServiceLocation() {
10844         Log.e(TAG, "Do not call TelephonyManager#updateServiceLocation()");
10845     }
10846 
10847     /** @hide */
10848     @SystemApi
10849     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10850     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
enableDataConnectivity()10851     public boolean enableDataConnectivity() {
10852         try {
10853             ITelephony telephony = getITelephony();
10854             if (telephony != null)
10855                 return telephony.enableDataConnectivity(getOpPackageName());
10856         } catch (RemoteException e) {
10857             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
10858         }
10859         return false;
10860     }
10861 
10862     /** @hide */
10863     @SystemApi
10864     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10865     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
disableDataConnectivity()10866     public boolean disableDataConnectivity() {
10867         try {
10868             ITelephony telephony = getITelephony();
10869             if (telephony != null)
10870                 return telephony.disableDataConnectivity(getOpPackageName());
10871         } catch (RemoteException e) {
10872             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
10873         }
10874         return false;
10875     }
10876 
10877     /** @hide */
10878     @SystemApi
10879     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataConnectivityPossible()10880     public boolean isDataConnectivityPossible() {
10881         try {
10882             ITelephony telephony = getITelephony();
10883             if (telephony != null)
10884                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
10885                         .getActiveDataSubscriptionId()));
10886         } catch (RemoteException e) {
10887             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
10888         }
10889         return false;
10890     }
10891 
10892     /** @hide */
10893     @SystemApi
10894     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
needsOtaServiceProvisioning()10895     public boolean needsOtaServiceProvisioning() {
10896         try {
10897             ITelephony telephony = getITelephony();
10898             if (telephony != null)
10899                 return telephony.needsOtaServiceProvisioning();
10900         } catch (RemoteException e) {
10901             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
10902         }
10903         return false;
10904     }
10905 
10906     /**
10907      * Get the mobile provisioning url that is used to launch a browser to allow users to manage
10908      * their mobile plan.
10909      *
10910      * <p>Requires Permission:
10911      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}.
10912      *
10913      * TODO: The legacy design only supports single sim design. Ideally, this should support
10914      * multi-sim design in current world.
10915      *
10916      * {@hide}
10917      */
10918     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMobileProvisioningUrl()10919     public @Nullable String getMobileProvisioningUrl() {
10920         try {
10921             final ITelephony service = getITelephony();
10922             if (service != null) {
10923                 return service.getMobileProvisioningUrl();
10924             } else {
10925                 throw new IllegalStateException("telephony service is null.");
10926             }
10927         } catch (RemoteException ex) {
10928             Rlog.e(TAG, "Telephony#getMobileProvisioningUrl RemoteException" + ex);
10929         }
10930         return null;
10931     }
10932 
10933     /**
10934      * Turns mobile data on or off.
10935      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
10936      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10937      *
10938      * <p>Requires Permission:
10939      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10940      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10941      *
10942      * @param enable Whether to enable mobile data.
10943      * @deprecated use setDataEnabledForReason with reason DATA_ENABLED_REASON_USER instead.
10944      *
10945      */
10946     @Deprecated
10947     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
10948     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(boolean enable)10949     public void setDataEnabled(boolean enable) {
10950         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
10951     }
10952 
10953     /**
10954      * @hide
10955      * @deprecated use {@link #setDataEnabledForReason(int, boolean)} instead.
10956     */
10957     @SystemApi
10958     @Deprecated
10959     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(int subId, boolean enable)10960     public void setDataEnabled(int subId, boolean enable) {
10961         try {
10962             setDataEnabledForReason(subId, DATA_ENABLED_REASON_USER, enable);
10963         } catch (RuntimeException e) {
10964             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
10965         }
10966     }
10967 
10968     /**
10969      * @deprecated use {@link #isDataEnabled()} instead.
10970      * @hide
10971      */
10972     @SystemApi
10973     @Deprecated
getDataEnabled()10974     public boolean getDataEnabled() {
10975         return isDataEnabled();
10976     }
10977 
10978     /**
10979      * Returns whether mobile data is enabled or not per user setting. There are other factors
10980      * that could disable mobile data, but they are not considered here.
10981      *
10982      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
10983      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10984      *
10985      * <p>Requires one of the following permissions:
10986      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
10987      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or
10988      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
10989      * READ_BASIC_PHONE_STATE} or that the calling app has carrier
10990      * privileges (see {@link #hasCarrierPrivileges}).
10991      *
10992      * <p>Note that this does not take into account any data restrictions that may be present on the
10993      * calling app. Such restrictions may be inspected with
10994      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
10995      *
10996      * @return true if mobile data is enabled.
10997      */
10998     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
10999             android.Manifest.permission.MODIFY_PHONE_STATE,
11000             android.Manifest.permission.READ_PHONE_STATE,
11001             android.Manifest.permission.READ_BASIC_PHONE_STATE})
11002     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabled()11003     public boolean isDataEnabled() {
11004         try {
11005             return isDataEnabledForReason(DATA_ENABLED_REASON_USER);
11006         } catch (IllegalStateException ise) {
11007             // TODO(b/176163590): Remove this catch once TelephonyManager is booting safely.
11008             Log.e(TAG, "Error calling #isDataEnabled, returning default (false).", ise);
11009             return false;
11010         }
11011     }
11012 
11013     /**
11014      * Returns whether mobile data roaming is enabled on the subscription.
11015      *
11016      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11017      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11018      *
11019      * <p>Requires one of the following permissions:
11020      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
11021      * {@link android.Manifest.permission#READ_PHONE_STATE} or
11022      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
11023      * READ_BASIC_PHONE_STATE} or that the calling app
11024      * has carrier privileges (see {@link #hasCarrierPrivileges}).
11025      *
11026      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
11027      * {@code false}.
11028      */
11029     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
11030             android.Manifest.permission.READ_PHONE_STATE,
11031             android.Manifest.permission.READ_BASIC_PHONE_STATE})
11032     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataRoamingEnabled()11033     public boolean isDataRoamingEnabled() {
11034         boolean isDataRoamingEnabled = false;
11035         try {
11036             ITelephony telephony = getITelephony();
11037             if (telephony != null) {
11038                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
11039                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
11040             }
11041         } catch (RemoteException e) {
11042             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
11043         }
11044         return isDataRoamingEnabled;
11045     }
11046 
11047     /**
11048      * Gets the roaming mode for CDMA phone.
11049      *
11050      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11051      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11052      *
11053      * @return the CDMA roaming mode.
11054      * @throws SecurityException if the caller does not have the permission.
11055      * @throws IllegalStateException if the Telephony process is not currently available.
11056      *
11057      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
11058      * @see #CDMA_ROAMING_MODE_HOME
11059      * @see #CDMA_ROAMING_MODE_AFFILIATED
11060      * @see #CDMA_ROAMING_MODE_ANY
11061      *
11062      * <p>Requires permission:
11063      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11064      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11065      *
11066      * @hide
11067      */
11068     @SystemApi
11069     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11070     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaRoamingMode()11071     public @CdmaRoamingMode int getCdmaRoamingMode() {
11072         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
11073         try {
11074             ITelephony telephony = getITelephony();
11075             if (telephony != null) {
11076                 mode = telephony.getCdmaRoamingMode(getSubId());
11077             } else {
11078                 throw new IllegalStateException("telephony service is null.");
11079             }
11080         } catch (RemoteException ex) {
11081             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
11082             ex.rethrowFromSystemServer();
11083         }
11084         return mode;
11085     }
11086 
11087     /**
11088      * Sets the roaming mode for CDMA phone to the given mode {@code mode}. If the phone is not
11089      * CDMA capable, this method throws an IllegalStateException.
11090      *
11091      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11092      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11093      *
11094      * @param mode CDMA roaming mode.
11095      * @throws SecurityException if the caller does not have the permission.
11096      * @throws IllegalStateException if the Telephony process or radio is not currently available,
11097      *         the device is not CDMA capable, or the request fails.
11098      *
11099      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
11100      * @see #CDMA_ROAMING_MODE_HOME
11101      * @see #CDMA_ROAMING_MODE_AFFILIATED
11102      * @see #CDMA_ROAMING_MODE_ANY
11103      *
11104      * <p>Requires Permission:
11105      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11106      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11107      *
11108      * @hide
11109      */
11110     @SystemApi
11111     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11112     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
setCdmaRoamingMode(@dmaRoamingMode int mode)11113     public void setCdmaRoamingMode(@CdmaRoamingMode int mode) {
11114         if (getPhoneType() != PHONE_TYPE_CDMA) {
11115             throw new IllegalStateException("Phone does not support CDMA.");
11116         }
11117         try {
11118             ITelephony telephony = getITelephony();
11119             if (telephony != null) {
11120                 boolean result = telephony.setCdmaRoamingMode(getSubId(), mode);
11121                 if (!result) throw new IllegalStateException("radio is unavailable.");
11122             } else {
11123                 throw new IllegalStateException("telephony service is null.");
11124             }
11125         } catch (RemoteException ex) {
11126             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
11127             ex.rethrowFromSystemServer();
11128         }
11129     }
11130 
11131     /** @hide */
11132     @IntDef(prefix = { "CDMA_SUBSCRIPTION_" }, value = {
11133             CDMA_SUBSCRIPTION_UNKNOWN,
11134             CDMA_SUBSCRIPTION_RUIM_SIM,
11135             CDMA_SUBSCRIPTION_NV
11136     })
11137     @Retention(RetentionPolicy.SOURCE)
11138     public @interface CdmaSubscription{}
11139 
11140     /**
11141      * Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
11142      * @hide
11143      */
11144     @SystemApi
11145     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
11146 
11147     /**
11148      * Used for CDMA subscription mode: RUIM/SIM (default)
11149      * @hide
11150      */
11151     @SystemApi
11152     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
11153 
11154     /**
11155      * Used for CDMA subscription mode: NV -> non-volatile memory
11156      * @hide
11157      */
11158     @SystemApi
11159     public static final int CDMA_SUBSCRIPTION_NV       = 1;
11160 
11161     /**
11162      * Gets the subscription mode for CDMA phone.
11163      *
11164      * @return the CDMA subscription mode.
11165      * @throws SecurityException if the caller does not have the permission.
11166      * @throws IllegalStateException if the Telephony process or radio is not currently available.
11167      *
11168      * @see #CDMA_SUBSCRIPTION_UNKNOWN
11169      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
11170      * @see #CDMA_SUBSCRIPTION_NV
11171      *
11172      * <p>Requires Permission:
11173      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11174      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11175      *
11176      * @hide
11177      */
11178     @SystemApi
11179     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11180     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaSubscriptionMode()11181     public @CdmaSubscription int getCdmaSubscriptionMode() {
11182         int mode = CDMA_SUBSCRIPTION_RUIM_SIM;
11183         try {
11184             ITelephony telephony = getITelephony();
11185             if (telephony != null) {
11186                 mode = telephony.getCdmaSubscriptionMode(getSubId());
11187             } else {
11188                 throw new IllegalStateException("telephony service is null.");
11189             }
11190         } catch (RemoteException ex) {
11191             Log.e(TAG, "Error calling ITelephony#getCdmaSubscriptionMode", ex);
11192             ex.rethrowFromSystemServer();
11193         }
11194         return mode;
11195     }
11196 
11197     /**
11198      * Sets the subscription mode for CDMA phone to the given mode {@code mode}. If the phone is not
11199      * CDMA capable, this method throws an IllegalStateException.
11200      *
11201      * @param mode CDMA subscription mode.
11202      * @throws SecurityException if the caller does not have the permission.
11203      * @throws IllegalStateException if the Telephony process or radio is not currently available,
11204      *         the device is not CDMA capable, or the request fails.
11205      *
11206      * @see #CDMA_SUBSCRIPTION_UNKNOWN
11207      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
11208      * @see #CDMA_SUBSCRIPTION_NV
11209      *
11210      * <p>Requires Permission:
11211      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11212      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11213      *
11214      * @hide
11215      */
11216     @SystemApi
11217     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11218     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
setCdmaSubscriptionMode(@dmaSubscription int mode)11219     public void setCdmaSubscriptionMode(@CdmaSubscription int mode) {
11220         if (getPhoneType() != PHONE_TYPE_CDMA) {
11221             throw new IllegalStateException("Phone does not support CDMA.");
11222         }
11223         try {
11224             ITelephony telephony = getITelephony();
11225             if (telephony != null) {
11226                 boolean result = telephony.setCdmaSubscriptionMode(getSubId(), mode);
11227                 if (!result) throw new IllegalStateException("radio is unavailable.");
11228             } else {
11229                 throw new IllegalStateException("telephony service is null.");
11230             }
11231         } catch (RemoteException ex) {
11232             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
11233             ex.rethrowFromSystemServer();
11234         }
11235     }
11236 
11237     /**
11238      * Enables/Disables the data roaming on the subscription.
11239      *
11240      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11241      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11242      *
11243      * <p> Requires permission:
11244      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
11245      * privileges (see {@link #hasCarrierPrivileges}).
11246      *
11247      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
11248      *
11249      * @hide
11250      */
11251     @SystemApi
11252     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11253     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataRoamingEnabled(boolean isEnabled)11254     public void setDataRoamingEnabled(boolean isEnabled) {
11255         try {
11256             ITelephony telephony = getITelephony();
11257             if (telephony != null) {
11258                 telephony.setDataRoamingEnabled(
11259                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
11260             }
11261         } catch (RemoteException e) {
11262             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
11263         }
11264     }
11265 
11266     /**
11267      * @deprecated use {@link #isDataEnabled()} instead.
11268      * @hide
11269      */
11270     @Deprecated
11271     @SystemApi
getDataEnabled(int subId)11272     public boolean getDataEnabled(int subId) {
11273         try {
11274             return isDataEnabledForReason(subId, DATA_ENABLED_REASON_USER);
11275         } catch (RuntimeException e) {
11276             Log.e(TAG, "Error calling isDataEnabledForReason e:" + e);
11277         }
11278         return false;
11279     }
11280 
11281     /**
11282      * Returns the result and response from RIL for oem request
11283      *
11284      * @param oemReq the data is sent to ril.
11285      * @param oemResp the respose data from RIL.
11286      * @return negative value request was not handled or get error
11287      *         0 request was handled succesfully, but no response data
11288      *         positive value success, data length of response
11289      * @hide
11290      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
11291      */
11292     @Deprecated
invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp)11293     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
11294         try {
11295             ITelephony telephony = getITelephony();
11296             if (telephony != null)
11297                 return telephony.invokeOemRilRequestRaw(oemReq, oemResp);
11298         } catch (RemoteException ex) {
11299         } catch (NullPointerException ex) {
11300         }
11301         return -1;
11302     }
11303 
11304     /**
11305      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
11306      * instead.
11307      * @hide
11308      */
11309     @Deprecated
11310     @SystemApi
11311     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableVideoCalling(boolean enable)11312     public void enableVideoCalling(boolean enable) {
11313         try {
11314             ITelephony telephony = getITelephony();
11315             if (telephony != null)
11316                 telephony.enableVideoCalling(enable);
11317         } catch (RemoteException e) {
11318             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
11319         }
11320     }
11321 
11322     /**
11323      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
11324      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
11325      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
11326      * determine if video calling is capable.
11327      * @hide
11328      */
11329     @Deprecated
11330     @SystemApi
11331     @RequiresPermission(anyOf = {
11332             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11333             android.Manifest.permission.READ_PHONE_STATE
11334     })
isVideoCallingEnabled()11335     public boolean isVideoCallingEnabled() {
11336         try {
11337             ITelephony telephony = getITelephony();
11338             if (telephony != null)
11339                 return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
11340         } catch (RemoteException e) {
11341             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
11342         }
11343         return false;
11344     }
11345 
11346     /**
11347      * Whether the device supports configuring the DTMF tone length.
11348      *
11349      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
11350      */
11351     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
canChangeDtmfToneLength()11352     public boolean canChangeDtmfToneLength() {
11353         try {
11354             ITelephony telephony = getITelephony();
11355             if (telephony != null) {
11356                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
11357                         getAttributionTag());
11358             }
11359         } catch (RemoteException e) {
11360             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
11361         } catch (SecurityException e) {
11362             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
11363         }
11364         return false;
11365     }
11366 
11367     /**
11368      * Whether the device is a world phone.
11369      *
11370      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
11371      */
isWorldPhone()11372     public boolean isWorldPhone() {
11373         try {
11374             ITelephony telephony = getITelephony();
11375             if (telephony != null) {
11376                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
11377             }
11378         } catch (RemoteException e) {
11379             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
11380         } catch (SecurityException e) {
11381             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
11382         }
11383         return false;
11384     }
11385 
11386     /**
11387      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
11388      * Whether the phone supports TTY mode.
11389      *
11390      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
11391      *
11392      */
11393     @Deprecated
isTtyModeSupported()11394     public boolean isTtyModeSupported() {
11395         try {
11396             TelecomManager telecomManager = null;
11397             if (mContext != null) {
11398                 telecomManager = mContext.getSystemService(TelecomManager.class);
11399             }
11400             if (telecomManager != null) {
11401                 return telecomManager.isTtySupported();
11402             }
11403         } catch (SecurityException e) {
11404             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
11405         }
11406         return false;
11407     }
11408 
11409     /**
11410      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
11411      * support for the feature and device firmware support.
11412      *
11413      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
11414      */
11415     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
isRttSupported()11416     public boolean isRttSupported() {
11417         try {
11418             ITelephony telephony = getITelephony();
11419             if (telephony != null) {
11420                 return telephony.isRttSupported(mSubId);
11421             }
11422         } catch (RemoteException e) {
11423             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
11424         } catch (SecurityException e) {
11425             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
11426         }
11427         return false;
11428     }
11429     /**
11430      * Whether the phone supports hearing aid compatibility.
11431      *
11432      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
11433      * otherwise.
11434      */
11435     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isHearingAidCompatibilitySupported()11436     public boolean isHearingAidCompatibilitySupported() {
11437         try {
11438             ITelephony telephony = getITelephony();
11439             if (telephony != null) {
11440                 return telephony.isHearingAidCompatibilitySupported();
11441             }
11442         } catch (RemoteException e) {
11443             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
11444         } catch (SecurityException e) {
11445             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
11446         }
11447         return false;
11448     }
11449 
11450     /**
11451      * Returns the IMS Registration Status for a particular Subscription ID.
11452      *
11453      * @param subId Subscription ID
11454      * @return true if IMS status is registered, false if the IMS status is not registered or a
11455      * RemoteException occurred.
11456      * Use {@link ImsMmTelManager.RegistrationCallback} instead.
11457      * @hide
11458      */
isImsRegistered(int subId)11459     public boolean isImsRegistered(int subId) {
11460         try {
11461             return getITelephony().isImsRegistered(subId);
11462         } catch (RemoteException | NullPointerException ex) {
11463             return false;
11464         }
11465     }
11466 
11467     /**
11468      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
11469      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
11470      * invalid subscription ID is used during creation, will the default subscription ID will be
11471      * used.
11472      *
11473      * @return true if IMS status is registered, false if the IMS status is not registered or a
11474      * RemoteException occurred.
11475      * @see SubscriptionManager#getDefaultSubscriptionId()
11476      * @hide
11477      */
11478     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()11479     public boolean isImsRegistered() {
11480        try {
11481            return getITelephony().isImsRegistered(getSubId());
11482        } catch (RemoteException | NullPointerException ex) {
11483            return false;
11484        }
11485     }
11486 
11487     /**
11488      * The current status of Voice over LTE for the subscription associated with this instance when
11489      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
11490      * used during creation, the default subscription ID will be used.
11491      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
11492      * @see SubscriptionManager#getDefaultSubscriptionId()
11493      * <p>
11494      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
11495      * @hide
11496      */
11497     @UnsupportedAppUsage
isVolteAvailable()11498     public boolean isVolteAvailable() {
11499         try {
11500             return getITelephony().isAvailable(getSubId(),
11501                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
11502                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
11503         } catch (RemoteException | NullPointerException ex) {
11504             return false;
11505         }
11506     }
11507 
11508     /**
11509      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
11510      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
11511      * used during creation, the default subscription ID will be used. To query the
11512      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
11513      * @return true if VT is available, or false if it is unavailable or unknown.
11514      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
11515      * @hide
11516      */
11517     @UnsupportedAppUsage
isVideoTelephonyAvailable()11518     public boolean isVideoTelephonyAvailable() {
11519         try {
11520             return getITelephony().isVideoTelephonyAvailable(getSubId());
11521         } catch (RemoteException | NullPointerException ex) {
11522             return false;
11523         }
11524     }
11525 
11526     /**
11527      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
11528      * @param subId the subscription ID.
11529      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
11530      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
11531      * @hide
11532      */
11533     @UnsupportedAppUsage
isWifiCallingAvailable()11534     public boolean isWifiCallingAvailable() {
11535        try {
11536            return getITelephony().isWifiCallingAvailable(getSubId());
11537        } catch (RemoteException | NullPointerException ex) {
11538            return false;
11539        }
11540    }
11541 
11542     /**
11543      * The technology that IMS is registered for for the MMTEL feature.
11544      * @param subId subscription ID to get IMS registration technology for.
11545      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
11546      * Valid return results are:
11547      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
11548      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
11549      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_CROSS_SIM} for registration over
11550      *  other sim's internet, or
11551      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
11552      *  result is unavailable.
11553      *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
11554      *  @hide
11555      */
getImsRegTechnologyForMmTel()11556     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
11557         try {
11558             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
11559         } catch (RemoteException ex) {
11560             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
11561         }
11562     }
11563 
11564    /**
11565     * Set TelephonyProperties.icc_operator_numeric for the default phone.
11566     *
11567     * @hide
11568     */
setSimOperatorNumeric(String numeric)11569     public void setSimOperatorNumeric(String numeric) {
11570         int phoneId = getPhoneId();
11571         setSimOperatorNumericForPhone(phoneId, numeric);
11572     }
11573 
11574    /**
11575     * Set TelephonyProperties.icc_operator_numeric for the given phone.
11576     *
11577     * @hide
11578     */
11579     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setSimOperatorNumericForPhone(int phoneId, String numeric)11580     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
11581         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11582             List<String> newList = updateTelephonyProperty(
11583                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
11584             TelephonyProperties.icc_operator_numeric(newList);
11585         }
11586     }
11587 
11588     /**
11589      * Set TelephonyProperties.icc_operator_alpha for the default phone.
11590      *
11591      * @hide
11592      */
setSimOperatorName(String name)11593     public void setSimOperatorName(String name) {
11594         int phoneId = getPhoneId();
11595         setSimOperatorNameForPhone(phoneId, name);
11596     }
11597 
11598     /**
11599      * Set TelephonyProperties.icc_operator_alpha for the given phone.
11600      *
11601      * @hide
11602      */
11603     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)11604     public void setSimOperatorNameForPhone(int phoneId, String name) {
11605         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11606             List<String> newList = updateTelephonyProperty(
11607                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
11608             TelephonyProperties.icc_operator_alpha(newList);
11609         }
11610     }
11611 
11612    /**
11613     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
11614     *
11615     * @hide
11616     */
setSimCountryIso(String iso)11617     public void setSimCountryIso(String iso) {
11618         int phoneId = getPhoneId();
11619         setSimCountryIsoForPhone(phoneId, iso);
11620     }
11621 
11622    /**
11623     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
11624     *
11625     * @hide
11626     */
11627     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)11628     public void setSimCountryIsoForPhone(int phoneId, String iso) {
11629         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11630             List<String> newList = updateTelephonyProperty(
11631                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
11632             TelephonyProperties.icc_operator_iso_country(newList);
11633         }
11634     }
11635 
11636     /**
11637      * Set TelephonyProperties.sim_state for the default phone.
11638      *
11639      * @hide
11640      */
setSimState(String state)11641     public void setSimState(String state) {
11642         int phoneId = getPhoneId();
11643         setSimStateForPhone(phoneId, state);
11644     }
11645 
11646     /**
11647      * Set TelephonyProperties.sim_state for the given phone.
11648      *
11649      * @hide
11650      */
11651     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)11652     public void setSimStateForPhone(int phoneId, String state) {
11653         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11654             List<String> newList = updateTelephonyProperty(
11655                     TelephonyProperties.sim_state(), phoneId, state);
11656             TelephonyProperties.sim_state(newList);
11657         }
11658     }
11659 
11660     /**
11661      * Powers down the SIM. SIM must be up prior.
11662      * @hide
11663      */
11664     public static final int CARD_POWER_DOWN = 0;
11665 
11666     /**
11667      * Powers up the SIM normally. SIM must be down prior.
11668      * @hide
11669      */
11670     public static final int CARD_POWER_UP = 1;
11671 
11672     /**
11673      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
11674      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
11675      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
11676      * and the SIM card is controlled completely by Telephony sending APDUs
11677      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
11678      * number of card apps will be 0.
11679      * No new error code is generated. Emergency calls are supported in the
11680      * same way as if the SIM card is absent.
11681      * The PASS_THROUGH mode is valid only for the specific card session where it
11682      * is activated, and normal behavior occurs at the next SIM initialization,
11683      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
11684      * is NOT persistent across boots. On reboot, SIM will power up normally.
11685      * @hide
11686      */
11687     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
11688 
11689     /** @hide */
11690     @Retention(RetentionPolicy.SOURCE)
11691     @IntDef(prefix = {"CARD_POWER"},
11692             value = {
11693                     CARD_POWER_DOWN,
11694                     CARD_POWER_UP,
11695                     CARD_POWER_UP_PASS_THROUGH,
11696             })
11697     public @interface SimPowerState {}
11698 
11699     /**
11700      * Set SIM card power state.
11701      *
11702      * @param state  State of SIM (power down, power up, pass through)
11703      * @see #CARD_POWER_DOWN
11704      * @see #CARD_POWER_UP
11705      * @see #CARD_POWER_UP_PASS_THROUGH
11706      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
11707      * broadcasts to determine success or failure and timeout if needed.
11708      *
11709      * @deprecated prefer {@link setSimPowerState(int, Executor, Consumer<Integer>)}.
11710      * There is no guarantee that SIM power changes will trigger ACTION_SIM_STATE_CHANGED on new
11711      * devices.
11712      *
11713      * <p>Requires Permission:
11714      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11715      *
11716      * {@hide}
11717      **/
11718     @SystemApi
11719     @Deprecated
11720     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerState(int state)11721     public void setSimPowerState(int state) {
11722         setSimPowerStateForSlot(getSlotIndex(), state);
11723     }
11724 
11725     /**
11726      * Set SIM card power state.
11727      *
11728      * @param slotIndex SIM slot id
11729      * @param state  State of SIM (power down, power up, pass through)
11730      * @see #CARD_POWER_DOWN
11731      * @see #CARD_POWER_UP
11732      * @see #CARD_POWER_UP_PASS_THROUGH
11733      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
11734      * broadcasts to determine success or failure and timeout if needed.
11735      *
11736      * @deprecated prefer {@link setSimPowerStateForSlot(int, int, Executor, Consumer<Integer>)}.
11737      * changes will trigger ACTION_SIM_STATE_CHANGED on new devices.
11738      *
11739      * <p>Requires Permission:
11740      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11741      *
11742      * {@hide}
11743      **/
11744     @SystemApi
11745     @Deprecated
11746     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerStateForSlot(int slotIndex, int state)11747     public void setSimPowerStateForSlot(int slotIndex, int state) {
11748         try {
11749             ITelephony telephony = getITelephony();
11750             if (telephony != null) {
11751                 telephony.setSimPowerStateForSlot(slotIndex, state);
11752             }
11753         } catch (RemoteException e) {
11754             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
11755         } catch (SecurityException e) {
11756             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
11757         }
11758     }
11759 
11760     /**
11761      * Set SIM card power state.
11762      *
11763      * @param state  State of SIM (power down, power up, pass through)
11764      * @see #CARD_POWER_DOWN
11765      * @see #CARD_POWER_UP
11766      * @see #CARD_POWER_UP_PASS_THROUGH
11767      * @param executor The executor of where the callback will execute.
11768      * @param callback Callback will be triggered once it succeeds or failed.
11769      * @see #SET_SIM_POWER_STATE_SUCCESS
11770      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
11771      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
11772      * @see #SET_SIM_POWER_STATE_SIM_ERROR
11773      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
11774      * @throws IllegalArgumentException if requested SIM state is invalid
11775      *
11776      * <p>Requires Permission:
11777      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11778      *
11779      * {@hide}
11780      **/
11781     @SystemApi
11782     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11783     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerState(@imPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)11784     public void setSimPowerState(@SimPowerState int state, @NonNull Executor executor,
11785             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
11786         setSimPowerStateForSlot(getSlotIndex(), state, executor, callback);
11787     }
11788 
11789     /**
11790      * Set SIM card power state.
11791      *
11792      * @param slotIndex SIM slot id
11793      * @param state  State of SIM (power down, power up, pass through)
11794      * @see #CARD_POWER_DOWN
11795      * @see #CARD_POWER_UP
11796      * @see #CARD_POWER_UP_PASS_THROUGH
11797      * @param executor The executor of where the callback will execute.
11798      * @param callback Callback will be triggered once it succeeds or failed.
11799      * @see #SET_SIM_POWER_STATE_SUCCESS
11800      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
11801      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
11802      * @see #SET_SIM_POWER_STATE_SIM_ERROR
11803      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
11804      * @throws IllegalArgumentException if requested SIM state is invalid
11805      *
11806      * <p>Requires Permission:
11807      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11808      *
11809      * {@hide}
11810      **/
11811     @SystemApi
11812     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11813     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerStateForSlot(int slotIndex, @SimPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)11814     public void setSimPowerStateForSlot(int slotIndex, @SimPowerState int state,
11815             @NonNull Executor executor,
11816             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
11817         if (state != CARD_POWER_DOWN && state != CARD_POWER_UP
11818                 && state != CARD_POWER_UP_PASS_THROUGH) {
11819             throw new IllegalArgumentException("requested SIM state is invalid");
11820         }
11821         try {
11822             ITelephony telephony = getITelephony();
11823             if (telephony == null) throw new IllegalStateException("Telephony is null.");
11824 
11825             IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
11826                 @Override
11827                 public void accept(int result) {
11828                     executor.execute(() ->
11829                             Binder.withCleanCallingIdentity(() -> callback.accept(result)));
11830                 }
11831             };
11832             if (telephony == null) {
11833                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
11834                     throw new IllegalStateException("Telephony is null");
11835                 } else {
11836                     return;
11837                 }
11838             }
11839             telephony.setSimPowerStateForSlotWithCallback(slotIndex, state, internalCallback);
11840         } catch (RemoteException e) {
11841             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
11842             runOnBackgroundThread(() -> executor.execute(
11843                     () -> callback.accept(SET_SIM_POWER_STATE_MODEM_ERROR)));
11844         } catch (SecurityException e) {
11845             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot",
11846                     e);
11847         }
11848     }
11849 
11850     /**
11851      * Set baseband version for the default phone.
11852      *
11853      * @param version baseband version
11854      * @hide
11855      */
setBasebandVersion(String version)11856     public void setBasebandVersion(String version) {
11857         int phoneId = getPhoneId();
11858         setBasebandVersionForPhone(phoneId, version);
11859     }
11860 
11861     /**
11862      * Set baseband version by phone id.
11863      *
11864      * @param phoneId for which baseband version is set
11865      * @param version baseband version
11866      * @hide
11867      */
11868     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)11869     public void setBasebandVersionForPhone(int phoneId, String version) {
11870         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11871             List<String> newList = updateTelephonyProperty(
11872                     TelephonyProperties.baseband_version(), phoneId, version);
11873             TelephonyProperties.baseband_version(newList);
11874         }
11875     }
11876 
11877     /**
11878      * Get baseband version for the default phone.
11879      *
11880      * @return baseband version.
11881      * @hide
11882      */
getBasebandVersion()11883     public String getBasebandVersion() {
11884         int phoneId = getPhoneId();
11885         return getBasebandVersionForPhone(phoneId);
11886     }
11887 
11888     /**
11889      * Get baseband version by phone id.
11890      *
11891      * @return baseband version.
11892      * @hide
11893      */
getBasebandVersionForPhone(int phoneId)11894     public String getBasebandVersionForPhone(int phoneId) {
11895         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
11896     }
11897 
11898     /**
11899      * Set phone type for the default phone.
11900      *
11901      * @param type phone type
11902      *
11903      * @hide
11904      */
setPhoneType(int type)11905     public void setPhoneType(int type) {
11906         int phoneId = getPhoneId();
11907         setPhoneType(phoneId, type);
11908     }
11909 
11910     /**
11911      * Set phone type by phone id.
11912      *
11913      * @param phoneId for which phone type is set
11914      * @param type phone type
11915      *
11916      * @hide
11917      */
11918     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)11919     public void setPhoneType(int phoneId, int type) {
11920         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11921             List<Integer> newList = updateTelephonyProperty(
11922                     TelephonyProperties.current_active_phone(), phoneId, type);
11923             TelephonyProperties.current_active_phone(newList);
11924         }
11925     }
11926 
11927     /**
11928      * Get OTASP number schema for the default phone.
11929      *
11930      * @param defaultValue default value
11931      * @return OTA SP number schema
11932      *
11933      * @hide
11934      */
getOtaSpNumberSchema(String defaultValue)11935     public String getOtaSpNumberSchema(String defaultValue) {
11936         int phoneId = getPhoneId();
11937         return getOtaSpNumberSchemaForPhone(phoneId, defaultValue);
11938     }
11939 
11940     /**
11941      * Get OTASP number schema by phone id.
11942      *
11943      * @param phoneId for which OTA SP number schema is get
11944      * @param defaultValue default value
11945      * @return OTA SP number schema
11946      *
11947      * @hide
11948      */
11949     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)11950     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
11951         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11952             return getTelephonyProperty(
11953                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
11954         }
11955 
11956         return defaultValue;
11957     }
11958 
11959     /**
11960      * Get SMS receive capable from system property for the default phone.
11961      *
11962      * @param defaultValue default value
11963      * @return SMS receive capable
11964      *
11965      * @hide
11966      */
getSmsReceiveCapable(boolean defaultValue)11967     public boolean getSmsReceiveCapable(boolean defaultValue) {
11968         int phoneId = getPhoneId();
11969         return getSmsReceiveCapableForPhone(phoneId, defaultValue);
11970     }
11971 
11972     /**
11973      * Get SMS receive capable from system property by phone id.
11974      *
11975      * @param phoneId for which SMS receive capable is get
11976      * @param defaultValue default value
11977      * @return SMS receive capable
11978      *
11979      * @hide
11980      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)11981     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
11982         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11983             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
11984         }
11985 
11986         return defaultValue;
11987     }
11988 
11989     /**
11990      * Get SMS send capable from system property for the default phone.
11991      *
11992      * @param defaultValue default value
11993      * @return SMS send capable
11994      *
11995      * @hide
11996      */
getSmsSendCapable(boolean defaultValue)11997     public boolean getSmsSendCapable(boolean defaultValue) {
11998         int phoneId = getPhoneId();
11999         return getSmsSendCapableForPhone(phoneId, defaultValue);
12000     }
12001 
12002     /**
12003      * Get SMS send capable from system property by phone id.
12004      *
12005      * @param phoneId for which SMS send capable is get
12006      * @param defaultValue default value
12007      * @return SMS send capable
12008      *
12009      * @hide
12010      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)12011     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
12012         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12013             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
12014         }
12015 
12016         return defaultValue;
12017     }
12018 
12019     /**
12020      * Get the component name of the default app to direct respond-via-message intent for the
12021      * user associated with this subscription, update the cache if there is no respond-via-message
12022      * application currently configured for this user.
12023      * @return component name of the app and class to direct Respond Via Message intent to, or
12024      * {@code null} if the functionality is not supported.
12025      * @hide
12026      */
12027     @SystemApi
12028     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
12029     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getAndUpdateDefaultRespondViaMessageApplication()12030     public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
12031         try {
12032             ITelephony telephony = getITelephony();
12033             if (telephony != null) {
12034                 return telephony.getDefaultRespondViaMessageApplication(getSubId(), true);
12035             }
12036         } catch (RemoteException e) {
12037             Log.e(TAG, "Error in getAndUpdateDefaultRespondViaMessageApplication: " + e);
12038         }
12039         return null;
12040     }
12041 
12042     /**
12043      * Get the component name of the default app to direct respond-via-message intent for the
12044      * user associated with this subscription.
12045      * @return component name of the app and class to direct Respond Via Message intent to, or
12046      * {@code null} if the functionality is not supported.
12047      * @hide
12048      */
12049     @SystemApi
12050     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
12051     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getDefaultRespondViaMessageApplication()12052     public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
12053         try {
12054             ITelephony telephony = getITelephony();
12055             if (telephony != null) {
12056                 return telephony.getDefaultRespondViaMessageApplication(getSubId(), false);
12057             }
12058         } catch (RemoteException e) {
12059             Log.e(TAG, "Error in getDefaultRespondViaMessageApplication: " + e);
12060         }
12061         return null;
12062     }
12063 
12064     /**
12065      * Set the alphabetic name of current registered operator.
12066      * @param name the alphabetic name of current registered operator.
12067      * @hide
12068      */
setNetworkOperatorName(String name)12069     public void setNetworkOperatorName(String name) {
12070         int phoneId = getPhoneId();
12071         setNetworkOperatorNameForPhone(phoneId, name);
12072     }
12073 
12074     /**
12075      * Set the alphabetic name of current registered operator.
12076      * @param phoneId which phone you want to set
12077      * @param name the alphabetic name of current registered operator.
12078      * @hide
12079      */
12080     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNameForPhone(int phoneId, String name)12081     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
12082         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12083             List<String> newList = updateTelephonyProperty(
12084                     TelephonyProperties.operator_alpha(), phoneId, name);
12085             try {
12086                 TelephonyProperties.operator_alpha(newList);
12087             } catch (IllegalArgumentException e) { //property value is longer than the byte limit
12088                 Log.e(TAG, "setNetworkOperatorNameForPhone: ", e);
12089 
12090                 int numberOfEntries = newList.size();
12091                 int maxOperatorLength = //save 1 byte for joiner " , "
12092                         (SystemProperties.PROP_VALUE_MAX - numberOfEntries) / numberOfEntries;
12093 
12094                 //examine and truncate every operator and retry
12095                 for (int i = 0; i < newList.size(); i++) {
12096                     if (newList.get(i) != null) {
12097                         newList.set(i, TextUtils
12098                                 .truncateStringForUtf8Storage(newList.get(i), maxOperatorLength));
12099                     }
12100                 }
12101                 TelephonyProperties.operator_alpha(newList);
12102                 Log.e(TAG, "successfully truncated operator_alpha: " + newList);
12103             }
12104         }
12105     }
12106 
12107     /**
12108      * Set the numeric name (MCC+MNC) of current registered operator.
12109      * @param operator the numeric name (MCC+MNC) of current registered operator
12110      * @hide
12111      */
setNetworkOperatorNumeric(String numeric)12112     public void setNetworkOperatorNumeric(String numeric) {
12113         int phoneId = getPhoneId();
12114         setNetworkOperatorNumericForPhone(phoneId, numeric);
12115     }
12116 
12117     /**
12118      * Set the numeric name (MCC+MNC) of current registered operator.
12119      * @param phoneId for which phone type is set
12120      * @param operator the numeric name (MCC+MNC) of current registered operator
12121      * @hide
12122      */
12123     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNumericForPhone(int phoneId, String numeric)12124     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
12125         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12126             List<String> newList = updateTelephonyProperty(
12127                     TelephonyProperties.operator_numeric(), phoneId, numeric);
12128             TelephonyProperties.operator_numeric(newList);
12129         }
12130     }
12131 
12132     /**
12133      * Set roaming state of the current network, for GSM purposes.
12134      * @param isRoaming is network in romaing state or not
12135      * @hide
12136      */
setNetworkRoaming(boolean isRoaming)12137     public void setNetworkRoaming(boolean isRoaming) {
12138         int phoneId = getPhoneId();
12139         setNetworkRoamingForPhone(phoneId, isRoaming);
12140     }
12141 
12142     /**
12143      * Set roaming state of the current network, for GSM purposes.
12144      * @param phoneId which phone you want to set
12145      * @param isRoaming is network in romaing state or not
12146      * @hide
12147      */
12148     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)12149     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
12150         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12151             List<Boolean> newList = updateTelephonyProperty(
12152                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
12153             TelephonyProperties.operator_is_roaming(newList);
12154         }
12155     }
12156 
12157     /**
12158      * Set the network type currently in use on the device for data transmission.
12159      *
12160      * If this object has been created with {@link #createForSubscriptionId}, applies to the
12161      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
12162      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12163      * @param type the network type currently in use on the device for data transmission
12164      * @hide
12165      */
setDataNetworkType(int type)12166     public void setDataNetworkType(int type) {
12167         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
12168         setDataNetworkTypeForPhone(phoneId, type);
12169     }
12170 
12171     /**
12172      * Set the network type currently in use on the device for data transmission.
12173      * @param phoneId which phone you want to set
12174      * @param type the network type currently in use on the device for data transmission
12175      * @hide
12176      */
12177     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setDataNetworkTypeForPhone(int phoneId, int type)12178     public void setDataNetworkTypeForPhone(int phoneId, int type) {
12179         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12180             List<String> newList = updateTelephonyProperty(
12181                     TelephonyProperties.data_network_type(), phoneId,
12182                     ServiceState.rilRadioTechnologyToString(type));
12183             TelephonyProperties.data_network_type(newList);
12184         }
12185     }
12186 
12187     /**
12188      * Returns the subscription ID for the given phone account.
12189      * @hide
12190      */
12191     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)12192     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
12193         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
12194         if (phoneAccount != null
12195                 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
12196             retval = getSubscriptionId(phoneAccount.getAccountHandle());
12197         }
12198         return retval;
12199     }
12200 
12201     /**
12202      * Determines the {@link PhoneAccountHandle} associated with this TelephonyManager.
12203      *
12204      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12205      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12206      *
12207      * <p>Requires Permission android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE or that the
12208      * calling app has carrier privileges (see {@link #hasCarrierPrivileges})
12209      *
12210      * @return The {@link PhoneAccountHandle} associated with the TelphonyManager, or {@code null}
12211      * if there is no associated {@link PhoneAccountHandle}; this can happen if the subscription is
12212      * data-only or an opportunistic subscription.
12213      */
12214     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12215     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPhoneAccountHandle()12216     public @Nullable PhoneAccountHandle getPhoneAccountHandle() {
12217         return getPhoneAccountHandleForSubscriptionId(getSubId());
12218     }
12219 
12220     /**
12221      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
12222      *
12223      * @param subscriptionId The subscription Id to check.
12224      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
12225      * there is no associated {@link PhoneAccountHandle}.
12226      * @hide
12227      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)12228     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
12229         PhoneAccountHandle returnValue = null;
12230         try {
12231             ITelephony service = getITelephony();
12232             if (service != null) {
12233                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
12234             }
12235         } catch (RemoteException e) {
12236         }
12237 
12238         return returnValue;
12239     }
12240 
12241     /**
12242      * Returns the subscription ID for the given phone account handle.
12243      *
12244      * @param phoneAccountHandle the phone account handle for outgoing calls
12245      * @return subscription ID for the given phone account handle; or
12246      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
12247      *         if not available; or throw a SecurityException if the caller doesn't have the
12248      *         permission.
12249      */
12250     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12251     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)12252     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
12253         return mPhoneAccountHandleToSubIdCache.query(phoneAccountHandle);
12254     }
12255 
12256     /**
12257      * Resets telephony manager settings back to factory defaults.
12258      *
12259      * @hide
12260      */
factoryReset(int subId)12261     public void factoryReset(int subId) {
12262         try {
12263             Log.d(TAG, "factoryReset: subId=" + subId);
12264             ITelephony telephony = getITelephony();
12265             if (telephony != null) {
12266                 telephony.factoryReset(subId, getOpPackageName());
12267             }
12268         } catch (RemoteException e) {
12269         }
12270     }
12271 
12272 
12273     /**
12274      * Resets Telephony and IMS settings back to factory defaults only for the subscription
12275      * associated with this instance.
12276      * @see #createForSubscriptionId(int)
12277      * @hide
12278      */
12279     @SystemApi
12280     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
resetSettings()12281     public void resetSettings() {
12282         try {
12283             Log.d(TAG, "resetSettings: subId=" + getSubId());
12284             ITelephony telephony = getITelephony();
12285             if (telephony != null) {
12286                 telephony.factoryReset(getSubId(), getOpPackageName());
12287             }
12288         } catch (RemoteException e) {
12289         }
12290     }
12291 
12292 
12293     /**
12294      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
12295      * no locale could be derived from subscriptions.
12296      *
12297      * <p>Requires Permission:
12298      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12299      *
12300      * @see Locale#toLanguageTag()
12301      *
12302      * @hide
12303      */
12304     @SystemApi
12305     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12306     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimLocale()12307     @Nullable public Locale getSimLocale() {
12308         try {
12309             final ITelephony telephony = getITelephony();
12310             if (telephony != null) {
12311                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
12312                 if (!TextUtils.isEmpty(languageTag)) {
12313                     return Locale.forLanguageTag(languageTag);
12314                 }
12315             }
12316         } catch (RemoteException ex) {
12317         }
12318         return null;
12319     }
12320 
12321     /**
12322      * TODO delete after SuW migrates to new API.
12323      * @hide
12324      */
getLocaleFromDefaultSim()12325     public String getLocaleFromDefaultSim() {
12326         try {
12327             final ITelephony telephony = getITelephony();
12328             if (telephony != null) {
12329                 return telephony.getSimLocaleForSubscriber(getSubId());
12330             }
12331         } catch (RemoteException ex) {
12332         }
12333         return null;
12334     }
12335 
12336     /**
12337      * Exception that may be supplied to the callback provided in {@link #requestModemActivityInfo}.
12338      * @hide
12339      */
12340     @SystemApi
12341     public static class ModemActivityInfoException extends Exception {
12342         /** Indicates that an unknown error occurred */
12343         public static final int ERROR_UNKNOWN = 0;
12344 
12345         /**
12346          * Indicates that the modem or phone processes are not available (such as when the device
12347          * is in airplane mode).
12348          */
12349         public static final int ERROR_PHONE_NOT_AVAILABLE = 1;
12350 
12351         /**
12352          * Indicates that the modem supplied an invalid instance of {@link ModemActivityInfo}
12353          */
12354         public static final int ERROR_INVALID_INFO_RECEIVED = 2;
12355 
12356         /**
12357          * Indicates that the modem encountered an internal failure when processing the request
12358          * for activity info.
12359          */
12360         public static final int ERROR_MODEM_RESPONSE_ERROR = 3;
12361 
12362         /** @hide */
12363         @Retention(RetentionPolicy.SOURCE)
12364         @IntDef(prefix = {"ERROR_"},
12365                 value = {
12366                         ERROR_UNKNOWN,
12367                         ERROR_PHONE_NOT_AVAILABLE,
12368                         ERROR_INVALID_INFO_RECEIVED,
12369                         ERROR_MODEM_RESPONSE_ERROR,
12370                 })
12371         public @interface ModemActivityInfoError {}
12372 
12373         private final int mErrorCode;
12374 
12375         /**
12376          * An exception with ModemActivityInfo specific error codes.
12377          *
12378          * @param errorCode a ModemActivityInfoError code.
12379          */
ModemActivityInfoException(@odemActivityInfoError int errorCode)12380         public ModemActivityInfoException(@ModemActivityInfoError int errorCode) {
12381             mErrorCode = errorCode;
12382         }
12383 
getErrorCode()12384         public @ModemActivityInfoError int getErrorCode() {
12385             return mErrorCode;
12386         }
12387 
12388         @Override
toString()12389         public String toString() {
12390             switch (mErrorCode) {
12391                 case ERROR_UNKNOWN: return "ERROR_UNKNOWN";
12392                 case ERROR_PHONE_NOT_AVAILABLE: return "ERROR_PHONE_NOT_AVAILABLE";
12393                 case ERROR_INVALID_INFO_RECEIVED: return "ERROR_INVALID_INFO_RECEIVED";
12394                 case ERROR_MODEM_RESPONSE_ERROR: return "ERROR_MODEM_RESPONSE_ERROR";
12395                 default: return "UNDEFINED";
12396             }
12397         }
12398     }
12399 
12400     /**
12401      * Requests the current modem activity info.
12402      *
12403      * The provided instance of {@link ModemActivityInfo} represents the cumulative activity since
12404      * the last restart of the phone process.
12405      *
12406      * @param callback A callback object to which the result will be delivered. If there was an
12407      *                 error processing the request, {@link OutcomeReceiver#onError} will be called
12408      *                 with more details about the error.
12409      * @hide
12410      */
12411     @SystemApi
12412     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
requestModemActivityInfo(@onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback)12413     public void requestModemActivityInfo(@NonNull @CallbackExecutor Executor executor,
12414             @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback) {
12415         Objects.requireNonNull(executor);
12416         Objects.requireNonNull(callback);
12417 
12418         // Pass no handler into the receiver, since we're going to be trampolining the call to the
12419         // listener onto the provided executor.
12420         ResultReceiver wrapperResultReceiver = new ResultReceiver(null) {
12421             @Override
12422             protected void onReceiveResult(int resultCode, Bundle data) {
12423                 if (data == null) {
12424                     Log.w(TAG, "requestModemActivityInfo: received null bundle");
12425                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
12426                     return;
12427                 }
12428                 data.setDefusable(true);
12429                 if (data.containsKey(EXCEPTION_RESULT_KEY)) {
12430                     int receivedErrorCode = data.getInt(EXCEPTION_RESULT_KEY);
12431                     sendErrorToListener(receivedErrorCode);
12432                     return;
12433                 }
12434 
12435                 if (!data.containsKey(MODEM_ACTIVITY_RESULT_KEY)) {
12436                     Log.w(TAG, "requestModemActivityInfo: Bundle did not contain expected key");
12437                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
12438                     return;
12439                 }
12440                 Parcelable receivedResult = data.getParcelable(MODEM_ACTIVITY_RESULT_KEY);
12441                 if (!(receivedResult instanceof ModemActivityInfo)) {
12442                     Log.w(TAG, "requestModemActivityInfo: Bundle contained something that wasn't "
12443                             + "a ModemActivityInfo.");
12444                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
12445                     return;
12446                 }
12447                 ModemActivityInfo modemActivityInfo = (ModemActivityInfo) receivedResult;
12448                 if (!modemActivityInfo.isValid()) {
12449                     Log.w(TAG, "requestModemActivityInfo: Received an invalid ModemActivityInfo");
12450                     sendErrorToListener(ModemActivityInfoException.ERROR_INVALID_INFO_RECEIVED);
12451                     return;
12452                 }
12453                 Log.d(TAG, "requestModemActivityInfo: Sending result to app: " + modemActivityInfo);
12454                 sendResultToListener(modemActivityInfo);
12455             }
12456 
12457             private void sendResultToListener(ModemActivityInfo info) {
12458                 Binder.withCleanCallingIdentity(() ->
12459                         executor.execute(() ->
12460                                 callback.onResult(info)));
12461             }
12462 
12463             private void sendErrorToListener(int code) {
12464                 ModemActivityInfoException e = new ModemActivityInfoException(code);
12465                 Binder.withCleanCallingIdentity(() ->
12466                         executor.execute(() ->
12467                                 callback.onError(e)));
12468             }
12469         };
12470 
12471         try {
12472             ITelephony service = getITelephony();
12473             if (service != null) {
12474                 service.requestModemActivityInfo(wrapperResultReceiver);
12475                 return;
12476             }
12477         } catch (RemoteException e) {
12478             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
12479         }
12480         executor.execute(() -> callback.onError(
12481                 new ModemActivityInfoException(
12482                         ModemActivityInfoException.ERROR_PHONE_NOT_AVAILABLE)));
12483     }
12484 
12485     /**
12486      * Returns the current {@link ServiceState} information.
12487      *
12488      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12489      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12490      *
12491      * If you want continuous updates of service state info, register a {@link PhoneStateListener}
12492      * via {@link #listen} with the {@link PhoneStateListener#LISTEN_SERVICE_STATE} event.
12493      *
12494      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12495      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
12496      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
12497      * May return {@code null} when the subscription is inactive or when there was an error
12498      * communicating with the phone process.
12499      */
12500     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12501     @RequiresPermission(allOf = {
12502             Manifest.permission.READ_PHONE_STATE,
12503             Manifest.permission.ACCESS_COARSE_LOCATION
12504     })
12505     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceState()12506     public @Nullable ServiceState getServiceState() {
12507         return getServiceState(getLocationData());
12508     }
12509 
12510     /**
12511      * Returns the current {@link ServiceState} information.
12512      *
12513      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12514      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12515      *
12516      * If you want continuous updates of service state info, register a {@link PhoneStateListener}
12517      * via {@link #listen} with the {@link PhoneStateListener#LISTEN_SERVICE_STATE} event.
12518      *
12519      * There's another way to renounce permissions with a custom context
12520      * {@code AttributionSource.Builder#setRenouncedPermissions(Set<String>)} but only for system
12521      * apps. To avoid confusion, calling this method supersede renouncing permissions with a
12522      * custom context.
12523      *
12524      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
12525      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
12526      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
12527      * @param includeLocationData Specifies if the caller would like to receive
12528      * location related information.
12529      * May return {@code null} when the subscription is inactive or when there was an error
12530      * communicating with the phone process.
12531      */
12532     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12533     @RequiresPermission(allOf = {
12534             Manifest.permission.READ_PHONE_STATE,
12535             Manifest.permission.ACCESS_COARSE_LOCATION
12536     })
getServiceState(@ncludeLocationData int includeLocationData)12537     public @Nullable ServiceState getServiceState(@IncludeLocationData int includeLocationData) {
12538         return getServiceStateForSubscriber(getSubId(),
12539                 includeLocationData != INCLUDE_LOCATION_DATA_FINE,
12540                 includeLocationData == INCLUDE_LOCATION_DATA_NONE);
12541     }
12542 
12543     /**
12544      * Returns the service state information on specified subscription. Callers require
12545      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
12546      *
12547      * May return {@code null} when the subscription is inactive or when there was an error
12548      * communicating with the phone process.
12549      * @param renounceFineLocationAccess Set this to true if the caller would not like to receive
12550      * location related information which will be sent if the caller already possess
12551      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and do not renounce the permission
12552      * @param renounceCoarseLocationAccess Set this to true if the caller would not like to
12553      * receive location related information which will be sent if the caller already possess
12554      * {@link Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the permissions.
12555      */
getServiceStateForSubscriber(int subId, boolean renounceFineLocationAccess, boolean renounceCoarseLocationAccess)12556     private ServiceState getServiceStateForSubscriber(int subId,
12557             boolean renounceFineLocationAccess,
12558             boolean renounceCoarseLocationAccess) {
12559         try {
12560             ITelephony service = getITelephony();
12561             if (service != null) {
12562                 return service.getServiceStateForSubscriber(subId, renounceFineLocationAccess,
12563                         renounceCoarseLocationAccess, getOpPackageName(), getAttributionTag());
12564             }
12565         } catch (RemoteException e) {
12566             Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
12567         } catch (NullPointerException e) {
12568             AnomalyReporter.reportAnomaly(
12569                     UUID.fromString("e2bed88e-def9-476e-bd71-3e572a8de6d1"),
12570                     "getServiceStateForSubscriber " + subId + " NPE");
12571         }
12572         return null;
12573     }
12574 
12575     /**
12576      * Returns the service state information on specified subscription. Callers require
12577      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
12578      *
12579      * May return {@code null} when the subscription is inactive or when there was an error
12580      * communicating with the phone process.
12581      * @hide
12582      */
12583     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)12584     public ServiceState getServiceStateForSubscriber(int subId) {
12585         return getServiceStateForSubscriber(getSubId(), false, false);
12586     }
12587 
12588     /**
12589      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
12590      *
12591      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
12592      * voicemail ringtone.
12593      * @return The URI for the ringtone to play when receiving a voicemail from a specific
12594      * PhoneAccount. May be {@code null} if no ringtone is set.
12595      */
12596     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)12597     public @Nullable Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
12598         try {
12599             ITelephony service = getITelephony();
12600             if (service != null) {
12601                 return service.getVoicemailRingtoneUri(accountHandle);
12602             }
12603         } catch (RemoteException e) {
12604             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
12605         }
12606         return null;
12607     }
12608 
12609     /**
12610      * Sets the per-account voicemail ringtone.
12611      *
12612      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
12613      * {@link #hasCarrierPrivileges}, or has permission
12614      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12615      *
12616      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
12617      * voicemail ringtone.
12618      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
12619      * PhoneAccount.
12620      *
12621      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
12622      * instead.
12623      */
12624     @Deprecated
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)12625     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
12626         try {
12627             ITelephony service = getITelephony();
12628             if (service != null) {
12629                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
12630             }
12631         } catch (RemoteException e) {
12632             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
12633         }
12634     }
12635 
12636     /**
12637      * Returns whether vibration is set for voicemail notification in Phone settings.
12638      *
12639      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
12640      * voicemail vibration setting.
12641      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
12642      */
12643     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)12644     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
12645         try {
12646             ITelephony service = getITelephony();
12647             if (service != null) {
12648                 return service.isVoicemailVibrationEnabled(accountHandle);
12649             }
12650         } catch (RemoteException e) {
12651             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
12652         }
12653         return false;
12654     }
12655 
12656     /**
12657      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
12658      *
12659      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
12660      * {@link #hasCarrierPrivileges}, or has permission
12661      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12662      *
12663      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
12664      * voicemail vibration setting.
12665      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
12666      * specific PhoneAccount.
12667      *
12668      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
12669      * instead.
12670      */
12671     @Deprecated
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)12672     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
12673             boolean enabled) {
12674         try {
12675             ITelephony service = getITelephony();
12676             if (service != null) {
12677                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
12678                         enabled);
12679             }
12680         } catch (RemoteException e) {
12681             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
12682         }
12683     }
12684 
12685     /**
12686      * Returns carrier id of the current subscription.
12687      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
12688      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
12689      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
12690      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
12691      *
12692      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
12693      * as an Android platform-wide identifier for carriers.
12694      *
12695      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
12696      * subscription is unavailable or the carrier cannot be identified.
12697      */
12698     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCarrierId()12699     public int getSimCarrierId() {
12700         try {
12701             ITelephony service = getITelephony();
12702             if (service != null) {
12703                 return service.getSubscriptionCarrierId(getSubId());
12704             }
12705         } catch (RemoteException ex) {
12706             // This could happen if binder process crashes.
12707         }
12708         return UNKNOWN_CARRIER_ID;
12709     }
12710 
12711     /**
12712      * Returns carrier id name of the current subscription.
12713      * <p>Carrier id name is a user-facing name of carrier id returned by
12714      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
12715      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
12716      * should have a single carrier name. Carrier name is not a canonical identity,
12717      * use {@link #getSimCarrierId()} instead.
12718      * <p>The returned carrier name is unlocalized.
12719      *
12720      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
12721      * unavailable or the carrier cannot be identified.
12722      */
12723     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCarrierIdName()12724     public @Nullable CharSequence getSimCarrierIdName() {
12725         try {
12726             ITelephony service = getITelephony();
12727             if (service != null) {
12728                 return service.getSubscriptionCarrierName(getSubId());
12729             }
12730         } catch (RemoteException ex) {
12731             // This could happen if binder process crashes.
12732         }
12733         return null;
12734     }
12735 
12736     /**
12737      * Returns fine-grained carrier ID of the current subscription.
12738      *
12739      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
12740      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
12741      * are used to make up the actual carrier service may have different carrier configurations.
12742      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
12743      * different carrier configuration for different service offering such as a prepaid plan.
12744      *
12745      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
12746      * about the carrier itself should use the regular carrier ID returned by
12747      * {@link #getSimCarrierId()}.
12748      *
12749      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
12750      * subscription while carrier ID remains the same.
12751      *
12752      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
12753      * <p>Specific carrier ids are defined in the same way as carrier id
12754      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
12755      * except each with a "parent" id linking to its top-level carrier id.
12756      *
12757      * @return Returns fine-grained carrier id of the current subscription.
12758      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
12759      * be identified.
12760      */
12761     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSpecificCarrierId()12762     public int getSimSpecificCarrierId() {
12763         try {
12764             ITelephony service = getITelephony();
12765             if (service != null) {
12766                 return service.getSubscriptionSpecificCarrierId(getSubId());
12767             }
12768         } catch (RemoteException ex) {
12769             // This could happen if binder process crashes.
12770         }
12771         return UNKNOWN_CARRIER_ID;
12772     }
12773 
12774     /**
12775      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
12776      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
12777      *
12778      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
12779      * about the carrier itself should use the regular carrier ID returned by
12780      * {@link #getSimCarrierIdName()}.
12781      *
12782      * <p>The returned name is unlocalized.
12783      *
12784      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
12785      * subscription is unavailable or the carrier cannot be identified.
12786      */
12787     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSpecificCarrierIdName()12788     public @Nullable CharSequence getSimSpecificCarrierIdName() {
12789         try {
12790             ITelephony service = getITelephony();
12791             if (service != null) {
12792                 return service.getSubscriptionSpecificCarrierName(getSubId());
12793             }
12794         } catch (RemoteException ex) {
12795             // This could happen if binder process crashes.
12796         }
12797         return null;
12798     }
12799 
12800     /**
12801      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
12802      * This is used for fallback when configurations/logic for exact carrier id
12803      * {@link #getSimCarrierId()} are not found.
12804      *
12805      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
12806      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
12807      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
12808      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
12809      * take the update with the new id, it might be helpful to always fallback by using carrier
12810      * id based on MCCMNC if there is no match.
12811      *
12812      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
12813      * subscription is unavailable or the carrier cannot be identified.
12814      */
12815     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierIdFromSimMccMnc()12816     public int getCarrierIdFromSimMccMnc() {
12817         try {
12818             ITelephony service = getITelephony();
12819             if (service != null) {
12820                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
12821             }
12822         } catch (RemoteException ex) {
12823             // This could happen if binder process crashes.
12824         }
12825         return UNKNOWN_CARRIER_ID;
12826     }
12827 
12828      /**
12829       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
12830       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
12831       * are not found.
12832       *
12833       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
12834       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
12835       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
12836       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
12837       * take the update with the new id, it might be helpful to always fallback by using carrier
12838       * id based on MCCMNC if there is no match.
12839       *
12840       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
12841       * subscription is unavailable or the carrier cannot be identified.
12842       * @hide
12843       */
12844      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)12845      public int getCarrierIdFromMccMnc(String mccmnc) {
12846         try {
12847             ITelephony service = getITelephony();
12848             if (service != null) {
12849                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
12850             }
12851         } catch (RemoteException ex) {
12852             // This could happen if binder process crashes.
12853         }
12854         return UNKNOWN_CARRIER_ID;
12855     }
12856 
12857     /**
12858      * Return a list of certs as hex strings from loaded carrier privileges access rules.
12859      *
12860      * @return a list of certificates as hex strings, or an empty list if there are no certs or
12861      *     privilege rules are not loaded yet.
12862      * @hide
12863      */
12864     @TestApi
12865     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12866     @NonNull
getCertsFromCarrierPrivilegeAccessRules()12867     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
12868         List<String> certs = null;
12869         try {
12870             ITelephony service = getITelephony();
12871             if (service != null) {
12872                 certs = service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
12873             }
12874         } catch (RemoteException ex) {
12875             // This could happen if binder process crashes.
12876         }
12877         return certs == null ? Collections.emptyList() : certs;
12878     }
12879 
12880     /**
12881      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
12882      * All uicc applications are uniquely identified by application ID, represented by the hex
12883      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
12884      * <p>Requires Permission:
12885      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
12886      *
12887      * @param appType the uicc app type.
12888      * @return Application ID for specified app type or {@code null} if no uicc or error.
12889      * @hide
12890      */
12891     @Nullable
12892     @SystemApi
12893     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12894     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getAidForAppType(@iccAppType int appType)12895     public String getAidForAppType(@UiccAppType int appType) {
12896         return getAidForAppType(getSubId(), appType);
12897     }
12898 
12899     /**
12900      * same as {@link #getAidForAppType(int)}
12901      * @hide
12902      */
getAidForAppType(int subId, int appType)12903     public String getAidForAppType(int subId, int appType) {
12904         try {
12905             ITelephony service = getITelephony();
12906             if (service != null) {
12907                 return service.getAidForAppType(subId, appType);
12908             }
12909         } catch (RemoteException e) {
12910             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
12911         }
12912         return null;
12913     }
12914 
12915     /**
12916      * Return the Electronic Serial Number.
12917      *
12918      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
12919      *
12920      * @return ESN or null if error.
12921      * @hide
12922      */
getEsn()12923     public String getEsn() {
12924         return getEsn(getSubId());
12925     }
12926 
12927     /**
12928      * Return the Electronic Serial Number.
12929      *
12930      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
12931      *
12932      * @param subId the subscription ID that this request applies to.
12933      * @return ESN or null if error.
12934      * @hide
12935      */
getEsn(int subId)12936     public String getEsn(int subId) {
12937         try {
12938             ITelephony service = getITelephony();
12939             if (service != null) {
12940                 return service.getEsn(subId);
12941             }
12942         } catch (RemoteException e) {
12943             Log.e(TAG, "Error calling ITelephony#getEsn", e);
12944         }
12945         return null;
12946     }
12947 
12948     /**
12949      * Return the Preferred Roaming List Version
12950      *
12951      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
12952      *
12953      * @return PRLVersion or null if error.
12954      * @hide
12955      */
12956     @SystemApi
12957     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaPrlVersion()12958     public String getCdmaPrlVersion() {
12959         return getCdmaPrlVersion(getSubId());
12960     }
12961 
12962     /**
12963      * Return the Preferred Roaming List Version
12964      *
12965      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
12966      *
12967      * @param subId the subscription ID that this request applies to.
12968      * @return PRLVersion or null if error.
12969      * @hide
12970      */
getCdmaPrlVersion(int subId)12971     public String getCdmaPrlVersion(int subId) {
12972         try {
12973             ITelephony service = getITelephony();
12974             if (service != null) {
12975                 return service.getCdmaPrlVersion(subId);
12976             }
12977         } catch (RemoteException e) {
12978             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
12979         }
12980         return null;
12981     }
12982 
12983     /**
12984      * Get snapshot of Telephony histograms
12985      * @return List of Telephony histograms
12986      * Requires Permission:
12987      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12988      * Or the calling app has carrier privileges.
12989      * @hide
12990      */
12991     @SystemApi
12992     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()12993     public List<TelephonyHistogram> getTelephonyHistograms() {
12994         try {
12995             ITelephony service = getITelephony();
12996             if (service != null) {
12997                 return service.getTelephonyHistograms();
12998             }
12999         } catch (RemoteException e) {
13000             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
13001         }
13002         return null;
13003     }
13004 
13005     /**
13006      * Set the allowed carrier list for slotIndex
13007      * Require system privileges. In the future we may add this to carrier APIs.
13008      *
13009      * <p>Requires Permission:
13010      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
13011      *
13012      * <p>This method works only on devices with {@link
13013      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13014      *
13015      * @deprecated use setCarrierRestrictionRules instead
13016      *
13017      * @return The number of carriers set successfully. Should be length of
13018      * carrierList on success; -1 if carrierList null or on error.
13019      * @hide
13020      */
13021     @SystemApi
13022     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13023     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)13024     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
13025         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
13026             return -1;
13027         }
13028         // Execute the method setCarrierRestrictionRules with an empty excluded list.
13029         // If the allowed list is empty, it means that all carriers are allowed (default allowed),
13030         // otherwise it means that only specified carriers are allowed (default not allowed).
13031         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
13032                 .setAllowedCarriers(carriers)
13033                 .setDefaultCarrierRestriction(
13034                     carriers.isEmpty()
13035                         ? CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_ALLOWED
13036                         : CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
13037                 .build();
13038 
13039         int result = setCarrierRestrictionRules(carrierRestrictionRules);
13040 
13041         // Convert result into int, as required by this method.
13042         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
13043             return carriers.size();
13044         } else {
13045             return -1;
13046         }
13047     }
13048 
13049     /**
13050      * The carrier restrictions were successfully set.
13051      * @hide
13052      */
13053     @SystemApi
13054     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
13055 
13056     /**
13057      * The carrier restrictions were not set due to lack of support in the modem. This can happen
13058      * if the modem does not support setting the carrier restrictions or if the configuration
13059      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
13060      * @hide
13061      */
13062     @SystemApi
13063     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
13064 
13065     /**
13066      * The setting of carrier restrictions failed.
13067      * @hide
13068      */
13069     @SystemApi
13070     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
13071 
13072     /** @hide */
13073     @Retention(RetentionPolicy.SOURCE)
13074     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
13075             value = {
13076                     SET_CARRIER_RESTRICTION_SUCCESS,
13077                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
13078                     SET_CARRIER_RESTRICTION_ERROR
13079             })
13080     public @interface SetCarrierRestrictionResult {}
13081 
13082     /**
13083      * The SIM power state was successfully set.
13084      * @hide
13085      */
13086     @SystemApi
13087     public static final int SET_SIM_POWER_STATE_SUCCESS = 0;
13088 
13089     /**
13090      * The SIM is already in the requested power state.
13091      * @hide
13092      */
13093     @SystemApi
13094     public static final int SET_SIM_POWER_STATE_ALREADY_IN_STATE = 1;
13095 
13096     /**
13097      * Failed to connect to the modem to make the power state request. This may happen if the
13098      * modem has an error. The user may want to make the request again later.
13099      * @hide
13100      */
13101     @SystemApi
13102     public static final int SET_SIM_POWER_STATE_MODEM_ERROR = 2;
13103 
13104     /**
13105      * Failed to connect to the SIM to make the power state request. This may happen if the
13106      * SIM has been removed. The user may want to make the request again later.
13107      * @hide
13108      */
13109     @SystemApi
13110     public static final int SET_SIM_POWER_STATE_SIM_ERROR = 3;
13111 
13112     /**
13113      * The modem version does not support synchronous power.
13114      * @hide
13115      */
13116     @SystemApi
13117     public static final int SET_SIM_POWER_STATE_NOT_SUPPORTED = 4;
13118 
13119     /** @hide */
13120     @Retention(RetentionPolicy.SOURCE)
13121     @IntDef(prefix = {"SET_SIM_POWER_STATE_"},
13122             value = {
13123                     SET_SIM_POWER_STATE_SUCCESS,
13124                     SET_SIM_POWER_STATE_ALREADY_IN_STATE,
13125                     SET_SIM_POWER_STATE_MODEM_ERROR,
13126                     SET_SIM_POWER_STATE_SIM_ERROR,
13127                     SET_SIM_POWER_STATE_NOT_SUPPORTED
13128             })
13129     public @interface SetSimPowerStateResult {}
13130 
13131     /**
13132      * Set the allowed carrier list and the excluded carrier list indicating the priority between
13133      * the two lists.
13134      * Requires system privileges.
13135      *
13136      * <p>Requires Permission:
13137      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
13138      *
13139      * <p>This method works only on devices with {@link
13140      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13141      *
13142      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
13143      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
13144      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
13145      * @hide
13146      */
13147     @SystemApi
13148     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13149     @SetCarrierRestrictionResult
13150     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)13151     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
13152         try {
13153             ITelephony service = getITelephony();
13154             if (service != null) {
13155                 return service.setAllowedCarriers(rules);
13156             }
13157         } catch (RemoteException e) {
13158             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
13159         } catch (NullPointerException e) {
13160             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
13161         }
13162         return SET_CARRIER_RESTRICTION_ERROR;
13163     }
13164 
13165     /**
13166      * Get the allowed carrier list for slotIndex.
13167      * Requires system privileges.
13168      *
13169      * <p>This method returns valid data on devices with {@link
13170      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13171      *
13172      * @deprecated Apps should use {@link getCarriersRestrictionRules} to retrieve the list of
13173      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
13174      * list is empty. This API could return an empty list, even if some restrictions are present.
13175      *
13176      * @return List of {@link android.telephony.CarrierIdentifier}; empty list
13177      * means all carriers are allowed.
13178      * @hide
13179      */
13180     @Deprecated
13181     @SystemApi
13182     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedCarriers(int slotIndex)13183     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
13184         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
13185             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
13186             if (carrierRestrictionRule != null) {
13187                 return carrierRestrictionRule.getAllowedCarriers();
13188             }
13189         }
13190         return new ArrayList<CarrierIdentifier>(0);
13191     }
13192 
13193     /**
13194      * Get the allowed carrier list and the excluded carrier list indicating the priority between
13195      * the two lists.
13196      * Require system privileges. In the future we may add this to carrier APIs.
13197      *
13198      * <p>This method returns valid data on devices with {@link
13199      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13200      *
13201      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
13202      * excluded carrier list with the priority between the two lists. Returns {@code null}
13203      * in case of error.
13204      * @hide
13205      */
13206     @SystemApi
13207     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13208     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
13209     @Nullable
getCarrierRestrictionRules()13210     public CarrierRestrictionRules getCarrierRestrictionRules() {
13211         try {
13212             ITelephony service = getITelephony();
13213             if (service != null) {
13214                 return service.getAllowedCarriers();
13215             }
13216         } catch (RemoteException e) {
13217             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
13218         } catch (NullPointerException e) {
13219             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
13220         }
13221         return null;
13222     }
13223 
13224     /**
13225      * Carrier restriction status value is unknown, in case modem did not provide any
13226      * information about carrier restriction status.
13227      */
13228     public static final int CARRIER_RESTRICTION_STATUS_UNKNOWN = 0;
13229 
13230     /** The device is not restricted to a carrier */
13231     public static final int CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED = 1;
13232 
13233     /** The device is restricted to a carrier. */
13234     public static final int CARRIER_RESTRICTION_STATUS_RESTRICTED = 2;
13235 
13236     /** The device is restricted to the carrier of the calling application. */
13237     public static final int CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER = 3;
13238 
13239     /** @hide */
13240     @IntDef(prefix = {"CARRIER_RESTRICTION_STATUS_"}, value = {
13241             CARRIER_RESTRICTION_STATUS_UNKNOWN,
13242             CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED,
13243             CARRIER_RESTRICTION_STATUS_RESTRICTED,
13244             CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER
13245     })
13246 
13247     public @interface CarrierRestrictionStatus {
13248     }
13249 
13250     /**
13251      * Get the carrier restriction status of the device.
13252      * <p>To fetch the carrier restriction status of the device the calling application needs to be
13253      * allowlisted to Android at <a href="https://android.googlesource.com/platform/packages/services/Telephony/+/master/assets/CarrierRestrictionOperatorDetails.json">here</a>.
13254      * The calling application also needs the READ_PHONE_STATE permission.
13255      * The return value of the API is as follows.
13256      * <ul>
13257      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER} if the caller
13258      *      and the device locked by the network are same</li>
13259      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_RESTRICTED} if the caller and the
13260      *      device locked by the network are different</li>
13261      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED} if the device is
13262      *      not locked</li>
13263      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_UNKNOWN} if the device locking
13264      *      state is unavailable or radio does not supports the feature</li>
13265      * </ul>
13266      *
13267      * @param executor The executor on which the result listener will be called.
13268      * @param resultListener {@link Consumer} that will be called with the result fetched
13269      *                       from the radio of type {@link CarrierRestrictionStatus}
13270      * @throws SecurityException if the caller does not have the required permission/privileges or
13271      *                           if the caller is not pre-registered.
13272      */
13273     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
13274     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCarrierRestrictionStatus(@onNull Executor executor, @NonNull @CarrierRestrictionStatus Consumer<Integer> resultListener)13275     public void getCarrierRestrictionStatus(@NonNull Executor executor,
13276             @NonNull @CarrierRestrictionStatus
13277                     Consumer<Integer> resultListener) {
13278         Objects.requireNonNull(executor);
13279         Objects.requireNonNull(resultListener);
13280 
13281         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
13282             @Override
13283             public void accept(@CarrierRestrictionStatus int result) {
13284                 executor.execute(() -> Binder.withCleanCallingIdentity(
13285                         () -> resultListener.accept(result)));
13286             }
13287         };
13288         try {
13289             ITelephony service = getITelephony();
13290             if (service != null) {
13291                 service.getCarrierRestrictionStatus(internalCallback, getOpPackageName());
13292             }
13293         } catch (RemoteException ex) {
13294             Rlog.e(TAG, "getCarrierRestrictionStatus: RemoteException = " + ex);
13295             throw ex.rethrowAsRuntimeException();
13296         }
13297     }
13298 
13299     /**
13300      * Test API to verify carrier restriction status allow list i.e.
13301      * packages/services/Telephony/assets/CarrierRestrictionOperatorDetails.json.
13302      *
13303      * @param pkgName : packaga name of the entry to verify
13304      * @param carrierId : carrier Id of the entry
13305      * @return {@code List<String>} : list of registered shaIds
13306      * @hide
13307      */
13308     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getShaIdFromAllowList(String pkgName, int carrierId)13309     public List<String> getShaIdFromAllowList(String pkgName, int carrierId) {
13310         try {
13311             ITelephony service = getITelephony();
13312             if (service != null) {
13313                 return service.getShaIdFromAllowList(pkgName, carrierId);
13314             }
13315         } catch (RemoteException ex) {
13316             Rlog.e(TAG, "getShaIdFromAllowList: RemoteException = " + ex);
13317             throw ex.rethrowAsRuntimeException();
13318         }
13319         return Collections.EMPTY_LIST;
13320     }
13321 
13322     /**
13323      * Used to enable or disable carrier data by the system based on carrier signalling or
13324      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
13325      * user settings, carrier data on/off won't affect user settings but will bypass the
13326      * settings and turns off data internally if set to {@code false}.
13327      *
13328      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13329      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13330      *
13331      * <p>Requires Permission:
13332      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13333      *
13334      * @param enabled control enable or disable carrier data.
13335      * @see #resetAllCarrierActions()
13336      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
13337      * reason {@link #DATA_ENABLED_REASON_CARRIER}} instead.
13338      * @hide
13339      */
13340     @Deprecated
13341     @SystemApi
13342     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCarrierDataEnabled(boolean enabled)13343     public void setCarrierDataEnabled(boolean enabled) {
13344         try {
13345             setDataEnabledForReason(DATA_ENABLED_REASON_CARRIER, enabled);
13346         } catch (RuntimeException e) {
13347             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
13348         }
13349     }
13350 
13351     /**
13352      * Carrier action to enable or disable the radio.
13353      *
13354      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13355      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13356      *
13357      * <p>Requires Permission:
13358      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13359      *
13360      * @param enabled control enable or disable radio.
13361      * @see #resetAllCarrierActions()
13362      *
13363      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
13364      * {@link clearRadioPowerOffForReason}.
13365      *
13366      * @hide
13367      */
13368     @Deprecated
13369     @SystemApi
13370     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13371     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadioEnabled(boolean enabled)13372     public void setRadioEnabled(boolean enabled) {
13373         if (enabled) {
13374             clearRadioPowerOffForReason(RADIO_POWER_REASON_CARRIER);
13375         } else {
13376             requestRadioPowerOffForReason(RADIO_POWER_REASON_CARRIER);
13377         }
13378     }
13379 
13380     /**
13381      * No error. Operation succeeded.
13382      * @hide
13383      */
13384     public static final int ENABLE_VONR_SUCCESS = 0;
13385 
13386     /**
13387      * Radio is not available.
13388      * @hide
13389      */
13390     public static final int ENABLE_VONR_RADIO_NOT_AVAILABLE = 2;
13391 
13392     /**
13393      * Internal Radio error.
13394      * @hide
13395      */
13396     public static final int ENABLE_VONR_RADIO_ERROR = 3;
13397 
13398     /**
13399      * Voice over NR enable/disable request is received when system is in invalid state.
13400      * @hide
13401      */
13402     public static final int ENABLE_VONR_RADIO_INVALID_STATE = 4;
13403 
13404     /**
13405      * Voice over NR enable/disable request is not supported.
13406      * @hide
13407      */
13408     public static final int ENABLE_VONR_REQUEST_NOT_SUPPORTED = 5;
13409 
13410     /** @hide */
13411     @Retention(RetentionPolicy.SOURCE)
13412     @IntDef(prefix = {"EnableVoNrResult"}, value = {
13413             ENABLE_VONR_SUCCESS,
13414             ENABLE_VONR_RADIO_NOT_AVAILABLE,
13415             ENABLE_VONR_RADIO_ERROR,
13416             ENABLE_VONR_RADIO_INVALID_STATE,
13417             ENABLE_VONR_REQUEST_NOT_SUPPORTED})
13418     public @interface EnableVoNrResult {}
13419 
13420     /**
13421      * Enable or disable Voice over NR (VoNR)
13422      *
13423      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13424      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13425      *
13426      * <p>Requires Permission:
13427      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13428      *
13429      * @param enabled  enable or disable VoNR.
13430      * @throws IllegalStateException if the Telephony process is not currently available.
13431      * @hide
13432      */
13433     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoNrEnabled(boolean enabled)13434     public @EnableVoNrResult int setVoNrEnabled(boolean enabled) {
13435         try {
13436             ITelephony service = getITelephony();
13437             if (service != null) {
13438                 return service.setVoNrEnabled(
13439                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
13440             } else {
13441                 throw new IllegalStateException("telephony service is null.");
13442             }
13443         } catch (RemoteException e) {
13444             Log.e(TAG, "Error calling ITelephony#setVoNrEnabled", e);
13445         }
13446 
13447         return ENABLE_VONR_RADIO_INVALID_STATE;
13448     }
13449 
13450     /**
13451      * Is Voice over NR (VoNR) enabled.
13452      * @return true if Voice over NR (VoNR) is enabled else false. Enabled state does not mean
13453      *  voice call over NR is active or voice ove NR is available. It means the device is allowed to
13454      *  register IMS over NR.
13455      * @throws IllegalStateException if the Telephony process is not currently available.
13456      * @hide
13457      */
13458     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isVoNrEnabled()13459     public boolean isVoNrEnabled() {
13460         try {
13461             ITelephony telephony = getITelephony();
13462             if (telephony != null) {
13463                 return telephony.isVoNrEnabled(getSubId());
13464             } else {
13465                 throw new IllegalStateException("telephony service is null.");
13466             }
13467         } catch (RemoteException ex) {
13468             Rlog.e(TAG, "isVoNrEnabled RemoteException", ex);
13469             ex.rethrowFromSystemServer();
13470         }
13471         return false;
13472     }
13473 
13474     /**
13475      * Carrier action to start or stop reporting default network available events.
13476      *
13477      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13478      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13479      *
13480      * <p>Requires Permission:
13481      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13482      *
13483      * @param report control start/stop reporting network status.
13484      * @see #resetAllCarrierActions()
13485      * @hide
13486      */
13487     @SystemApi
13488     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13489     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
reportDefaultNetworkStatus(boolean report)13490     public void reportDefaultNetworkStatus(boolean report) {
13491         try {
13492             ITelephony service = getITelephony();
13493             if (service != null) {
13494                 service.carrierActionReportDefaultNetworkStatus(
13495                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
13496             }
13497         } catch (RemoteException e) {
13498             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
13499         }
13500     }
13501 
13502     /**
13503      * Reset all carrier actions previously set by {@link #setRadioEnabled},
13504      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
13505      *
13506      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13507      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13508      *
13509      * <p>Requires Permission:
13510      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13511      * @hide
13512      */
13513     @SystemApi
13514     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13515     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
resetAllCarrierActions()13516     public void resetAllCarrierActions() {
13517         try {
13518             ITelephony service = getITelephony();
13519             if (service != null) {
13520                 service.carrierActionResetAll(
13521                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
13522             }
13523         } catch (RemoteException e) {
13524             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
13525         }
13526     }
13527 
13528     /**
13529      * Policy control of data connection. Usually used when data limit is passed.
13530      * @param enabled True if enabling the data, otherwise disabling.
13531      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
13532      * reason {@link #DATA_ENABLED_REASON_POLICY}} instead.
13533      * @hide
13534      */
13535     @Deprecated
13536     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setPolicyDataEnabled(boolean enabled)13537     public void setPolicyDataEnabled(boolean enabled) {
13538         try {
13539             setDataEnabledForReason(DATA_ENABLED_REASON_POLICY, enabled);
13540         } catch (RuntimeException e) {
13541             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
13542         }
13543     }
13544 
13545     /** @hide */
13546     @IntDef({
13547             DATA_ENABLED_REASON_USER,
13548             DATA_ENABLED_REASON_POLICY,
13549             DATA_ENABLED_REASON_CARRIER,
13550             DATA_ENABLED_REASON_THERMAL
13551     })
13552     @Retention(RetentionPolicy.SOURCE)
13553     public @interface DataEnabledReason{}
13554 
13555     /** @hide */
13556     @IntDef({
13557             DATA_ENABLED_REASON_UNKNOWN,
13558             DATA_ENABLED_REASON_USER,
13559             DATA_ENABLED_REASON_POLICY,
13560             DATA_ENABLED_REASON_CARRIER,
13561             DATA_ENABLED_REASON_THERMAL,
13562             DATA_ENABLED_REASON_OVERRIDE
13563     })
13564     @Retention(RetentionPolicy.SOURCE)
13565     public @interface DataEnabledChangedReason{}
13566 
13567     /**
13568      * To indicate that data was enabled or disabled due to an unknown reason.
13569      * Note that this is not a valid reason for {@link #setDataEnabledForReason(int, boolean)} and
13570      * is only used to indicate that data enabled was changed.
13571      */
13572     public static final int DATA_ENABLED_REASON_UNKNOWN = -1;
13573 
13574     /**
13575      * To indicate that user enabled or disabled data.
13576      */
13577     public static final int DATA_ENABLED_REASON_USER = 0;
13578 
13579     /**
13580      * To indicate that data control due to policy. Usually used when data limit is passed.
13581      * Policy data on/off won't affect user settings but will bypass the
13582      * settings and turns off data internally if set to {@code false}.
13583      */
13584     public static final int DATA_ENABLED_REASON_POLICY = 1;
13585 
13586     /**
13587      * To indicate enable or disable carrier data by the system based on carrier signalling or
13588      * carrier privileged apps. Carrier data on/off won't affect user settings but will bypass the
13589      * settings and turns off data internally if set to {@code false}.
13590      */
13591     public static final int DATA_ENABLED_REASON_CARRIER = 2;
13592 
13593     /**
13594      * To indicate enable or disable data by thermal service.
13595      * Thermal data on/off won't affect user settings but will bypass the
13596      * settings and turns off data internally if set to {@code false}.
13597      */
13598     public static final int DATA_ENABLED_REASON_THERMAL = 3;
13599 
13600     /**
13601      * To indicate data was enabled or disabled due to {@link MobileDataPolicy} overrides.
13602      * Note that this is not a valid reason for {@link #setDataEnabledForReason(int, boolean)} and
13603      * is only used to indicate that data enabled was changed due to an override.
13604      */
13605     public static final int DATA_ENABLED_REASON_OVERRIDE = 4;
13606 
13607     /**
13608      * Control of data connection and provide the reason triggering the data connection control.
13609      * This can be called for following reasons
13610      * <ol>
13611      * <li>data limit is passed {@link #DATA_ENABLED_REASON_POLICY}
13612      * <li>data disabled by carrier {@link #DATA_ENABLED_REASON_CARRIER}
13613      * <li>data disabled by user {@link #DATA_ENABLED_REASON_USER}
13614      * <li>data disabled due to thermal {@link #DATA_ENABLED_REASON_THERMAL}
13615      * </ol>
13616      * If any of the reason is off, then it will result in
13617      * bypassing user preference and result in data to be turned off.
13618      *
13619      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
13620      *      to the given subId. Otherwise, applies to
13621      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13622      *
13623      *
13624      * @param reason the reason the data enable change is taking place
13625      * @param enabled True if enabling the data, otherwise disabling.
13626      *
13627      * <p>Requires Permission:
13628      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) if the reason is
13629      * {@link #DATA_ENABLED_REASON_USER} or {@link #DATA_ENABLED_REASON_CARRIER} or the call app
13630      * has {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} irrespective of
13631      * the reason.
13632      * @throws IllegalStateException if the Telephony process is not currently available.
13633      */
13634     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
13635     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabledForReason(@ataEnabledReason int reason, boolean enabled)13636     public void setDataEnabledForReason(@DataEnabledReason int reason, boolean enabled) {
13637         setDataEnabledForReason(getSubId(), reason, enabled);
13638     }
13639 
setDataEnabledForReason(int subId, @DataEnabledReason int reason, boolean enabled)13640     private void setDataEnabledForReason(int subId, @DataEnabledReason int reason,
13641             boolean enabled) {
13642         try {
13643             ITelephony service = getITelephony();
13644             if (service != null) {
13645                 service.setDataEnabledForReason(subId, reason, enabled, getOpPackageName());
13646             } else {
13647                 throw new IllegalStateException("telephony service is null.");
13648             }
13649         } catch (RemoteException ex) {
13650             Log.e(TAG, "Telephony#setDataEnabledForReason RemoteException", ex);
13651             ex.rethrowFromSystemServer();
13652         }
13653     }
13654 
13655     /**
13656      * Return whether data is enabled for certain reason .
13657      *
13658      * If {@link #isDataEnabledForReason} returns false, it means in data enablement for a
13659      * specific reason is turned off. If any of the reason is off, then it will result in
13660      * bypassing user preference and result in data to be turned off. Call
13661      * {@link #isDataConnectionAllowed} in order to know whether
13662      * data connection is allowed on the device.
13663      *
13664      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
13665      *      to the given subId. Otherwise, applies to
13666      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13667      * @param reason the reason the data enable change is taking place
13668      * @return whether data is enabled for a reason.
13669      * <p>Requires Permission:
13670      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) or
13671      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or
13672      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE} or
13673      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}
13674      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE}
13675      * @throws IllegalStateException if the Telephony process is not currently available.
13676      */
13677     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
13678             android.Manifest.permission.READ_PHONE_STATE,
13679             android.Manifest.permission.MODIFY_PHONE_STATE,
13680             android.Manifest.permission.READ_BASIC_PHONE_STATE
13681     })
13682     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabledForReason(@ataEnabledReason int reason)13683     public boolean isDataEnabledForReason(@DataEnabledReason int reason) {
13684         return isDataEnabledForReason(getSubId(), reason);
13685     }
13686 
isDataEnabledForReason(int subId, @DataEnabledReason int reason)13687     private boolean isDataEnabledForReason(int subId, @DataEnabledReason int reason) {
13688         try {
13689             ITelephony service = getITelephony();
13690             if (service != null) {
13691                 return service.isDataEnabledForReason(subId, reason);
13692             } else {
13693                 throw new IllegalStateException("telephony service is null.");
13694             }
13695         } catch (RemoteException ex) {
13696             Log.e(TAG, "Telephony#isDataEnabledForReason RemoteException", ex);
13697             ex.rethrowFromSystemServer();
13698         }
13699         return false;
13700     }
13701 
13702     /**
13703      * Get Client request stats which will contain statistical information
13704      * on each request made by client.
13705      * Callers require either READ_PRIVILEGED_PHONE_STATE or
13706      * READ_PHONE_STATE to retrieve the information.
13707      * @param subId sub id
13708      * @return List of Client Request Stats
13709      * @hide
13710      */
getClientRequestStats(int subId)13711     public List<ClientRequestStats> getClientRequestStats(int subId) {
13712         try {
13713             ITelephony service = getITelephony();
13714             if (service != null) {
13715                 return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
13716                         subId);
13717             }
13718         } catch (RemoteException e) {
13719             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
13720         }
13721 
13722         return null;
13723     }
13724 
13725     /**
13726      * Checks if phone is in emergency callback mode.
13727      *
13728      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13729      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
13730      *
13731      * @return true if phone is in emergency callback mode.
13732      * @hide
13733      */
13734     @SystemApi
13735     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13736     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyCallbackMode()13737     public boolean getEmergencyCallbackMode() {
13738         return getEmergencyCallbackMode(getSubId());
13739     }
13740 
13741     /**
13742      * Check if phone is in emergency callback mode
13743      * @return true if phone is in emergency callback mode
13744      * @param subId the subscription ID that this action applies to.
13745      * @hide
13746      */
getEmergencyCallbackMode(int subId)13747     public boolean getEmergencyCallbackMode(int subId) {
13748         try {
13749             ITelephony telephony = getITelephony();
13750             if (telephony == null) {
13751                 return false;
13752             }
13753             return telephony.getEmergencyCallbackMode(subId);
13754         } catch (RemoteException e) {
13755             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
13756         }
13757         return false;
13758     }
13759 
13760     /**
13761      * Checks if manual network selection is allowed.
13762      *
13763      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
13764      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
13765      * (see {@link #hasCarrierPrivileges})
13766      *
13767      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13768      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
13769      *
13770      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
13771      */
13772     @SuppressAutoDoc // No support carrier privileges (b/72967236).
13773     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRECISE_PHONE_STATE,
13774             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
13775     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isManualNetworkSelectionAllowed()13776     public boolean isManualNetworkSelectionAllowed() {
13777         try {
13778             ITelephony telephony = getITelephony();
13779             if (telephony != null) {
13780                 return telephony.isManualNetworkSelectionAllowed(getSubId());
13781             }
13782         } catch (RemoteException e) {
13783             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
13784         }
13785         return true;
13786     }
13787 
13788     /**
13789      * Get the most recently available signal strength information.
13790      *
13791      * Get the most recent SignalStrength information reported by the modem. Due
13792      * to power saving this information may not always be current.
13793      * @return the most recent cached signal strength info from the modem
13794      */
13795     @Nullable
13796     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSignalStrength()13797     public SignalStrength getSignalStrength() {
13798         try {
13799             ITelephony service = getITelephony();
13800             if (service != null) {
13801                 return service.getSignalStrength(getSubId());
13802             }
13803         } catch (RemoteException e) {
13804             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
13805         }
13806         return null;
13807     }
13808 
13809     /**
13810      * Checks whether cellular data connection is allowed in the device.
13811      *
13812      * <p>Whether cellular data connection is allowed considers all factors below:
13813      * <UL>
13814      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
13815      *   <LI>Carrier allows data to be on.</LI>
13816      *   <LI>Network policy.</LI>
13817      *   <LI>And possibly others.</LI>
13818      * </UL>
13819      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
13820      */
13821     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
13822             android.Manifest.permission.READ_PHONE_STATE,
13823             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
13824             android.Manifest.permission.READ_BASIC_PHONE_STATE})
13825     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataConnectionAllowed()13826     public boolean isDataConnectionAllowed() {
13827         boolean retVal = false;
13828         try {
13829             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
13830             ITelephony telephony = getITelephony();
13831             if (telephony != null)
13832                 retVal = telephony.isDataEnabled(subId);
13833         } catch (RemoteException e) {
13834             Log.e(TAG, "Error isDataConnectionAllowed", e);
13835         }
13836         return retVal;
13837     }
13838 
13839     /**
13840      * @return true if the current device is "data capable" over a radio on the device.
13841      * <p>
13842      * "Data capable" means that this device supports packet-switched
13843      * data connections over the telephony network.
13844      * <p>
13845      */
13846     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataCapable()13847     public boolean isDataCapable() {
13848         if (mContext == null) return true;
13849         return mContext.getResources().getBoolean(
13850                 com.android.internal.R.bool.config_mobile_data_capable);
13851     }
13852 
13853     /**
13854      * The indication for signal strength update.
13855      * @hide
13856      */
13857     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
13858 
13859     /**
13860      * The indication for full network state update.
13861      * @hide
13862      */
13863     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
13864 
13865     /**
13866      * The indication for data call dormancy changed update.
13867      * @hide
13868      */
13869     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
13870 
13871     /**
13872      * The indication for link capacity estimate update.
13873      * @hide
13874      */
13875     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
13876 
13877     /**
13878      * The indication for physical channel config update.
13879      * @hide
13880      */
13881     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
13882 
13883     /**
13884      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
13885      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
13886      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
13887      *
13888      * <p>Requires Permission:
13889      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
13890      *
13891      *
13892      * @deprecated
13893      * @hide
13894      */
13895     @Deprecated
13896     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)13897     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
13898             String gid2, String plmn, String spn) {
13899         try {
13900             ITelephony telephony = getITelephony();
13901             if (telephony != null) {
13902                 telephony.setCarrierTestOverride(
13903                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
13904                         null, null);
13905             }
13906         } catch (RemoteException ex) {
13907             // This could happen if binder process crashes.
13908         }
13909     }
13910 
13911     /**
13912      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
13913      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
13914      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
13915      * a test SIM with a call box.
13916      *
13917      * <p>Requires Permission:
13918      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
13919      *
13920      * @hide
13921      */
13922     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)13923     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
13924                                        String gid2, String plmn, String spn,
13925                                        String carrierPriviledgeRules, String apn) {
13926         try {
13927             ITelephony telephony = getITelephony();
13928             if (telephony != null) {
13929                 telephony.setCarrierTestOverride(
13930                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
13931                         carrierPriviledgeRules, apn);
13932             }
13933         } catch (RemoteException ex) {
13934             // This could happen if binder process crashes.
13935         }
13936     }
13937 
13938     /**
13939      * A test API to return installed carrier id list version
13940      *
13941      * <p>Requires Permission:
13942      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
13943      *
13944      * @hide
13945      */
13946     @UnsupportedAppUsage
13947     @TestApi
getCarrierIdListVersion()13948     public int getCarrierIdListVersion() {
13949         try {
13950             ITelephony telephony = getITelephony();
13951             if (telephony != null) {
13952                 return telephony.getCarrierIdListVersion(getSubId());
13953             }
13954         } catch (RemoteException ex) {
13955             // This could happen if binder process crashes.
13956         }
13957         return UNKNOWN_CARRIER_ID_LIST_VERSION;
13958     }
13959 
13960     /**
13961      * How many modems can have simultaneous data connections.
13962      * @hide
13963      */
13964     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()13965     public int getNumberOfModemsWithSimultaneousDataConnections() {
13966         try {
13967             ITelephony telephony = getITelephony();
13968             if (telephony != null) {
13969                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
13970                         getSubId(), getOpPackageName(), getAttributionTag());
13971             }
13972         } catch (RemoteException ex) {
13973             // This could happen if binder process crashes.
13974         }
13975         return 0;
13976     }
13977 
13978     /**
13979      * Enable or disable OpportunisticNetworkService.
13980      *
13981      * This method should be called to enable or disable
13982      * OpportunisticNetwork service on the device.
13983      *
13984      * <p>
13985      * Requires Permission:
13986      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
13987      *
13988      * @param enable enable(True) or disable(False)
13989      * @return returns true if successfully set.
13990      * @hide
13991      */
13992     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13993     @SystemApi
13994     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setOpportunisticNetworkState(boolean enable)13995     public boolean setOpportunisticNetworkState(boolean enable) {
13996         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
13997         boolean ret = false;
13998         try {
13999             IOns iOpportunisticNetworkService = getIOns();
14000             if (iOpportunisticNetworkService != null) {
14001                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
14002             }
14003         } catch (RemoteException ex) {
14004             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
14005         }
14006 
14007         return ret;
14008     }
14009 
14010     /**
14011      * is OpportunisticNetworkService enabled
14012      *
14013      * This method should be called to determine if the OpportunisticNetworkService is
14014      * enabled
14015      *
14016      * <p>
14017      * Requires Permission:
14018      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
14019      * @hide
14020      */
14021     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14022     @SystemApi
14023     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isOpportunisticNetworkEnabled()14024     public boolean isOpportunisticNetworkEnabled() {
14025         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
14026         boolean isEnabled = false;
14027 
14028         try {
14029             IOns iOpportunisticNetworkService = getIOns();
14030             if (iOpportunisticNetworkService != null) {
14031                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
14032             }
14033         } catch (RemoteException ex) {
14034             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
14035         }
14036 
14037         return isEnabled;
14038     }
14039 
14040     /** @hide */
14041     @Retention(RetentionPolicy.SOURCE)
14042     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
14043             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
14044                     NETWORK_TYPE_BITMASK_GSM,
14045                     NETWORK_TYPE_BITMASK_GPRS,
14046                     NETWORK_TYPE_BITMASK_EDGE,
14047                     NETWORK_TYPE_BITMASK_CDMA,
14048                     NETWORK_TYPE_BITMASK_1xRTT,
14049                     NETWORK_TYPE_BITMASK_EVDO_0,
14050                     NETWORK_TYPE_BITMASK_EVDO_A,
14051                     NETWORK_TYPE_BITMASK_EVDO_B,
14052                     NETWORK_TYPE_BITMASK_EHRPD,
14053                     NETWORK_TYPE_BITMASK_HSUPA,
14054                     NETWORK_TYPE_BITMASK_HSDPA,
14055                     NETWORK_TYPE_BITMASK_HSPA,
14056                     NETWORK_TYPE_BITMASK_HSPAP,
14057                     NETWORK_TYPE_BITMASK_UMTS,
14058                     NETWORK_TYPE_BITMASK_TD_SCDMA,
14059                     NETWORK_TYPE_BITMASK_LTE,
14060                     NETWORK_TYPE_BITMASK_LTE_CA,
14061                     NETWORK_TYPE_BITMASK_NR,
14062                     NETWORK_TYPE_BITMASK_IWLAN,
14063                     NETWORK_TYPE_BITMASK_IDEN
14064             })
14065     public @interface NetworkTypeBitMask {}
14066 
14067     // 2G
14068     /**
14069      * network type bitmask unknown.
14070      */
14071     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
14072     /**
14073      * network type bitmask indicating the support of radio tech GSM.
14074      */
14075     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
14076     /**
14077      * network type bitmask indicating the support of radio tech GPRS.
14078      */
14079     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
14080     /**
14081      * network type bitmask indicating the support of radio tech EDGE.
14082      */
14083     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
14084     /**
14085      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
14086      */
14087     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
14088     /**
14089      * network type bitmask indicating the support of radio tech 1xRTT.
14090      */
14091     @SuppressLint("AllUpper")
14092     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
14093     // 3G
14094     /**
14095      * network type bitmask indicating the support of radio tech EVDO 0.
14096      */
14097     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
14098     /**
14099      * network type bitmask indicating the support of radio tech EVDO A.
14100      */
14101     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
14102     /**
14103      * network type bitmask indicating the support of radio tech EVDO B.
14104      */
14105     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
14106     /**
14107      * network type bitmask indicating the support of radio tech EHRPD.
14108      */
14109     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
14110     /**
14111      * network type bitmask indicating the support of radio tech HSUPA.
14112      */
14113     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
14114     /**
14115      * network type bitmask indicating the support of radio tech HSDPA.
14116      */
14117     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
14118     /**
14119      * network type bitmask indicating the support of radio tech HSPA.
14120      */
14121     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
14122     /**
14123      * network type bitmask indicating the support of radio tech iDen.
14124      * @hide
14125      */
14126     public static final long NETWORK_TYPE_BITMASK_IDEN = (1 << (NETWORK_TYPE_IDEN - 1));
14127     /**
14128      * network type bitmask indicating the support of radio tech HSPAP.
14129      */
14130     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
14131     /**
14132      * network type bitmask indicating the support of radio tech UMTS.
14133      */
14134     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
14135     /**
14136      * network type bitmask indicating the support of radio tech TD_SCDMA.
14137      */
14138     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
14139     // 4G
14140     /**
14141      * network type bitmask indicating the support of radio tech LTE.
14142      */
14143     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
14144     /**
14145      * NOT USED; this bitmask is exposed accidentally.
14146      * If used, will be converted to {@link #NETWORK_TYPE_BITMASK_LTE}.
14147      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
14148      *
14149      * @deprecated Please use {@link #NETWORK_TYPE_BITMASK_LTE} instead. Deprecated in Android U.
14150      */
14151     @Deprecated
14152     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
14153 
14154     /**
14155      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
14156      */
14157     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
14158 
14159     /**
14160      * network type bitmask indicating the support of radio tech IWLAN.
14161      */
14162     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
14163 
14164     /** @hide */
14165     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
14166                 | NETWORK_TYPE_BITMASK_GPRS
14167                 | NETWORK_TYPE_BITMASK_EDGE
14168                 | NETWORK_TYPE_BITMASK_CDMA
14169                 | NETWORK_TYPE_BITMASK_1xRTT;
14170 
14171     /** @hide */
14172     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
14173             | NETWORK_TYPE_BITMASK_EVDO_A
14174             | NETWORK_TYPE_BITMASK_EVDO_B
14175             | NETWORK_TYPE_BITMASK_EHRPD
14176             | NETWORK_TYPE_BITMASK_HSUPA
14177             | NETWORK_TYPE_BITMASK_HSDPA
14178             | NETWORK_TYPE_BITMASK_HSPA
14179             | NETWORK_TYPE_BITMASK_HSPAP
14180             | NETWORK_TYPE_BITMASK_UMTS
14181             | NETWORK_TYPE_BITMASK_TD_SCDMA;
14182 
14183     /** @hide */
14184     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
14185             | NETWORK_TYPE_BITMASK_LTE_CA
14186             | NETWORK_TYPE_BITMASK_IWLAN;
14187 
14188     /** @hide */
14189     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
14190 
14191     /** @hide */
14192     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
14193             | NETWORK_TYPE_BITMASK_GPRS
14194             | NETWORK_TYPE_BITMASK_EDGE
14195             | NETWORK_TYPE_BITMASK_HSUPA
14196             | NETWORK_TYPE_BITMASK_HSDPA
14197             | NETWORK_TYPE_BITMASK_HSPA
14198             | NETWORK_TYPE_BITMASK_HSPAP
14199             | NETWORK_TYPE_BITMASK_UMTS
14200             | NETWORK_TYPE_BITMASK_TD_SCDMA
14201             | NETWORK_TYPE_BITMASK_LTE
14202             | NETWORK_TYPE_BITMASK_LTE_CA
14203             | NETWORK_TYPE_BITMASK_NR;
14204 
14205     /** @hide */
14206     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
14207             | NETWORK_TYPE_BITMASK_1xRTT
14208             | NETWORK_TYPE_BITMASK_EVDO_0
14209             | NETWORK_TYPE_BITMASK_EVDO_A
14210             | NETWORK_TYPE_BITMASK_EVDO_B
14211             | NETWORK_TYPE_BITMASK_EHRPD;
14212 
14213     /**
14214      * @return Modem supported radio access family bitmask
14215      *
14216      * <p>Requires permission: android.Manifest.READ_PRIVILEGED_PHONE_STATE or
14217      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
14218      *
14219      * @throws SecurityException if the caller does not have the required permission
14220      */
14221     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14222     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSupportedRadioAccessFamily()14223     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
14224         try {
14225             ITelephony telephony = getITelephony();
14226             if (telephony != null) {
14227                 return telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
14228             } else {
14229                 // This can happen when the ITelephony interface is not up yet.
14230                 return NETWORK_TYPE_BITMASK_UNKNOWN;
14231             }
14232         } catch (RemoteException ex) {
14233             // This shouldn't happen in the normal case
14234             return NETWORK_TYPE_BITMASK_UNKNOWN;
14235         } catch (NullPointerException ex) {
14236             // This could happen before phone restarts due to crashing
14237             return NETWORK_TYPE_BITMASK_UNKNOWN;
14238         }
14239     }
14240 
14241     /**
14242      * Indicates Emergency number database version is invalid.
14243      *
14244      * @hide
14245      */
14246     @SystemApi
14247     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
14248 
14249     /**
14250      * Notify Telephony for OTA emergency number database installation complete.
14251      *
14252      * <p> Requires permission:
14253      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14254      *
14255      * @hide
14256      */
14257     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14258     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
14259     @SystemApi
notifyOtaEmergencyNumberDbInstalled()14260     public void notifyOtaEmergencyNumberDbInstalled() {
14261         try {
14262             ITelephony telephony = getITelephony();
14263             if (telephony != null) {
14264                 telephony.notifyOtaEmergencyNumberDbInstalled();
14265             } else {
14266                 throw new IllegalStateException("telephony service is null.");
14267             }
14268         } catch (RemoteException ex) {
14269             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
14270             ex.rethrowAsRuntimeException();
14271         }
14272     }
14273 
14274     /**
14275      * Override the file path for OTA emergency number database in a file partition.
14276      *
14277      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
14278      *
14279      * <p> Requires permission:
14280      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
14281      *
14282      * @hide
14283      */
14284     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
14285     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
14286     @SystemApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)14287     public void updateOtaEmergencyNumberDbFilePath(
14288             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
14289         try {
14290             ITelephony telephony = getITelephony();
14291             if (telephony != null) {
14292                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
14293             } else {
14294                 throw new IllegalStateException("telephony service is null.");
14295             }
14296         } catch (RemoteException ex) {
14297             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
14298             ex.rethrowAsRuntimeException();
14299         }
14300     }
14301 
14302     /**
14303      * Reset the file path to default for OTA emergency number database in a file partition.
14304      *
14305      * <p> Requires permission:
14306      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
14307      *
14308      * @hide
14309      */
14310     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
14311     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
14312     @SystemApi
resetOtaEmergencyNumberDbFilePath()14313     public void resetOtaEmergencyNumberDbFilePath() {
14314         try {
14315             ITelephony telephony = getITelephony();
14316             if (telephony != null) {
14317                 telephony.resetOtaEmergencyNumberDbFilePath();
14318             } else {
14319                 throw new IllegalStateException("telephony service is null.");
14320             }
14321         } catch (RemoteException ex) {
14322             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
14323             ex.rethrowAsRuntimeException();
14324         }
14325     }
14326 
14327     /**
14328      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
14329      * available on the device.
14330      * <p>
14331      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
14332      *
14333      * @return {@code true} if emergency assistance is available, {@code false} otherwise
14334      *
14335      * @hide
14336      */
14337     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14338     @SuppressWarnings("AndroidFrameworkClientSidePermissionCheck")
14339     @SystemApi
isEmergencyAssistanceEnabled()14340     public boolean isEmergencyAssistanceEnabled() {
14341         mContext.enforceCallingOrSelfPermission(
14342                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
14343                 "isEmergencyAssistanceEnabled");
14344         return EMERGENCY_ASSISTANCE_ENABLED;
14345     }
14346 
14347     /**
14348      * Get the emergency number list based on current locale, sim, default, modem and network.
14349      *
14350      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
14351      * priority sources will be located at the smaller index; the priority order of sources are:
14352      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
14353      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
14354      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
14355      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
14356      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
14357      *
14358      * <p>The subscriptions which the returned list would be based on, are all the active
14359      * subscriptions, no matter which subscription could be used to create TelephonyManager.
14360      *
14361      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
14362      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
14363      *
14364      * @return Map including the keys as the active subscription IDs (Note: if there is no active
14365      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
14366      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
14367      * or throw a SecurityException if the caller does not have the permission.
14368      */
14369     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
14370     @NonNull
14371     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyNumberList()14372     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
14373         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
14374         try {
14375             ITelephony telephony = getITelephony();
14376             if (telephony != null) {
14377                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
14378                         mContext.getAttributionTag());
14379             } else {
14380                 throw new IllegalStateException("telephony service is null.");
14381             }
14382         } catch (RemoteException ex) {
14383             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
14384             ex.rethrowAsRuntimeException();
14385         }
14386         return emergencyNumberList;
14387     }
14388 
14389     /**
14390      * Get the per-category emergency number list based on current locale, sim, default, modem
14391      * and network.
14392      *
14393      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
14394      * priority sources will be located at the smaller index; the priority order of sources are:
14395      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
14396      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
14397      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
14398      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
14399      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
14400      *
14401      * <p>The subscriptions which the returned list would be based on, are all the active
14402      * subscriptions, no matter which subscription could be used to create TelephonyManager.
14403      *
14404      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
14405      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
14406      *
14407      * @param categories the emergency service categories which are the bitwise-OR combination of
14408      * the following constants:
14409      * <ol>
14410      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
14411      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
14412      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
14413      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
14414      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
14415      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
14416      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
14417      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
14418      * </ol>
14419      * @return Map including the keys as the active subscription IDs (Note: if there is no active
14420      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
14421      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
14422      * or throw a SecurityException if the caller does not have the permission.
14423      * @throws IllegalStateException if the Telephony process is not currently available.
14424      */
14425     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
14426     @NonNull
14427     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyNumberList( @mergencyServiceCategories int categories)14428     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
14429             @EmergencyServiceCategories int categories) {
14430         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
14431         try {
14432             ITelephony telephony = getITelephony();
14433             if (telephony != null) {
14434                 Map<Integer, List<EmergencyNumber>> emergencyNumberList =
14435                         telephony.getEmergencyNumberList(mContext.getOpPackageName(),
14436                                 mContext.getAttributionTag());
14437                 emergencyNumberListForCategories =
14438                         filterEmergencyNumbersByCategories(emergencyNumberList, categories);
14439             } else {
14440                 throw new IllegalStateException("telephony service is null.");
14441             }
14442         } catch (RemoteException ex) {
14443             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
14444             ex.rethrowAsRuntimeException();
14445         }
14446         return emergencyNumberListForCategories;
14447     }
14448 
14449     /**
14450      * Filter emergency numbers with categories.
14451      *
14452      * @hide
14453      */
14454     @VisibleForTesting
filterEmergencyNumbersByCategories( Map<Integer, List<EmergencyNumber>> emergencyNumberList, @EmergencyServiceCategories int categories)14455     public Map<Integer, List<EmergencyNumber>> filterEmergencyNumbersByCategories(
14456             Map<Integer, List<EmergencyNumber>> emergencyNumberList,
14457                     @EmergencyServiceCategories int categories) {
14458         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
14459         if (emergencyNumberList != null) {
14460             for (Integer subscriptionId : emergencyNumberList.keySet()) {
14461                 List<EmergencyNumber> allNumbersForSub = emergencyNumberList.get(
14462                         subscriptionId);
14463                 List<EmergencyNumber> numbersForCategoriesPerSub = new ArrayList<>();
14464                 for (EmergencyNumber number : allNumbersForSub) {
14465                     if (number.isInEmergencyServiceCategories(categories)) {
14466                         numbersForCategoriesPerSub.add(number);
14467                     }
14468                 }
14469                 emergencyNumberListForCategories.put(
14470                         subscriptionId, numbersForCategoriesPerSub);
14471             }
14472         }
14473         return emergencyNumberListForCategories;
14474     }
14475 
14476     /**
14477      * Identifies if the supplied phone number is an emergency number that matches a known
14478      * emergency number based on current locale, SIM card(s), Android database, modem, network,
14479      * or defaults.
14480      *
14481      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
14482      * numbers are not considered emergency numbers. A dialable phone number consists only
14483      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
14484      *
14485      * <p>The subscriptions which the identification would be based on, are all the active
14486      * subscriptions, no matter which subscription could be used to create TelephonyManager.
14487      *
14488      * @param number - the number to look up
14489      * @return {@code true} if the given number is an emergency number based on current locale,
14490      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
14491      * @throws IllegalStateException if the Telephony process is not currently available.
14492      */
14493     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isEmergencyNumber(@onNull String number)14494     public boolean isEmergencyNumber(@NonNull String number) {
14495         try {
14496             ITelephony telephony = getITelephony();
14497             if (telephony != null) {
14498                 return telephony.isEmergencyNumber(number, true);
14499             } else {
14500                 throw new IllegalStateException("telephony service is null.");
14501             }
14502         } catch (RemoteException ex) {
14503             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
14504             ex.rethrowAsRuntimeException();
14505         }
14506         return false;
14507     }
14508 
14509     /**
14510      * Checks if the supplied number is an emergency number based on current locale, sim, default,
14511      * modem and network.
14512      *
14513      * <p> Specifically, this method will return {@code true} if the specified number is an
14514      * emergency number, *or* if the number simply starts with the same digits as any current
14515      * emergency number.
14516      *
14517      * <p>The subscriptions which the identification would be based on, are all the active
14518      * subscriptions, no matter which subscription could be used to create TelephonyManager.
14519      *
14520      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
14521      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
14522      *
14523      * @param number - the number to look up
14524      * @return {@code true} if the given number is an emergency number or it simply starts with
14525      * the same digits of any current emergency number based on current locale, sim, modem and
14526      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
14527      * have the required permission/privileges
14528      * @throws IllegalStateException if the Telephony process is not currently available.
14529      *
14530      * @deprecated Please use {@link TelephonyManager#isEmergencyNumber(String)} instead.
14531      * @hide
14532      */
14533     @Deprecated
14534     @SystemApi
14535     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14536     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isPotentialEmergencyNumber(@onNull String number)14537     public boolean isPotentialEmergencyNumber(@NonNull String number) {
14538         try {
14539             ITelephony telephony = getITelephony();
14540             if (telephony != null) {
14541                 return telephony.isEmergencyNumber(number, false);
14542             } else {
14543                 throw new IllegalStateException("telephony service is null.");
14544             }
14545         } catch (RemoteException ex) {
14546             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
14547             ex.rethrowAsRuntimeException();
14548         }
14549         return false;
14550     }
14551 
14552     /**
14553      * Returns the emergency number database version.
14554      *
14555      * <p>Requires Permission:
14556      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
14557      *
14558      * @hide
14559      */
14560     @SystemApi
14561     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14562     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyNumberDbVersion()14563     public int getEmergencyNumberDbVersion() {
14564         try {
14565             ITelephony telephony = getITelephony();
14566             if (telephony != null) {
14567                 return telephony.getEmergencyNumberDbVersion(getSubId());
14568             }
14569         } catch (RemoteException ex) {
14570             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
14571             ex.rethrowAsRuntimeException();
14572         }
14573         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
14574     }
14575 
14576     /** @hide */
14577     @Retention(RetentionPolicy.SOURCE)
14578     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
14579             SET_OPPORTUNISTIC_SUB_SUCCESS,
14580             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
14581             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
14582             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
14583             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
14584     public @interface SetOpportunisticSubscriptionResult {}
14585 
14586     /**
14587      * No error. Operation succeeded.
14588      */
14589     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
14590 
14591     /**
14592      * Validation failed when trying to switch to preferred subscription.
14593      */
14594     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
14595 
14596     /**
14597      * The subscription is not valid. It must be an active opportunistic subscription.
14598      */
14599     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
14600 
14601     /**
14602      * The subscription is not valid. It must be an opportunistic subscription.
14603      */
14604     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
14605 
14606     /**
14607      * Subscription service happened remote exception.
14608      */
14609     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
14610 
14611 
14612     /** @hide */
14613     @Retention(RetentionPolicy.SOURCE)
14614     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
14615             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
14616             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
14617             UPDATE_AVAILABLE_NETWORKS_ABORTED,
14618             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
14619             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
14620             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
14621             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
14622             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
14623             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
14624             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
14625             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED,
14626             UPDATE_AVAILABLE_NETWORKS_SIM_PORT_NOT_AVAILABLE})
14627     public @interface UpdateAvailableNetworksResult {}
14628 
14629     /**
14630      * No error. Operation succeeded.
14631      */
14632     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
14633 
14634     /**
14635      * There is a unknown failure happened.
14636      */
14637     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
14638 
14639     /**
14640      * The request is aborted.
14641      */
14642     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
14643 
14644     /**
14645      * The parameter passed in is invalid.
14646      */
14647     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
14648 
14649     /**
14650      * No carrier privilege.
14651      */
14652     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
14653 
14654     /**
14655      * Disable modem fail.
14656      */
14657     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
14658 
14659     /**
14660      * Enable modem fail.
14661      */
14662     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
14663 
14664     /**
14665      * Carrier app does not support multiple available networks.
14666      */
14667     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
14668 
14669     /**
14670      * The subscription is not valid. It must be an opportunistic subscription.
14671      */
14672     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
14673 
14674     /**
14675      * There is no OpportunisticNetworkService.
14676      */
14677     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
14678 
14679     /**
14680      * OpportunisticNetworkService is disabled.
14681      */
14682     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
14683 
14684     /**
14685      * SIM port is not available to switch to opportunistic subscription.
14686      * @hide
14687      */
14688     public static final int UPDATE_AVAILABLE_NETWORKS_SIM_PORT_NOT_AVAILABLE = 11;
14689 
14690     /**
14691      * Set preferred opportunistic data subscription id.
14692      *
14693      * Switch internet data to preferred opportunistic data subscription id. This api
14694      * can result in lose of internet connectivity for short period of time while internet data
14695      * is handed over.
14696      * <p>Requires that the calling app has carrier privileges on both primary and
14697      * secondary subscriptions (see
14698      * {@link #hasCarrierPrivileges}), or has permission
14699      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14700      *
14701      * @param subId which opportunistic subscription
14702      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
14703      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
14704      * @param needValidation whether validation is needed before switch happens.
14705      * @param executor The executor of where the callback will execute.
14706      * @param callback Callback will be triggered once it succeeds or failed.
14707      *                 See {@link TelephonyManager.SetOpportunisticSubscriptionResult}
14708      *                 for more details. Pass null if don't care about the result.
14709      */
14710     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)14711     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
14712             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
14713         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
14714         try {
14715             IOns iOpportunisticNetworkService = getIOns();
14716             if (iOpportunisticNetworkService == null) {
14717                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
14718                     throw new IllegalStateException("Opportunistic Network Service is null");
14719                 } else {
14720                     // Let the general remote exception handling catch this.
14721                     throw new RemoteException("Null Opportunistic Network Service!");
14722                 }
14723             }
14724             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
14725                 @Override
14726                 public void onComplete(int result) {
14727                     if (executor == null || callback == null) {
14728                         return;
14729                     }
14730                     final long identity = Binder.clearCallingIdentity();
14731                     try {
14732                         executor.execute(() -> {
14733                             callback.accept(result);
14734                         });
14735                     } finally {
14736                         Binder.restoreCallingIdentity(identity);
14737                     }
14738                 }
14739             };
14740 
14741             iOpportunisticNetworkService
14742                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
14743                             pkgForDebug);
14744         } catch (RemoteException ex) {
14745             Rlog.e(TAG, "setPreferredOpportunisticDataSubscription RemoteException", ex);
14746             if (executor == null || callback == null) {
14747                 return;
14748             }
14749             runOnBackgroundThread(() -> executor.execute(() -> {
14750                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
14751                     callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
14752                 } else {
14753                     callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
14754                 }
14755             }));
14756         }
14757     }
14758 
14759     /**
14760      * Get preferred opportunistic data subscription Id
14761      *
14762      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
14763      * or has either READ_PRIVILEGED_PHONE_STATE
14764      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
14765      * @return subId preferred opportunistic subscription id or
14766      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
14767      * subscription id
14768      *
14769      */
14770     @RequiresPermission(anyOf = {
14771             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
14772             android.Manifest.permission.READ_PHONE_STATE
14773     })
14774     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getPreferredOpportunisticDataSubscription()14775     public int getPreferredOpportunisticDataSubscription() {
14776         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
14777         String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
14778         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
14779         try {
14780             IOns iOpportunisticNetworkService = getIOns();
14781             if (iOpportunisticNetworkService != null) {
14782                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
14783                         packageName, attributionTag);
14784             }
14785         } catch (RemoteException ex) {
14786             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
14787         }
14788         return subId;
14789     }
14790 
14791     /**
14792      * Update availability of a list of networks in the current location.
14793      *
14794      * This api should be called to inform OpportunisticNetwork Service about the availability
14795      * of a network at the current location. This information will be used by OpportunisticNetwork
14796      * service to enable modem stack and to attach to the network. If an empty list is passed,
14797      * it is assumed that no network is available and will result in disabling the modem stack
14798      * to save power. This api do not switch internet data once network attach is completed.
14799      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
14800      * to switch internet data after network attach is complete.
14801      * Requires that the calling app has carrier privileges on both primary and
14802      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
14803      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14804      * @param availableNetworks is a list of available network information.
14805      * @param executor The executor of where the callback will execute.
14806      * @param callback Callback will be triggered once it succeeds or failed.
14807      *
14808      */
14809     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
14810     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)14811     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
14812             @Nullable @CallbackExecutor Executor executor,
14813             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
14814         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
14815         Objects.requireNonNull(availableNetworks, "availableNetworks must not be null.");
14816         try {
14817             IOns iOpportunisticNetworkService = getIOns();
14818             if (iOpportunisticNetworkService == null) {
14819                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
14820                     throw new IllegalStateException("Opportunistic Network Service is null");
14821                 } else {
14822                     // Let the general remote exception handling catch this.
14823                     throw new RemoteException("Null Opportunistic Network Service!");
14824                 }
14825             }
14826 
14827             IUpdateAvailableNetworksCallback callbackStub =
14828                     new IUpdateAvailableNetworksCallback.Stub() {
14829                         @Override
14830                         public void onComplete(int result) {
14831                             if (executor == null || callback == null) {
14832                                 return;
14833                             }
14834                             Binder.withCleanCallingIdentity(() -> {
14835                                 executor.execute(() -> callback.accept(result));
14836                             });
14837                         }
14838                     };
14839             iOpportunisticNetworkService
14840                     .updateAvailableNetworks(availableNetworks, callbackStub, pkgForDebug);
14841         } catch (RemoteException ex) {
14842             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
14843             if (executor == null || callback == null) {
14844                 return;
14845             }
14846             runOnBackgroundThread(() -> executor.execute(() -> {
14847                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
14848                     callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
14849                 } else {
14850                     callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
14851                 }
14852             }));
14853         }
14854     }
14855 
14856     /**
14857      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
14858      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
14859      * For example, we will disable a modem when user or system believes the corresponding SIM
14860      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
14861      *
14862      * Requires that the calling app has permission
14863      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14864      * @param slotIndex which corresponding modem will operate on.
14865      * @param enable whether to enable or disable the modem stack.
14866      * @return whether the operation is successful.
14867      *
14868      * @hide
14869      */
14870     @SystemApi
14871     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableModemForSlot(int slotIndex, boolean enable)14872     public boolean enableModemForSlot(int slotIndex, boolean enable) {
14873         boolean ret = false;
14874         try {
14875             ITelephony telephony = getITelephony();
14876             if (telephony != null) {
14877                 ret = telephony.enableModemForSlot(slotIndex, enable);
14878             }
14879         } catch (RemoteException ex) {
14880             Log.e(TAG, "enableModem RemoteException", ex);
14881         }
14882         return ret;
14883     }
14884 
14885     /**
14886      * Indicates whether or not there is a modem stack enabled for the given SIM slot.
14887      *
14888      * <p>Requires Permission:
14889      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE},
14890      * READ_PRIVILEGED_PHONE_STATE or that the calling app has carrier privileges (see
14891      * {@link #hasCarrierPrivileges()}).
14892      *
14893      * @param slotIndex which slot it's checking.
14894      */
14895     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
14896     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PHONE_STATE,
14897             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
isModemEnabledForSlot(int slotIndex)14898     public boolean isModemEnabledForSlot(int slotIndex) {
14899         try {
14900             ITelephony telephony = getITelephony();
14901             if (telephony != null) {
14902                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
14903                         mContext.getAttributionTag());
14904             }
14905         } catch (RemoteException ex) {
14906             Log.e(TAG, "enableModem RemoteException", ex);
14907         }
14908         return false;
14909     }
14910 
14911     /**
14912      * Broadcast intent action for network country code changes.
14913      *
14914      * <p>
14915      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
14916      * network returned by {@link #getNetworkCountryIso()}.
14917      *
14918      * <p>There may be a delay of several minutes before reporting that no country is detected.
14919      *
14920      * @see #EXTRA_NETWORK_COUNTRY
14921      * @see #getNetworkCountryIso()
14922      */
14923     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
14924             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
14925 
14926     /**
14927      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
14928      * the country code in ISO-3166-1 alpha-2 format. This is the same country code returned by
14929      * {@link #getNetworkCountryIso()}. This might be an empty string when the country code is not
14930      * available.
14931      *
14932      * <p class="note">
14933      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
14934      */
14935     public static final String EXTRA_NETWORK_COUNTRY =
14936             "android.telephony.extra.NETWORK_COUNTRY";
14937 
14938     /**
14939      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
14940      * last known the country code in ISO-3166-1 alpha-2 format. This might be an empty string when
14941      * the country code was never available. The last known country code persists across reboot.
14942      *
14943      * <p class="note">
14944      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
14945      */
14946     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
14947             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
14948 
14949     /**
14950      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
14951      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
14952      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
14953      * policies of the carrier.
14954      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
14955      * access to the network.
14956      *
14957      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
14958      * otherwise.
14959      *
14960      * @hide
14961      */
14962     @SystemApi
14963     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14964     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)14965     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
14966         try {
14967             ITelephony service = getITelephony();
14968             if (service != null) {
14969                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
14970             }
14971         } catch (RemoteException e) {
14972             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
14973         }
14974     }
14975 
14976     /**
14977      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
14978      * Standby or Dual Active) is supported.
14979      */
14980     public static final int MULTISIM_ALLOWED = 0;
14981 
14982     /**
14983      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
14984      * Standby or Dual Active) is not supported by the hardware.
14985      */
14986     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
14987 
14988     /**
14989      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
14990      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
14991      */
14992     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
14993 
14994     /** @hide */
14995     @Retention(RetentionPolicy.SOURCE)
14996     @IntDef(prefix = {"MULTISIM_"},
14997             value = {
14998                     MULTISIM_ALLOWED,
14999                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
15000                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
15001             })
15002     public @interface IsMultiSimSupportedResult {}
15003 
15004     /**
15005      * Returns if the usage of multiple SIM cards at the same time to register on the network
15006      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
15007      *
15008      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
15009      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15010      *
15011      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
15012      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
15013      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
15014      * functionality is restricted by the carrier.
15015      */
15016     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15017     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
15018     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
15019     @IsMultiSimSupportedResult
isMultiSimSupported()15020     public int isMultiSimSupported() {
15021         if (getSupportedModemCount() < 2) {
15022             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
15023         }
15024         try {
15025             ITelephony service = getITelephony();
15026             if (service != null) {
15027                 return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
15028             }
15029         } catch (RemoteException e) {
15030             Log.e(TAG, "isMultiSimSupported RemoteException", e);
15031         }
15032         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
15033     }
15034 
15035     /**
15036      * Switch configs to enable multi-sim or switch back to single-sim
15037      * <p>Requires Permission:
15038      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
15039      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15040      *
15041      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
15042      * to single-sim
15043      *
15044      * @param numOfSims number of live SIMs we want to switch to
15045      * @throws android.os.RemoteException
15046      */
15047     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15048     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15049     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
switchMultiSimConfig(int numOfSims)15050     public void switchMultiSimConfig(int numOfSims) {
15051         try {
15052             ITelephony telephony = getITelephony();
15053             if (telephony != null) {
15054                 telephony.switchMultiSimConfig(numOfSims);
15055             }
15056         } catch (RemoteException ex) {
15057             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
15058         }
15059     }
15060 
15061     /**
15062      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
15063      * trigger device reboot.
15064      * The modem configuration change refers to switching from single SIM configuration to DSDS
15065      * or the other way around.
15066      *
15067      *  <p>Requires Permission:
15068      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
15069      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15070      *
15071      * @return {@code true} if reboot will be triggered after making changes to modem
15072      * configurations, otherwise return {@code false}.
15073      */
15074     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
15075     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
doesSwitchMultiSimConfigTriggerReboot()15076     public boolean doesSwitchMultiSimConfigTriggerReboot() {
15077         try {
15078             ITelephony service = getITelephony();
15079             if (service != null) {
15080                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
15081                         getOpPackageName(), getAttributionTag());
15082             }
15083         } catch (RemoteException e) {
15084             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
15085         }
15086         return false;
15087     }
15088 
15089     /**
15090      * Retrieve the Radio HAL Version for this device.
15091      *
15092      * Get the HAL version for the IRadio interface for test purposes.
15093      *
15094      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
15095      *
15096      * @hide
15097      *
15098      * @deprecated Use {@link #getHalVersion} instead.
15099      */
15100     @Deprecated
15101     @UnsupportedAppUsage
15102     @TestApi
getRadioHalVersion()15103     public Pair<Integer, Integer> getRadioHalVersion() {
15104         return getHalVersion(HAL_SERVICE_RADIO);
15105     }
15106 
15107     /** @hide */
15108     public static final int HAL_SERVICE_RADIO = 0;
15109 
15110     /**
15111      * HAL service type that supports the HAL APIs implementation of IRadioData
15112      * {@link RadioDataProxy}
15113      * @hide
15114      */
15115     @TestApi
15116     public static final int HAL_SERVICE_DATA = 1;
15117 
15118     /**
15119      * HAL service type that supports the HAL APIs implementation of IRadioMessaging
15120      * {@link RadioMessagingProxy}
15121      * @hide
15122      */
15123     @TestApi
15124     public static final int HAL_SERVICE_MESSAGING = 2;
15125 
15126     /**
15127      * HAL service type that supports the HAL APIs implementation of IRadioModem
15128      * {@link RadioModemProxy}
15129      * @hide
15130      */
15131     @TestApi
15132     public static final int HAL_SERVICE_MODEM = 3;
15133 
15134     /**
15135      * HAL service type that supports the HAL APIs implementation of IRadioNetwork
15136      * {@link RadioNetworkProxy}
15137      * @hide
15138      */
15139     @TestApi
15140     public static final int HAL_SERVICE_NETWORK = 4;
15141 
15142     /**
15143      * HAL service type that supports the HAL APIs implementation of IRadioSim
15144      * {@link RadioSimProxy}
15145      * @hide
15146      */
15147     @TestApi
15148     public static final int HAL_SERVICE_SIM = 5;
15149 
15150     /**
15151      * HAL service type that supports the HAL APIs implementation of IRadioVoice
15152      * {@link RadioVoiceProxy}
15153      * @hide
15154      */
15155     @TestApi
15156     public static final int HAL_SERVICE_VOICE = 6;
15157 
15158     /**
15159      * HAL service type that supports the HAL APIs implementation of IRadioIms
15160      * {@link RadioImsProxy}
15161      * @hide
15162      */
15163     @TestApi
15164     public static final int HAL_SERVICE_IMS = 7;
15165 
15166     /** @hide */
15167     @Retention(RetentionPolicy.SOURCE)
15168     @IntDef(prefix = {"HAL_SERVICE_"},
15169             value = {
15170                     HAL_SERVICE_RADIO,
15171                     HAL_SERVICE_DATA,
15172                     HAL_SERVICE_MESSAGING,
15173                     HAL_SERVICE_MODEM,
15174                     HAL_SERVICE_NETWORK,
15175                     HAL_SERVICE_SIM,
15176                     HAL_SERVICE_VOICE,
15177                     HAL_SERVICE_IMS,
15178             })
15179     public @interface HalService {}
15180 
15181     /**
15182      * The HAL Version indicating that the version is unknown or invalid.
15183      * @hide
15184      */
15185     @TestApi
15186     public static final Pair HAL_VERSION_UNKNOWN = new Pair(-1, -1);
15187 
15188     /**
15189      * The HAL Version indicating that the version is unsupported.
15190      * @hide
15191      */
15192     @TestApi
15193     public static final Pair HAL_VERSION_UNSUPPORTED = new Pair(-2, -2);
15194 
15195     /**
15196      * Retrieve the HAL Version of a specific service for this device.
15197      *
15198      * Get the HAL version for a specific HAL interface for test purposes.
15199      *
15200      * @param halService the service id to query.
15201      * @return a Pair of (major version, minor version), HAL_VERSION_UNKNOWN if unknown
15202      * or HAL_VERSION_UNSUPPORTED if unsupported.
15203      *
15204      * @hide
15205      */
15206     @TestApi
getHalVersion(@alService int halService)15207     public @NonNull Pair<Integer, Integer> getHalVersion(@HalService int halService) {
15208         try {
15209             ITelephony service = getITelephony();
15210             if (service != null) {
15211                 int version = service.getHalVersion(halService);
15212                 if (version != -1) {
15213                     return new Pair<Integer, Integer>(version / 100, version % 100);
15214                 }
15215             } else {
15216                 throw new IllegalStateException("telephony service is null.");
15217             }
15218         } catch (RemoteException e) {
15219             Log.e(TAG, "getHalVersion() RemoteException", e);
15220             e.rethrowAsRuntimeException();
15221         }
15222         return HAL_VERSION_UNKNOWN;
15223     }
15224 
15225     /**
15226      * Get the calling application status about carrier privileges for the subscription created
15227      * in TelephonyManager. Used by Telephony Module for permission checking.
15228      *
15229      * @param uid Uid to check.
15230      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
15231      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
15232      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
15233      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
15234      *
15235      * @hide
15236      */
15237     @SystemApi
15238     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15239     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPrivilegeStatus(int uid)15240     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
15241         try {
15242             ITelephony telephony = getITelephony();
15243             if (telephony != null) {
15244                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
15245             }
15246         } catch (RemoteException ex) {
15247             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
15248         }
15249         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
15250     }
15251 
15252     /**
15253      * Returns a list of APNs set as overrides by the device policy manager via
15254      * {@link #addDevicePolicyOverrideApn}.
15255      * This method must only be called from the system or phone processes.
15256      *
15257      * @param context Context to use.
15258      * @return {@link List} of APNs that have been set as overrides.
15259      * @throws {@link SecurityException} if the caller is not the system or phone process.
15260      * @hide
15261      */
15262     @TestApi
15263     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)15264     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
15265         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
15266             if (cursor == null) {
15267                 return Collections.emptyList();
15268             }
15269             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
15270             cursor.moveToPosition(-1);
15271             while (cursor.moveToNext()) {
15272                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
15273                 apnList.add(apn);
15274             }
15275             return apnList;
15276         }
15277     }
15278 
15279     /**
15280      * Used by the device policy manager to add a new override APN.
15281      * This method must only be called from the system or phone processes.
15282      *
15283      * @param context Context to use.
15284      * @param apnSetting The {@link ApnSetting} describing the new APN.
15285      * @return An integer, corresponding to a primary key in a database, that allows the caller to
15286      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
15287      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
15288      *         failed.
15289      * @throws {@link SecurityException} if the caller is not the system or phone process.
15290      * @hide
15291      */
15292     @TestApi
15293     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)15294     public int addDevicePolicyOverrideApn(@NonNull Context context,
15295             @NonNull ApnSetting apnSetting) {
15296         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
15297 
15298         int resultId = INVALID_APN_ID;
15299         if (resultUri != null) {
15300             try {
15301                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
15302             } catch (NumberFormatException e) {
15303                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
15304                         + resultUri.getLastPathSegment());
15305             }
15306         }
15307         return resultId;
15308     }
15309 
15310     /**
15311      * Used by the device policy manager to modify an override APN.
15312      * This method must only be called from the system or phone processes.
15313      *
15314      * @param context Context to use.
15315      * @param apnId The integer key of the APN to modify, as returned by
15316      *              {@link #addDevicePolicyOverrideApn}
15317      * @param apnSetting The {@link ApnSetting} describing the updated APN.
15318      * @return {@code true} if successful, {@code false} otherwise.
15319      * @throws {@link SecurityException} if the caller is not the system or phone process.
15320      * @hide
15321      */
15322     @TestApi
15323     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)15324     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
15325             @NonNull ApnSetting apnSetting) {
15326         return context.getContentResolver().update(
15327                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
15328                 apnSetting.toContentValues(), null, null) > 0;
15329     }
15330 
15331     /**
15332      * Return whether data is enabled for certain APN type. This will tell if framework will accept
15333      * corresponding network requests on a subId.
15334      *
15335      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
15336      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
15337      *
15338      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
15339      * It will return true if:
15340      *
15341      *  1) User data is turned on, or
15342      *  2) APN is un-metered for this subscription, or
15343      *  3) APN type is whitelisted. E.g. MMS is whitelisted if
15344      *  {@link #MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED} is enabled.
15345      *
15346      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
15347      * @return whether data is enabled for a apn type.
15348      *
15349      * @hide
15350      */
15351     @SystemApi
15352     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15353     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabledForApn(@pnType int apnType)15354     public boolean isDataEnabledForApn(@ApnType int apnType) {
15355         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15356         try {
15357             ITelephony service = getITelephony();
15358             if (service != null) {
15359                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
15360             }
15361         } catch (RemoteException ex) {
15362             Rlog.e(TAG, "Telephony#isDataEnabledForApn RemoteException" + ex);
15363         }
15364         return false;
15365     }
15366 
15367     /**
15368      * Whether an APN type is metered or not. It will be evaluated with the subId associated
15369      * with the TelephonyManager instance.
15370      *
15371      * @hide
15372      */
15373     @SystemApi
15374     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15375     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isApnMetered(@pnType int apnType)15376     public boolean isApnMetered(@ApnType int apnType) {
15377         try {
15378             ITelephony service = getITelephony();
15379             if (service != null) {
15380                 return service.isApnMetered(apnType, getSubId());
15381             }
15382         } catch (RemoteException ex) {
15383             Rlog.e(TAG, "Telephony#isApnMetered RemoteException" + ex);
15384         }
15385         return true;
15386     }
15387 
15388     /**
15389      * Specify which bands modem's background scan must act on.
15390      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
15391      * Otherwise, it scans all bands.
15392      *
15393      * For example, CBRS is only on LTE band 48. By specifying this band,
15394      * modem saves more power.
15395      *
15396      * @param specifiers which bands to scan.
15397      * @param executor The executor to execute the callback on
15398      * @param callback The callback that gets invoked when the radio responds to the request. Called
15399      *                 with {@code true} if the request succeeded, {@code false} otherwise.
15400      * @hide
15401      */
15402     @SystemApi
15403     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15404     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)15405     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
15406             @NonNull @CallbackExecutor Executor executor,
15407             @NonNull Consumer<Boolean> callback) {
15408         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
15409         Objects.requireNonNull(executor, "Executor must not be null.");
15410         Objects.requireNonNull(callback, "Callback must not be null.");
15411         setSystemSelectionChannelsInternal(specifiers, executor, callback);
15412     }
15413 
15414     /**
15415      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
15416      * used when the caller does not need feedback on the results of the operation.
15417      * @param specifiers which bands to scan.
15418      * @hide
15419      */
15420     @SystemApi
15421     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15422     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)15423     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
15424         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
15425         setSystemSelectionChannelsInternal(specifiers, null, null);
15426     }
15427 
15428 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)15429     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
15430             @Nullable @CallbackExecutor Executor executor,
15431             @Nullable Consumer<Boolean> callback) {
15432         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
15433             @Override
15434             public void accept(boolean result) {
15435                 final long identity = Binder.clearCallingIdentity();
15436                 try {
15437                     executor.execute(() -> callback.accept(result));
15438                 } finally {
15439                     Binder.restoreCallingIdentity(identity);
15440                 }
15441             }
15442         };
15443 
15444         try {
15445             ITelephony service = getITelephony();
15446             if (service != null) {
15447                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
15448             }
15449         } catch (RemoteException ex) {
15450             Rlog.e(TAG, "Telephony#setSystemSelectionChannels RemoteException" + ex);
15451         }
15452     }
15453 
15454     /**
15455      * Get which bands the modem's background scan is acting on, specified by
15456      * {@link #setSystemSelectionChannels}.
15457      *
15458      * <p>Requires Permission:
15459      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
15460      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15461      *
15462      * @return a list of {@link RadioAccessSpecifier}, or an empty list if no bands are specified.
15463      * @throws IllegalStateException if the Telephony process is not currently available.
15464      *
15465      * @hide
15466      */
15467     @SystemApi
15468     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15469     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSystemSelectionChannels()15470     public @NonNull List<RadioAccessSpecifier> getSystemSelectionChannels() {
15471         try {
15472             ITelephony service = getITelephony();
15473             if (service != null) {
15474                 return service.getSystemSelectionChannels(getSubId());
15475             } else {
15476                 throw new IllegalStateException("telephony service is null.");
15477             }
15478         } catch (RemoteException ex) {
15479             Rlog.e(TAG, "Telephony#getSystemSelectionChannels RemoteException" + ex);
15480         }
15481         return new ArrayList<>();
15482     }
15483 
15484     /**
15485      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
15486      *
15487      * @param mccmnc the carrier's mccmnc that you want to match
15488      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
15489      * @param mvnoMatchData the MVNO match data
15490      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
15491      * {@code false} otherwise.
15492      *
15493      * {@hide}
15494      */
15495     @SystemApi
15496     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15497     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
matchesCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)15498     public boolean matchesCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
15499             @Nullable String mvnoMatchData) {
15500         try {
15501             if (!mccmnc.equals(getSimOperator())) {
15502                 return false;
15503             }
15504             ITelephony service = getITelephony();
15505             if (service != null) {
15506                 return service.isMvnoMatched(getSlotIndex(), mvnoType, mvnoMatchData);
15507             }
15508         } catch (RemoteException ex) {
15509             Rlog.e(TAG, "Telephony#matchesCurrentSimOperator RemoteException" + ex);
15510         }
15511         return false;
15512     }
15513 
15514     /**
15515      * Callback to be used with {@link #getCallForwarding}
15516      * @hide
15517      */
15518     @SystemApi
15519     public interface CallForwardingInfoCallback {
15520         /**
15521          * Indicates that the operation was successful.
15522          */
15523         int RESULT_SUCCESS = 0;
15524 
15525         /**
15526          * Indicates that setting or retrieving the call forwarding info failed with an unknown
15527          * error.
15528          */
15529         int RESULT_ERROR_UNKNOWN = 1;
15530 
15531         /**
15532          * Indicates that call forwarding is not enabled because the recipient is not on a
15533          * Fixed Dialing Number (FDN) list.
15534          */
15535         int RESULT_ERROR_FDN_CHECK_FAILURE = 2;
15536 
15537         /**
15538          * Indicates that call forwarding is not supported on the network at this time.
15539          */
15540         int RESULT_ERROR_NOT_SUPPORTED = 3;
15541 
15542         /**
15543          * Call forwarding errors
15544          * @hide
15545          */
15546         @IntDef(prefix = { "RESULT_ERROR_" }, value = {
15547                 RESULT_ERROR_UNKNOWN,
15548                 RESULT_ERROR_NOT_SUPPORTED,
15549                 RESULT_ERROR_FDN_CHECK_FAILURE
15550         })
15551         @Retention(RetentionPolicy.SOURCE)
15552         @interface CallForwardingError{
15553         }
15554         /**
15555          * Called when the call forwarding info is successfully retrieved from the network.
15556          * @param info information about how calls are forwarded
15557          */
onCallForwardingInfoAvailable(@onNull CallForwardingInfo info)15558         void onCallForwardingInfoAvailable(@NonNull CallForwardingInfo info);
15559 
15560         /**
15561          * Called when there was an error retrieving the call forwarding information.
15562          * @param error
15563          */
onError(@allForwardingError int error)15564         void onError(@CallForwardingError int error);
15565     }
15566 
15567     /**
15568      * Gets the voice call forwarding info for a given call forwarding reason.
15569      *
15570      * This method queries the network for the currently set call forwarding configuration for the
15571      * provided call forwarding reason. When the network has provided its response, the result will
15572      * be supplied via the provided {@link Executor} on the provided
15573      * {@link CallForwardingInfoCallback}.
15574      *
15575      * @param callForwardingReason the call forwarding reason to query.
15576      * @param executor The executor on which to execute the callback once the result is ready.
15577      * @param callback The callback the results should be delivered on.
15578      *
15579      * @throws IllegalArgumentException if callForwardingReason is not any of
15580      * {@link CallForwardingInfo#REASON_UNCONDITIONAL}, {@link CallForwardingInfo#REASON_BUSY},
15581      * {@link CallForwardingInfo#REASON_NO_REPLY}, {@link CallForwardingInfo#REASON_NOT_REACHABLE},
15582      * {@link CallForwardingInfo#REASON_ALL}, or {@link CallForwardingInfo#REASON_ALL_CONDITIONAL}
15583      *
15584      * @hide
15585      */
15586     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15587     @SystemApi
15588     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallForwarding(@allForwardingReason int callForwardingReason, @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback)15589     public void getCallForwarding(@CallForwardingReason int callForwardingReason,
15590             @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback) {
15591         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
15592                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
15593             throw new IllegalArgumentException("callForwardingReason is out of range");
15594         }
15595 
15596         ICallForwardingInfoCallback internalCallback = new ICallForwardingInfoCallback.Stub() {
15597             @Override
15598             public void onCallForwardingInfoAvailable(CallForwardingInfo info) {
15599                 executor.execute(() ->
15600                         Binder.withCleanCallingIdentity(() ->
15601                                 callback.onCallForwardingInfoAvailable(info)));
15602             }
15603 
15604             @Override
15605             public void onError(int error) {
15606                 executor.execute(() ->
15607                         Binder.withCleanCallingIdentity(() ->
15608                                 callback.onError(error)));
15609             }
15610         };
15611 
15612         try {
15613             ITelephony telephony = getITelephony();
15614             if (telephony != null) {
15615                 telephony.getCallForwarding(getSubId(), callForwardingReason, internalCallback);
15616             }
15617         } catch (RemoteException ex) {
15618             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
15619             ex.rethrowAsRuntimeException();
15620         }
15621     }
15622 
15623     /**
15624      * Sets voice call forwarding behavior as described by the provided {@link CallForwardingInfo}.
15625      *
15626      * This method will enable call forwarding if the provided {@link CallForwardingInfo} returns
15627      * {@code true} from its {@link CallForwardingInfo#isEnabled()} method, and disables call
15628      * forwarding otherwise.
15629      *
15630      * If you wish to be notified about the results of this operation, provide an {@link Executor}
15631      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
15632      *
15633      * @param callForwardingInfo Info about whether calls should be forwarded and where they
15634      *                           should be forwarded to.
15635      * @param executor The executor on which the listener will be called. Must be non-null if
15636      *                 {@code listener} is non-null.
15637      * @param resultListener Asynchronous listener that'll be called when the operation completes.
15638      *                      Called with {@link CallForwardingInfoCallback#RESULT_SUCCESS} if the
15639      *                      operation succeeded and an error code from
15640      *                      {@link CallForwardingInfoCallback} it failed.
15641      *
15642      * @throws IllegalArgumentException if any of the following are true for the parameter
15643      * callForwardingInfo:
15644      * <ul>
15645      * <li>it is {@code null}.</li>
15646      * <li>{@link CallForwardingInfo#getReason()} is not any of:
15647      *     <ul>
15648      *         <li>{@link CallForwardingInfo#REASON_UNCONDITIONAL}</li>
15649      *         <li>{@link CallForwardingInfo#REASON_BUSY}</li>
15650      *         <li>{@link CallForwardingInfo#REASON_NO_REPLY}</li>
15651      *         <li>{@link CallForwardingInfo#REASON_NOT_REACHABLE}</li>
15652      *         <li>{@link CallForwardingInfo#REASON_ALL}</li>
15653      *         <li>{@link CallForwardingInfo#REASON_ALL_CONDITIONAL}</li>
15654      *     </ul>
15655      * <li>{@link CallForwardingInfo#getNumber()} returns {@code null} when enabling call
15656      * forwarding</li>
15657      * <li>{@link CallForwardingInfo#getTimeoutSeconds()} returns a non-positive value when
15658      * enabling call forwarding</li>
15659      * </ul>
15660      * @hide
15661      */
15662     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15663     @SystemApi
15664     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo, @Nullable @CallbackExecutor Executor executor, @Nullable @CallForwardingInfoCallback.CallForwardingError Consumer<Integer> resultListener)15665     public void setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo,
15666             @Nullable @CallbackExecutor Executor executor,
15667             @Nullable @CallForwardingInfoCallback.CallForwardingError
15668                     Consumer<Integer> resultListener) {
15669         if (callForwardingInfo == null) {
15670             throw new IllegalArgumentException("callForwardingInfo is null");
15671         }
15672         int callForwardingReason = callForwardingInfo.getReason();
15673         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
15674                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
15675             throw new IllegalArgumentException("callForwardingReason is out of range");
15676         }
15677         if (callForwardingInfo.isEnabled()) {
15678             if (callForwardingInfo.getNumber() == null) {
15679                 throw new IllegalArgumentException("callForwarding number is null");
15680             }
15681             if (callForwardingReason == CallForwardingInfo.REASON_NO_REPLY
15682                         && callForwardingInfo.getTimeoutSeconds() <= 0) {
15683                 throw new IllegalArgumentException("callForwarding timeout isn't positive");
15684             }
15685         }
15686         if (resultListener != null) {
15687             Objects.requireNonNull(executor);
15688         }
15689 
15690         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
15691             @Override
15692             public void accept(int result) {
15693                 executor.execute(() ->
15694                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
15695             }
15696         };
15697 
15698         try {
15699             ITelephony telephony = getITelephony();
15700             if (telephony != null) {
15701                 telephony.setCallForwarding(getSubId(), callForwardingInfo, internalCallback);
15702             }
15703         } catch (RemoteException ex) {
15704             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
15705             ex.rethrowAsRuntimeException();
15706         } catch (NullPointerException ex) {
15707             Rlog.e(TAG, "setCallForwarding NPE", ex);
15708             throw ex;
15709         }
15710     }
15711 
15712     /**
15713      * Indicates that call waiting is enabled.
15714      *
15715      * @hide
15716      */
15717     @SystemApi
15718     public static final int CALL_WAITING_STATUS_ENABLED = 1;
15719 
15720     /**
15721      * Indicates that call waiting is disabled.
15722      *
15723      * @hide
15724      */
15725     @SystemApi
15726     public static final int CALL_WAITING_STATUS_DISABLED = 2;
15727 
15728     /**
15729      * Indicates there was an unknown error retrieving the call waiting status.
15730      *
15731      * @hide
15732      */
15733     @SystemApi
15734     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
15735 
15736     /**
15737      * Indicates the call waiting is not supported on the current network.
15738      *
15739      * @hide
15740      */
15741     @SystemApi
15742     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
15743 
15744     /**
15745      * Indicates the call waiting status could not be set or queried because the Fixed Dialing
15746      * Numbers (FDN) feature is enabled.
15747      *
15748      * @hide
15749      */
15750     @SystemApi
15751     public static final int CALL_WAITING_STATUS_FDN_CHECK_FAILURE = 5;
15752 
15753     /**
15754      * @hide
15755      */
15756     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
15757             CALL_WAITING_STATUS_ENABLED,
15758             CALL_WAITING_STATUS_DISABLED,
15759             CALL_WAITING_STATUS_UNKNOWN_ERROR,
15760             CALL_WAITING_STATUS_NOT_SUPPORTED,
15761             CALL_WAITING_STATUS_FDN_CHECK_FAILURE,
15762     })
15763     @Retention(RetentionPolicy.SOURCE)
15764     public @interface CallWaitingStatus {
15765     }
15766 
15767     /**
15768      * Retrieves the call waiting status of this device from the network.
15769      *
15770      * When call waiting is enabled, an incoming call that arrives when the user is already on
15771      * an active call will be held in a waiting state while the user is notified instead of being
15772      * rejected with a busy signal.
15773      *
15774      * @param executor The executor on which the result listener will be called.
15775      * @param resultListener A {@link Consumer} that will be called with the result fetched
15776      *                       from the network. The result will be one of:
15777      *                       <ul>
15778      *                          <li>{@link #CALL_WAITING_STATUS_ENABLED}}</li>
15779      *                          <li>{@link #CALL_WAITING_STATUS_DISABLED}}</li>
15780      *                          <li>{@link #CALL_WAITING_STATUS_UNKNOWN_ERROR}}</li>
15781      *                          <li>{@link #CALL_WAITING_STATUS_NOT_SUPPORTED}}</li>
15782      *                          <li>{@link #CALL_WAITING_STATUS_FDN_CHECK_FAILURE}}</li>
15783      *                       </ul>
15784      * @hide
15785      */
15786     @SystemApi
15787     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15788     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallWaitingStatus(@onNull Executor executor, @NonNull @CallWaitingStatus Consumer<Integer> resultListener)15789     public void getCallWaitingStatus(@NonNull Executor executor,
15790             @NonNull @CallWaitingStatus Consumer<Integer> resultListener) {
15791         Objects.requireNonNull(executor);
15792         Objects.requireNonNull(resultListener);
15793 
15794         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
15795             @Override
15796             public void accept(int result) {
15797                 executor.execute(() -> Binder.withCleanCallingIdentity(
15798                         () -> resultListener.accept(result)));
15799             }
15800         };
15801 
15802         try {
15803             ITelephony telephony = getITelephony();
15804             if (telephony != null) {
15805                 telephony.getCallWaitingStatus(getSubId(), internalCallback);
15806             }
15807         } catch (RemoteException ex) {
15808             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
15809             ex.rethrowAsRuntimeException();
15810         } catch (NullPointerException ex) {
15811             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
15812             throw ex;
15813         }
15814     }
15815 
15816     /**
15817      * Sets the call waiting status of this device with the network.
15818      *
15819      * If you wish to be notified about the results of this operation, provide an {@link Executor}
15820      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
15821      *
15822      * @see #getCallWaitingStatus for a description of the call waiting functionality.
15823      *
15824      * @param enabled {@code true} to enable; {@code false} to disable.
15825      * @param executor The executor on which the listener will be called. Must be non-null if
15826      *                 {@code listener} is non-null.
15827      * @param resultListener Asynchronous listener that'll be called when the operation completes.
15828      *                       Called with the new call waiting status (either
15829      *                       {@link #CALL_WAITING_STATUS_ENABLED} or
15830      *                       {@link #CALL_WAITING_STATUS_DISABLED} if the operation succeeded and
15831      *                       {@link #CALL_WAITING_STATUS_NOT_SUPPORTED} or
15832      *                       {@link #CALL_WAITING_STATUS_UNKNOWN_ERROR} or
15833      *                       {@link #CALL_WAITING_STATUS_FDN_CHECK_FAILURE} if it failed.
15834      * @hide
15835      */
15836     @SystemApi
15837     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15838     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallWaitingEnabled(boolean enabled, @Nullable Executor executor, @Nullable Consumer<Integer> resultListener)15839     public void setCallWaitingEnabled(boolean enabled, @Nullable Executor executor,
15840             @Nullable Consumer<Integer> resultListener) {
15841         if (resultListener != null) {
15842             Objects.requireNonNull(executor);
15843         }
15844 
15845         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
15846             @Override
15847             public void accept(int result) {
15848                 executor.execute(() ->
15849                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
15850             }
15851         };
15852 
15853         try {
15854             ITelephony telephony = getITelephony();
15855             if (telephony != null) {
15856                 telephony.setCallWaitingStatus(getSubId(), enabled, internalCallback);
15857             }
15858         } catch (RemoteException ex) {
15859             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
15860             ex.rethrowAsRuntimeException();
15861         } catch (NullPointerException ex) {
15862             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
15863             throw ex;
15864         }
15865     }
15866 
15867     /**
15868      * Controls whether mobile data  on the non-default SIM is allowed during a voice call.
15869      *
15870      * This is used for allowing data on the non-default data SIM when a voice call is placed on
15871      * the non-default data SIM on DSDS devices. If this policy is disabled, users will not be able
15872      * to use mobile data via the non-default data SIM during the call, which may mean no mobile
15873      * data at all since some modem implementations disallow mobile data via the default data SIM
15874      * during voice calls.
15875      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM
15876      * during any voice calls.
15877      *
15878      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
15879      * @hide
15880      */
15881     @SystemApi
15882     public static final int MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL = 1;
15883 
15884     /**
15885      * Controls whether MMS messages bypass the user-specified "mobile data" toggle.
15886      *
15887      * When enabled, requests for connections to the MMS APN will be accepted by telephony even if
15888      * the user has turned "mobile data" off on this specific sim card. {@link #isDataEnabledForApn}
15889      * will also return true for {@link ApnSetting#TYPE_MMS}.
15890      * When disabled, the MMS APN will be governed by the same rules as all other APNs.
15891      *
15892      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
15893      * @hide
15894      */
15895     @SystemApi
15896     public static final int MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED = 2;
15897 
15898     /**
15899      * Allow switching mobile data to the non-default SIM if the non-default SIM has better
15900      * availability.
15901      *
15902      * This is used for temporarily allowing data on the non-default data SIM when on-default SIM
15903      * has better availability on DSDS devices, where better availability means strong
15904      * signal/connectivity.
15905      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM,
15906      * including during any voice calls(equivalent to enabling
15907      * {@link #MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL}).
15908      *
15909      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
15910      * @hide
15911      */
15912     @SystemApi
15913     public static final int MOBILE_DATA_POLICY_AUTO_DATA_SWITCH = 3;
15914 
15915     /**
15916      * @hide
15917      */
15918     @IntDef(prefix = { "MOBILE_DATA_POLICY_" }, value = {
15919             MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL,
15920             MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED,
15921             MOBILE_DATA_POLICY_AUTO_DATA_SWITCH,
15922     })
15923     @Retention(RetentionPolicy.SOURCE)
15924     public @interface MobileDataPolicy { }
15925 
15926     /**
15927      * Enables or disables a piece of mobile data policy.
15928      *
15929      * Enables or disables the mobile data policy specified in {@code policy}. See the detailed
15930      * description of each policy constant for what they do.
15931      *
15932      * @param policy The data policy to enable.
15933      * @param enabled Whether to enable or disable the policy.
15934      * @hide
15935      */
15936     @SystemApi
15937     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15938     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setMobileDataPolicyEnabled(@obileDataPolicy int policy, boolean enabled)15939     public void setMobileDataPolicyEnabled(@MobileDataPolicy int policy, boolean enabled) {
15940         try {
15941             ITelephony service = getITelephony();
15942             if (service != null) {
15943                 service.setMobileDataPolicyEnabled(getSubId(), policy, enabled);
15944             }
15945         } catch (RemoteException ex) {
15946             Rlog.e(TAG, "Telephony#setMobileDataPolicyEnabled RemoteException" + ex);
15947         }
15948     }
15949 
15950     /**
15951      * Fetches the status of a piece of mobile data policy.
15952      *
15953      * @param policy The data policy that you want the status for.
15954      * @return {@code true} if enabled, {@code false} otherwise.
15955      * @hide
15956      */
15957     @SystemApi
15958     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15959     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isMobileDataPolicyEnabled(@obileDataPolicy int policy)15960     public boolean isMobileDataPolicyEnabled(@MobileDataPolicy int policy) {
15961         try {
15962             ITelephony service = getITelephony();
15963             if (service != null) {
15964                 return service.isMobileDataPolicyEnabled(getSubId(), policy);
15965             }
15966         } catch (RemoteException ex) {
15967             Rlog.e(TAG, "Telephony#isMobileDataPolicyEnabled RemoteException" + ex);
15968         }
15969         return false;
15970     }
15971 
15972     /**
15973      * Indicates that the ICC PIN lock state or PIN was changed successfully.
15974      * @hide
15975      */
15976     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
15977 
15978     /**
15979      * Check whether ICC PIN lock is enabled.
15980      * This is a sync call which returns the cached PIN enabled state.
15981      *
15982      * @return {@code true} if ICC PIN lock enabled, {@code false} if disabled.
15983      * @throws SecurityException if the caller doesn't have the permission.
15984      * @throws IllegalStateException if the Telephony process is not currently available.
15985      *
15986      * <p>Requires Permission:
15987      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
15988      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15989      *
15990      * @hide
15991      */
15992     @WorkerThread
15993     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15994     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
15995     @SystemApi
isIccLockEnabled()15996     public boolean isIccLockEnabled() {
15997         try {
15998             ITelephony telephony = getITelephony();
15999             if (telephony != null) {
16000                 return telephony.isIccLockEnabled(getSubId());
16001             } else {
16002                 throw new IllegalStateException("telephony service is null.");
16003             }
16004         } catch (RemoteException e) {
16005             Log.e(TAG, "isIccLockEnabled RemoteException", e);
16006             e.rethrowFromSystemServer();
16007         }
16008         return false;
16009     }
16010 
16011     /**
16012      * Enable or disable the ICC PIN lock.
16013      *
16014      * @param enabled "true" for locked, "false" for unlocked.
16015      * @param pin needed to change the ICC PIN lock, aka. Pin1.
16016      * @return the result of enabling or disabling the ICC PIN lock.
16017      * @throws SecurityException if the caller doesn't have the permission.
16018      * @throws IllegalStateException if the Telephony process is not currently available.
16019      *
16020      * <p>Requires Permission:
16021      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
16022      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
16023      *
16024      * @hide
16025      */
16026     @SystemApi
16027     @NonNull
16028     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16029     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setIccLockEnabled(boolean enabled, @NonNull String pin)16030     public PinResult setIccLockEnabled(boolean enabled, @NonNull String pin) {
16031         checkNotNull(pin, "setIccLockEnabled pin can't be null.");
16032         try {
16033             ITelephony telephony = getITelephony();
16034             if (telephony != null) {
16035                 int result = telephony.setIccLockEnabled(getSubId(), enabled, pin);
16036                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
16037                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
16038                 } else if (result < 0) {
16039                     return PinResult.getDefaultFailedResult();
16040                 } else {
16041                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
16042                 }
16043             } else {
16044                 throw new IllegalStateException("telephony service is null.");
16045             }
16046         } catch (RemoteException e) {
16047             Log.e(TAG, "setIccLockEnabled RemoteException", e);
16048             e.rethrowFromSystemServer();
16049         }
16050         return PinResult.getDefaultFailedResult();
16051     }
16052 
16053     /**
16054      * Change the ICC lock PIN.
16055      *
16056      * @param oldPin is the old PIN
16057      * @param newPin is the new PIN
16058      * @return The result of changing the ICC lock PIN.
16059      * @throws SecurityException if the caller doesn't have the permission.
16060      * @throws IllegalStateException if the Telephony process is not currently available.
16061      *
16062      * <p>Requires Permission:
16063      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
16064      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
16065      *
16066      * @hide
16067      */
16068     @SystemApi
16069     @NonNull
16070     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16071     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
changeIccLockPin(@onNull String oldPin, @NonNull String newPin)16072     public PinResult changeIccLockPin(@NonNull String oldPin, @NonNull String newPin) {
16073         checkNotNull(oldPin, "changeIccLockPin oldPin can't be null.");
16074         checkNotNull(newPin, "changeIccLockPin newPin can't be null.");
16075         try {
16076             ITelephony telephony = getITelephony();
16077             if (telephony != null) {
16078                 int result = telephony.changeIccLockPassword(getSubId(), oldPin, newPin);
16079                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
16080                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
16081                 } else if (result < 0) {
16082                     return PinResult.getDefaultFailedResult();
16083                 } else {
16084                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
16085                 }
16086             } else {
16087                 throw new IllegalStateException("telephony service is null.");
16088             }
16089         } catch (RemoteException e) {
16090             Log.e(TAG, "changeIccLockPin RemoteException", e);
16091             e.rethrowFromSystemServer();
16092         }
16093         return PinResult.getDefaultFailedResult();
16094     }
16095 
16096     /**
16097      * Called when userActivity is signalled in the power manager.
16098      * This should only be called from system Uid.
16099      * @hide
16100      */
16101     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
notifyUserActivity()16102     public void notifyUserActivity() {
16103         try {
16104             ITelephony service = getITelephony();
16105             if (service != null) {
16106                 service.userActivity();
16107             }
16108         } catch (RemoteException e) {
16109             // one-way notification, if telephony is not available, it is okay to not throw
16110             // exception here.
16111             Log.w(TAG, "notifyUserActivity exception: " + e.getMessage());
16112         }
16113     }
16114 
16115     /**
16116      * No error. Operation succeeded.
16117      * @hide
16118      */
16119     @SystemApi
16120     public static final int ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS = 0;
16121 
16122     /**
16123      * NR Dual connectivity enablement is not supported.
16124      * @hide
16125      */
16126     @SystemApi
16127     public static final int ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED = 1;
16128 
16129     /**
16130      * Radio is not available.
16131      * @hide
16132      */
16133     @SystemApi
16134     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE = 2;
16135 
16136     /**
16137      * Internal Radio error.
16138      * @hide
16139      */
16140     @SystemApi
16141     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR = 3;
16142 
16143     /**
16144      * Currently in invalid state. Not able to process the request.
16145      * @hide
16146      */
16147     @SystemApi
16148     public static final int ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE = 4;
16149 
16150     /** @hide */
16151     @Retention(RetentionPolicy.SOURCE)
16152     @IntDef(prefix = {"ENABLE_NR_DUAL_CONNECTIVITY"}, value = {
16153             ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS,
16154             ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED,
16155             ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE,
16156             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE,
16157             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR})
16158     public @interface EnableNrDualConnectivityResult {}
16159 
16160     /**
16161      * Enable NR dual connectivity. Enabled state does not mean dual connectivity
16162      * is active. It means device is allowed to connect to both primary and secondary.
16163      *
16164      * @hide
16165      */
16166     @SystemApi
16167     public static final int NR_DUAL_CONNECTIVITY_ENABLE = 1;
16168 
16169     /**
16170      * Disable NR dual connectivity. Disabled state does not mean the secondary cell is released.
16171      * Modem will release it only if the current bearer is released to avoid radio link failure.
16172      * @hide
16173      */
16174     @SystemApi
16175     public static final int NR_DUAL_CONNECTIVITY_DISABLE = 2;
16176 
16177     /**
16178      * Disable NR dual connectivity and force the secondary cell to be released if dual connectivity
16179      * was active. This will result in radio link failure.
16180      * @hide
16181      */
16182     @SystemApi
16183     public static final int NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE = 3;
16184 
16185     /**
16186      * @hide
16187      */
16188     @IntDef(prefix = { "NR_DUAL_CONNECTIVITY_" }, value = {
16189             NR_DUAL_CONNECTIVITY_ENABLE,
16190             NR_DUAL_CONNECTIVITY_DISABLE,
16191             NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE,
16192     })
16193     @Retention(RetentionPolicy.SOURCE)
16194     public @interface NrDualConnectivityState {
16195     }
16196 
16197     /**
16198      * Enable/Disable E-UTRA-NR Dual Connectivity.
16199      *
16200      * This api is supported only if
16201      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
16202      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
16203      * returns true.
16204      * @param nrDualConnectivityState expected NR dual connectivity state
16205      * This can be passed following states
16206      * <ol>
16207      * <li>Enable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_ENABLE}
16208      * <li>Disable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_DISABLE}
16209      * <li>Disable NR dual connectivity and force secondary cell to be released
16210      * {@link #NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE}
16211      * </ol>
16212      * @return operation result.
16213      * @throws IllegalStateException if the Telephony process is not currently available.
16214      * @hide
16215      */
16216     @SystemApi
16217     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16218     @RequiresFeature(
16219             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
16220             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
setNrDualConnectivityState( @rDualConnectivityState int nrDualConnectivityState)16221     public @EnableNrDualConnectivityResult int setNrDualConnectivityState(
16222             @NrDualConnectivityState int nrDualConnectivityState) {
16223         try {
16224             ITelephony telephony = getITelephony();
16225             if (telephony != null) {
16226                 return telephony.setNrDualConnectivityState(getSubId(), nrDualConnectivityState);
16227             } else {
16228                 throw new IllegalStateException("telephony service is null.");
16229             }
16230         } catch (RemoteException ex) {
16231             Rlog.e(TAG, "setNrDualConnectivityState RemoteException", ex);
16232             ex.rethrowFromSystemServer();
16233         }
16234 
16235         return ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE;
16236     }
16237 
16238     /**
16239      * Is E-UTRA-NR Dual Connectivity enabled.
16240      * This api is supported only if
16241      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
16242      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
16243      * returns true.
16244      * @return true if dual connectivity is enabled else false. Enabled state does not mean dual
16245      * connectivity is active. It means the device is allowed to connect to both primary and
16246      * secondary cell.
16247      * @throws IllegalStateException if the Telephony process is not currently available.
16248      * @hide
16249      */
16250     @SystemApi
16251     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16252     @RequiresFeature(
16253             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
16254             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
isNrDualConnectivityEnabled()16255     public boolean isNrDualConnectivityEnabled() {
16256         try {
16257             ITelephony telephony = getITelephony();
16258             if (telephony != null) {
16259                 return telephony.isNrDualConnectivityEnabled(getSubId());
16260             } else {
16261                 throw new IllegalStateException("telephony service is null.");
16262             }
16263         } catch (RemoteException ex) {
16264             Rlog.e(TAG, "isNRDualConnectivityEnabled RemoteException", ex);
16265             ex.rethrowFromSystemServer();
16266         }
16267         return false;
16268     }
16269 
16270     private static class DeathRecipient implements IBinder.DeathRecipient {
16271         @Override
binderDied()16272         public void binderDied() {
16273             resetServiceCache();
16274         }
16275     }
16276 
16277    /**
16278     * Reset everything in the service cache; if one handle died then they are
16279     * all probably broken.
16280     * @hide
16281     */
resetServiceCache()16282     private static void resetServiceCache() {
16283         synchronized (sCacheLock) {
16284             if (sITelephony != null) {
16285                 sITelephony.asBinder().unlinkToDeath(sServiceDeath, 0);
16286                 sITelephony = null;
16287             }
16288             if (sISub != null) {
16289                 sISub.asBinder().unlinkToDeath(sServiceDeath, 0);
16290                 sISub = null;
16291                 SubscriptionManager.clearCaches();
16292             }
16293             if (sISms != null) {
16294                 sISms.asBinder().unlinkToDeath(sServiceDeath, 0);
16295                 sISms = null;
16296             }
16297             if (sIPhoneSubInfo != null) {
16298                 sIPhoneSubInfo.asBinder().unlinkToDeath(sServiceDeath, 0);
16299                 sIPhoneSubInfo = null;
16300             }
16301         }
16302     }
16303 
16304     /**
16305      * @hide
16306      */
getSubscriberInfoService()16307     static IPhoneSubInfo getSubscriberInfoService() {
16308         // Keeps cache disabled until test fixes are checked into AOSP.
16309         if (!sServiceHandleCacheEnabled) {
16310             return IPhoneSubInfo.Stub.asInterface(
16311                 TelephonyFrameworkInitializer
16312                         .getTelephonyServiceManager()
16313                         .getPhoneSubServiceRegisterer()
16314                         .get());
16315         }
16316 
16317         if (sIPhoneSubInfo == null) {
16318             IPhoneSubInfo temp = IPhoneSubInfo.Stub.asInterface(
16319                     TelephonyFrameworkInitializer
16320                         .getTelephonyServiceManager()
16321                         .getPhoneSubServiceRegisterer()
16322                         .get());
16323             synchronized (sCacheLock) {
16324                 if (sIPhoneSubInfo == null && temp != null) {
16325                     try {
16326                         sIPhoneSubInfo = temp;
16327                         sIPhoneSubInfo.asBinder().linkToDeath(sServiceDeath, 0);
16328                     } catch (Exception e) {
16329                         // something has gone horribly wrong
16330                         sIPhoneSubInfo = null;
16331                     }
16332                 }
16333             }
16334         }
16335         return sIPhoneSubInfo;
16336     }
16337 
16338    /**
16339     * @hide
16340     */
getSubscriptionService()16341     static ISub getSubscriptionService() {
16342         // Keeps cache disabled until test fixes are checked into AOSP.
16343         if (!sServiceHandleCacheEnabled) {
16344             return ISub.Stub.asInterface(
16345                     TelephonyFrameworkInitializer
16346                             .getTelephonyServiceManager()
16347                             .getSubscriptionServiceRegisterer()
16348                             .get());
16349         }
16350 
16351         if (sISub == null) {
16352             ISub temp = ISub.Stub.asInterface(
16353                     TelephonyFrameworkInitializer
16354                             .getTelephonyServiceManager()
16355                             .getSubscriptionServiceRegisterer()
16356                             .get());
16357             synchronized (sCacheLock) {
16358                 if (sISub == null && temp != null) {
16359                     try {
16360                         sISub = temp;
16361                         sISub.asBinder().linkToDeath(sServiceDeath, 0);
16362                     } catch (Exception e) {
16363                         // something has gone horribly wrong
16364                         sISub = null;
16365                     }
16366                 }
16367             }
16368         }
16369         return sISub;
16370     }
16371 
16372     /**
16373     * @hide
16374     */
getSmsService()16375     static ISms getSmsService() {
16376         // Keeps cache disabled until test fixes are checked into AOSP.
16377         if (!sServiceHandleCacheEnabled) {
16378             return ISms.Stub.asInterface(
16379                     TelephonyFrameworkInitializer
16380                             .getTelephonyServiceManager()
16381                             .getSmsServiceRegisterer()
16382                             .get());
16383         }
16384 
16385         if (sISms == null) {
16386             ISms temp = ISms.Stub.asInterface(
16387                     TelephonyFrameworkInitializer
16388                             .getTelephonyServiceManager()
16389                             .getSmsServiceRegisterer()
16390                             .get());
16391             synchronized (sCacheLock) {
16392                 if (sISms == null && temp != null) {
16393                     try {
16394                         sISms = temp;
16395                         sISms.asBinder().linkToDeath(sServiceDeath, 0);
16396                     } catch (Exception e) {
16397                         // something has gone horribly wrong
16398                         sISms = null;
16399                     }
16400                 }
16401             }
16402         }
16403         return sISms;
16404     }
16405 
16406     /**
16407      * Disables service handle caching for tests that utilize mock services.
16408      * @hide
16409      */
16410     @VisibleForTesting
disableServiceHandleCaching()16411     public static void disableServiceHandleCaching() {
16412         sServiceHandleCacheEnabled = false;
16413     }
16414 
16415     /**
16416      * Reenables service handle caching.
16417      * @hide
16418      */
16419     @VisibleForTesting
enableServiceHandleCaching()16420     public static void enableServiceHandleCaching() {
16421         sServiceHandleCacheEnabled = true;
16422     }
16423 
16424     /**
16425      * Setup sITelephony for testing.
16426      * @hide
16427      */
16428     @VisibleForTesting
setupITelephonyForTest(ITelephony telephony)16429     public static void setupITelephonyForTest(ITelephony telephony) {
16430         sITelephony = telephony;
16431     }
16432 
16433     /**
16434      * Setup sIPhoneSubInfo for testing.
16435      *
16436      * @hide
16437      */
16438     @VisibleForTesting
setupIPhoneSubInfoForTest(IPhoneSubInfo iPhoneSubInfo)16439     public static void setupIPhoneSubInfoForTest(IPhoneSubInfo iPhoneSubInfo) {
16440         synchronized (sCacheLock) {
16441             sIPhoneSubInfo = iPhoneSubInfo;
16442         }
16443     }
16444 
16445     /**
16446      * Setup sISub for testing.
16447      *
16448      * @hide
16449      */
16450     @VisibleForTesting
setupISubForTest(ISub iSub)16451     public static void setupISubForTest(ISub iSub) {
16452         synchronized (sCacheLock) {
16453             sISub = iSub;
16454         }
16455     }
16456 
16457     /**
16458      * Whether device can connect to 5G network when two SIMs are active.
16459      *
16460      * @hide TODO b/153669716: remove or make system API.
16461      */
canConnectTo5GInDsdsMode()16462     public boolean canConnectTo5GInDsdsMode() {
16463         ITelephony telephony = getITelephony();
16464         if (telephony == null) return true;
16465         try {
16466             return telephony.canConnectTo5GInDsdsMode();
16467         } catch (RemoteException ex) {
16468             return true;
16469         } catch (NullPointerException ex) {
16470             return true;
16471         }
16472     }
16473 
16474     /**
16475      * Returns a list of the equivalent home PLMNs (EF_EHPLMN) from the USIM app.
16476      *
16477      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
16478      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16479      *
16480      * @return A list of equivalent home PLMNs. Returns an empty list if EF_EHPLMN is empty or
16481      * does not exist on the SIM card.
16482      *
16483      * @throws IllegalStateException if the Telephony process is not currently available.
16484      * @throws SecurityException if the caller doesn't have the permission.
16485      *
16486      */
16487     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
16488     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getEquivalentHomePlmns()16489     public @NonNull List<String> getEquivalentHomePlmns() {
16490         try {
16491             ITelephony telephony = getITelephony();
16492             if (telephony != null) {
16493                 return telephony.getEquivalentHomePlmns(getSubId(), mContext.getOpPackageName(),
16494                         getAttributionTag());
16495             } else {
16496                 throw new IllegalStateException("telephony service is null.");
16497             }
16498         } catch (RemoteException ex) {
16499             Rlog.e(TAG, "Telephony#getEquivalentHomePlmns RemoteException" + ex);
16500         }
16501 
16502         return Collections.emptyList();
16503     }
16504 
16505     /**
16506      * Indicates whether {@link CarrierBandwidth#getSecondaryDownlinkCapacityKbps()} and
16507      * {@link CarrierBandwidth#getSecondaryUplinkCapacityKbps()} are visible.  See comments
16508      * on respective methods for more information.
16509      *
16510      * @hide
16511      */
16512     @SystemApi
16513     public static final String CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE =
16514             "CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE";
16515 
16516     /**
16517      * Indicates whether {@link #setPreferredNetworkType}, {@link
16518      * #setPreferredNetworkTypeBitmask}, {@link #setAllowedNetworkTypes} and
16519      * {@link #setAllowedNetworkTypesForReason} rely on
16520      * setAllowedNetworkTypesBitmap instead of setPreferredNetworkTypesBitmap on the radio
16521      * interface.
16522      *
16523      * @hide
16524      */
16525     @SystemApi
16526     public static final String CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK =
16527             "CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK";
16528 
16529     /**
16530      * Indicates whether {@link #setNrDualConnectivityState()} and
16531      * {@link #isNrDualConnectivityEnabled()} ()} are available.  See comments
16532      * on respective methods for more information.
16533      *
16534      * @hide
16535      */
16536     @SystemApi
16537     public static final String CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE =
16538             "CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE";
16539 
16540     /**
16541      * Indicates whether a data throttling request sent with {@link #sendThermalMitigationRequest}
16542      * is supported. See comments on {@link #sendThermalMitigationRequest} for more information.
16543      *
16544      * @hide
16545      */
16546     @SystemApi
16547     public static final String CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING =
16548             "CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING";
16549 
16550     /**
16551      * Indicates whether {@link #getNetworkSlicingConfiguration} is supported. See comments on
16552      * respective methods for more information.
16553      */
16554     public static final String CAPABILITY_SLICING_CONFIG_SUPPORTED =
16555             "CAPABILITY_SLICING_CONFIG_SUPPORTED";
16556 
16557     /**
16558      * Indicates whether PHYSICAL_CHANNEL_CONFIG HAL1.6 is supported. See comments on
16559      * respective methods for more information.
16560      *
16561      * @hide
16562      */
16563     public static final String CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED =
16564             "CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED";
16565 
16566     /**
16567      * Indicates whether modem supports handling parsed SIM phonebook records through the RIL,
16568      * both batched reads and individual writes.
16569      *
16570      * @hide
16571      */
16572     public static final String CAPABILITY_SIM_PHONEBOOK_IN_MODEM =
16573             "CAPABILITY_SIM_PHONEBOOK_IN_MODEM";
16574 
16575     /**
16576      * A list of the radio interface capability values with public valid constants.
16577      *
16578      * Here is a related list for the systemapi-only valid constants:
16579      *     CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE
16580      *     CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK
16581      *     CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE
16582      *     CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING
16583      *
16584      * @hide
16585      * TODO(b/185508047): Doc generation for mixed public/systemapi StringDefs formats badly.
16586      */
16587     @Retention(RetentionPolicy.SOURCE)
16588     @StringDef(prefix = "CAPABILITY_", value = {
16589             CAPABILITY_SLICING_CONFIG_SUPPORTED,
16590             CAPABILITY_SIM_PHONEBOOK_IN_MODEM,
16591     })
16592     public @interface RadioInterfaceCapability {}
16593 
16594     /**
16595      * Whether the device supports a given capability on the radio interface.
16596      *
16597      * If the capability is not in the set of radio interface capabilities, false is returned.
16598      *
16599      * @param capability the name of the capability to check for
16600      * @return the availability of the capability
16601      */
16602     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isRadioInterfaceCapabilitySupported( @onNull @adioInterfaceCapability String capability)16603     public boolean isRadioInterfaceCapabilitySupported(
16604             @NonNull @RadioInterfaceCapability String capability) {
16605         try {
16606             if (capability == null) return false;
16607 
16608             ITelephony telephony = getITelephony();
16609             if (telephony != null) {
16610                 return telephony.isRadioInterfaceCapabilitySupported(capability);
16611             } else {
16612                 throw new IllegalStateException("telephony service is null.");
16613             }
16614         } catch (RemoteException ex) {
16615             Rlog.e(TAG, "Telephony#isRadioInterfaceCapabilitySupported RemoteException" + ex);
16616         }
16617         return false;
16618     }
16619 
16620     /**
16621      * Indicates that the thermal mitigation request was completed successfully.
16622      *
16623      * @hide
16624      */
16625     @SystemApi
16626     public static final int THERMAL_MITIGATION_RESULT_SUCCESS = 0;
16627 
16628     /**
16629      * Indicates that the thermal mitigation request was not completed because of a modem error.
16630      *
16631      * @hide
16632      */
16633     @SystemApi
16634     public static final int THERMAL_MITIGATION_RESULT_MODEM_ERROR = 1;
16635 
16636     /**
16637      * Indicates that the thermal mitigation request was not completed because the modem is not
16638      * available.
16639      *
16640      * @hide
16641      */
16642     @SystemApi
16643     public static final int THERMAL_MITIGATION_RESULT_MODEM_NOT_AVAILABLE = 2;
16644 
16645     /**
16646      * Indicates that the thermal mitigation request could not power off the radio due to the device
16647      * either being in an active emergency voice call, device pending an emergency call, or any
16648      * other state that would disallow powering off of radio.
16649      *
16650      * @hide
16651      */
16652     @SystemApi
16653     public static final int THERMAL_MITIGATION_RESULT_INVALID_STATE = 3;
16654 
16655     /**
16656      * Indicates that the thermal mitigation request resulted an unknown error.
16657      *
16658      * @hide
16659      */
16660     @SystemApi
16661     public static final int THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR = 4;
16662 
16663     /**
16664      * Thermal mitigation request to control functionalities at modem. Thermal mitigation is done
16665      * per-subscription. Caller must be sure to bind the TelephonyManager instance to subId by
16666      * calling {@link #createForSubscriptionId(int)} if they want thermal mitigation on a specific
16667      * subscription Id. Otherwise, TelephonyManager will use the default subscription.
16668      *
16669      * Calling this does not guarantee that the thermal mitigation action requested was done to
16670      * completion. A thermal module should actively monitor the temperature levels and request an
16671      * appropriate thermal mitigation action. Every action is assumed to be done 'on top of' the
16672      * previous action, where the order of actions from least thermal mitigation to most is as
16673      * follows:
16674      * <ol>
16675      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_DATA_THROTTLING}</li>
16676      *   <ol>
16677      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING}</li>
16678      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}</li>
16679      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER}</li>
16680      *   </ol>
16681      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY}</li>
16682      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}</li>
16683      * </ol>
16684      *
16685      * So, for example, requesting {@link
16686      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will ensure that the
16687      * data on secondary carrier has been disabled before throttling on primary carrier. {@link
16688      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} will ensure that data on both
16689      * primary and secondary have been disabled. {@link
16690      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF} will ensure that voice is
16691      * disabled and that data on both primary and secondary carriers are disabled before turning
16692      * radio off. {@link DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD} is not part of the order
16693      * and can be used at any time during data throttling to hold onto the current level of data
16694      * throttling.
16695      *
16696      * <p> If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}({@link
16697      * #CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING}) returns false, then sending a {@link
16698      * DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD}, {@link
16699      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}, or {@link
16700      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will result in {@link
16701      * IllegalArgumentException} being thrown. However, on devices that do not
16702      * support data throttling, {@link
16703      * DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING} can still be requested in
16704      * order to undo the mitigations above it (i.e {@link
16705      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} and/or {@link
16706      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}). </p>
16707      *
16708      * <p> In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of
16709      * this API must also be listed in the device configuration as an authorized app in
16710      * {@code packages/services/Telephony/res/values/config.xml} under the
16711      * {@code thermal_mitigation_allowlisted_packages} key. </p>
16712      *
16713      * @param thermalMitigationRequest Thermal mitigation request. See {@link
16714      * ThermalMitigationRequest} for details.
16715      *
16716      * @throws IllegalStateException if the Telephony process is not currently available.
16717      * @throws IllegalArgumentException if the thermalMitigationRequest had invalid parameters or
16718      * if the device's modem does not support data throttling.
16719      *
16720      * @hide
16721      */
16722     @SystemApi
16723     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16724     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
16725     @ThermalMitigationResult
sendThermalMitigationRequest( @onNull ThermalMitigationRequest thermalMitigationRequest)16726     public int sendThermalMitigationRequest(
16727             @NonNull ThermalMitigationRequest thermalMitigationRequest) {
16728         try {
16729             ITelephony telephony = getITelephony();
16730             if (telephony != null) {
16731                 return telephony.sendThermalMitigationRequest(getSubId(), thermalMitigationRequest,
16732                         getOpPackageName());
16733             }
16734             throw new IllegalStateException("telephony service is null.");
16735         } catch (RemoteException ex) {
16736             Log.e(TAG, "Telephony#thermalMitigationRequest RemoteException", ex);
16737             ex.rethrowFromSystemServer();
16738         }
16739         return THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR;
16740     }
16741 
16742     /**
16743      * Registers a callback object to receive notification of changes in specified telephony states.
16744      * <p>
16745      * To register a callback, pass a {@link TelephonyCallback} which implements
16746      * interfaces of events. For example,
16747      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
16748      * {@link TelephonyCallback.ServiceStateListener}.
16749      *
16750      * At registration, and when a specified telephony state changes, the telephony manager invokes
16751      * the appropriate callback method on the callback object and passes the current (updated)
16752      * values.
16753      * <p>
16754      * Note: Be aware of the permission requirements stated on the {@link TelephonyCallback}
16755      * listeners you implement.  Your application must be granted these permissions in order to
16756      * register a {@link TelephonyCallback} which requires them; a {@link SecurityException} will be
16757      * thrown if you do not hold the required permissions for all {@link TelephonyCallback}
16758      * listeners you implement.
16759      * <p>
16760      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
16761      * applies to the given subId. Otherwise, applies to
16762      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
16763      * subIds, pass a separate callback object to each TelephonyManager object created with
16764      * {@link #createForSubscriptionId}.
16765      *
16766      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
16767      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
16768      * {@link SecurityException} will be thrown otherwise.
16769      *
16770      * This API should be used sparingly -- large numbers of callbacks will cause system
16771      * instability. If a process has registered too many callbacks without unregistering them, it
16772      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
16773      *
16774      * @param executor The executor of where the callback will execute.
16775      * @param callback The {@link TelephonyCallback} object to register. The caller should hold a
16776      * reference to the callback. The framework only holds a weak reference.
16777      */
registerTelephonyCallback(@onNull @allbackExecutor Executor executor, @NonNull TelephonyCallback callback)16778     public void registerTelephonyCallback(@NonNull @CallbackExecutor Executor executor,
16779             @NonNull TelephonyCallback callback) {
16780         registerTelephonyCallback(getLocationData(), executor, callback);
16781     }
16782 
getLocationData()16783     private int getLocationData() {
16784         boolean renounceCoarseLocation =
16785                 getRenouncedPermissions().contains(Manifest.permission.ACCESS_COARSE_LOCATION);
16786         boolean renounceFineLocation =
16787                 getRenouncedPermissions().contains(Manifest.permission.ACCESS_FINE_LOCATION);
16788         if (renounceCoarseLocation) {
16789             return INCLUDE_LOCATION_DATA_NONE;
16790         } else if (renounceFineLocation) {
16791             return INCLUDE_LOCATION_DATA_COARSE;
16792         } else {
16793             return INCLUDE_LOCATION_DATA_FINE;
16794         }
16795     }
16796 
16797     /** @hide */
16798     @Retention(RetentionPolicy.SOURCE)
16799     @IntDef(prefix = {"INCLUDE_LOCATION_DATA_"}, value = {
16800             INCLUDE_LOCATION_DATA_NONE,
16801             INCLUDE_LOCATION_DATA_COARSE,
16802             INCLUDE_LOCATION_DATA_FINE})
16803     public @interface IncludeLocationData {}
16804 
16805     /**
16806      * Specifies to not include any location related data.
16807      *
16808      * Indicates whether the caller would not like to receive
16809      * location related information which will be sent if the caller already possess
16810      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the
16811      * permissions.
16812      */
16813     public static final int INCLUDE_LOCATION_DATA_NONE = 0;
16814 
16815     /**
16816      * Include coarse location data.
16817      *
16818      * Indicates whether the caller would not like to receive
16819      * location related information which will be sent if the caller already possess
16820      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the
16821      * permissions.
16822      */
16823     public static final int INCLUDE_LOCATION_DATA_COARSE = 1;
16824 
16825     /**
16826      * Include fine location data.
16827      *
16828      * Indicates whether the caller would not like to receive
16829      * location related information which will be sent if the caller already possess
16830      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and do not renounce the
16831      * permissions.
16832      */
16833     public static final int INCLUDE_LOCATION_DATA_FINE = 2;
16834 
16835     /**
16836      * Registers a callback object to receive notification of changes in specified telephony states.
16837      * <p>
16838      * To register a callback, pass a {@link TelephonyCallback} which implements
16839      * interfaces of events. For example,
16840      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
16841      * {@link TelephonyCallback.ServiceStateListener}.
16842      *
16843      * At registration, and when a specified telephony state changes, the telephony manager invokes
16844      * the appropriate callback method on the callback object and passes the current (updated)
16845      * values.
16846      * <p>
16847      *
16848      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
16849      * applies to the given subId. Otherwise, applies to
16850      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
16851      * subIds, pass a separate callback object to each TelephonyManager object created with
16852      * {@link #createForSubscriptionId}.
16853      *
16854      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
16855      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
16856      * {@link SecurityException} will be thrown otherwise.
16857      *
16858      * This API should be used sparingly -- large numbers of callbacks will cause system
16859      * instability. If a process has registered too many callbacks without unregistering them, it
16860      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
16861      *
16862      * <p>
16863      * There's another way to renounce permissions with a custom context
16864      * {@code AttributionSource.Builder#setRenouncedPermissions(Set<String>)} but only for system
16865      * apps. To avoid confusion, calling this method supersede renouncing permissions with a
16866      * custom context.
16867      *
16868      * @param includeLocationData Specifies if the caller would like to receive
16869      * location related information.
16870      * @param executor The executor of where the callback will execute.
16871      * @param callback The {@link TelephonyCallback} object to register. The caller should hold a
16872      * reference to the callback. The framework only holds a weak reference.
16873      */
registerTelephonyCallback(@ncludeLocationData int includeLocationData, @NonNull @CallbackExecutor Executor executor, @NonNull TelephonyCallback callback)16874     public void registerTelephonyCallback(@IncludeLocationData int includeLocationData,
16875             @NonNull @CallbackExecutor Executor executor,
16876             @NonNull TelephonyCallback callback) {
16877         if (mContext == null) {
16878             throw new IllegalStateException("telephony service is null.");
16879         }
16880 
16881         if (executor == null || callback == null) {
16882             throw new IllegalArgumentException("TelephonyCallback and executor must be non-null");
16883         }
16884         mTelephonyRegistryMgr = (TelephonyRegistryManager)
16885                 mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
16886         if (mTelephonyRegistryMgr != null) {
16887             mTelephonyRegistryMgr.registerTelephonyCallback(
16888                     includeLocationData != INCLUDE_LOCATION_DATA_FINE,
16889                     includeLocationData == INCLUDE_LOCATION_DATA_NONE,
16890                     executor, mSubId, getOpPackageName(),
16891                     getAttributionTag(), callback, getITelephony() != null);
16892         } else {
16893             throw new IllegalStateException("telephony service is null.");
16894         }
16895     }
16896 
16897     /**
16898      * Unregister an existing {@link TelephonyCallback}.
16899      *
16900      * @param callback The {@link TelephonyCallback} object to unregister.
16901      */
unregisterTelephonyCallback(@onNull TelephonyCallback callback)16902     public void unregisterTelephonyCallback(@NonNull TelephonyCallback callback) {
16903 
16904         if (mContext == null) {
16905             throw new IllegalStateException("telephony service is null.");
16906         }
16907 
16908         if (callback.callback == null) {
16909             return;
16910         }
16911 
16912         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
16913         if (mTelephonyRegistryMgr != null) {
16914             mTelephonyRegistryMgr.unregisterTelephonyCallback(mSubId, getOpPackageName(),
16915                     getAttributionTag(), callback, getITelephony() != null);
16916         } else {
16917             throw new IllegalStateException("telephony service is null.");
16918         }
16919     }
16920 
16921     /** @hide */
16922     @Retention(RetentionPolicy.SOURCE)
16923     @IntDef(prefix = {"GBA_FAILURE_REASON_"}, value = {
16924             GBA_FAILURE_REASON_UNKNOWN,
16925             GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED,
16926             GBA_FAILURE_REASON_FEATURE_NOT_READY,
16927             GBA_FAILURE_REASON_NETWORK_FAILURE,
16928             GBA_FAILURE_REASON_INCORRECT_NAF_ID,
16929             GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED})
16930     public @interface AuthenticationFailureReason {}
16931 
16932     /**
16933      * GBA Authentication has failed for an unknown reason.
16934      *
16935      * <p>The caller should retry a message that failed with this response.
16936      * @hide
16937      */
16938     @SystemApi
16939     public static final int GBA_FAILURE_REASON_UNKNOWN = 0;
16940 
16941     /**
16942      * GBA Authentication is not supported by the carrier, SIM or android.
16943      *
16944      * <p>Application should use other authentication mechanisms if possible.
16945      * @hide
16946      */
16947     @SystemApi
16948     public static final int GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED = 1;
16949 
16950     /**
16951      * GBA Authentication service is not ready for use.
16952      *
16953      * <p>Application could try again at a later time.
16954      * @hide
16955      */
16956     @SystemApi
16957     public static final int GBA_FAILURE_REASON_FEATURE_NOT_READY = 2;
16958 
16959     /**
16960      * GBA Authentication has been failed by the network.
16961      * @hide
16962      */
16963     @SystemApi
16964     public static final int GBA_FAILURE_REASON_NETWORK_FAILURE = 3;
16965 
16966     /**
16967      * GBA Authentication has failed due to incorrect NAF URL.
16968      * @hide
16969      */
16970     @SystemApi
16971     public static final int GBA_FAILURE_REASON_INCORRECT_NAF_ID = 4;
16972 
16973     /**
16974      * GBA Authentication has failed due to unsupported security protocol
16975      * @hide
16976      */
16977     @SystemApi
16978     public static final int GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED = 5;
16979 
16980     /**
16981      * The callback associated with a {@link #bootstrapAuthenticationRequest()}.
16982      * @hide
16983      */
16984     @SystemApi
16985     public static class BootstrapAuthenticationCallback {
16986 
16987         /**
16988          * Invoked when the previously requested GBA keys are available (@see
16989          * bootstrapAuthenticationRequest()).
16990          * @param gbaKey Ks_NAF/Ks_ext_NAF Response
16991          * @param transactionId Bootstrapping Transaction Identifier
16992          */
onKeysAvailable(@onNull byte[] gbaKey, @NonNull String transactionId)16993         public void onKeysAvailable(@NonNull byte[] gbaKey, @NonNull String transactionId) {}
16994 
16995         /**
16996          * @param reason The reason for the authentication failure.
16997          */
onAuthenticationFailure(@uthenticationFailureReason int reason)16998         public void onAuthenticationFailure(@AuthenticationFailureReason int reason) {}
16999     }
17000 
17001     /**
17002      * Used to get the Generic Bootstrapping Architecture authentication keys
17003      * KsNAF/Ks_ext_NAF for a particular NAF as defined in 3GPP spec TS 33.220 for
17004      * the specified sub id.
17005      *
17006      * <p>Application must be prepared to wait for receiving the Gba keys through the
17007      * registered callback and not invoke the API on the main application thread.
17008      * Application also must call the api to get the fresh key every time instead
17009      * of caching the key.
17010      *
17011      * Following steps may be invoked on the API call depending on the state of the
17012      * underlying GBA implementation:
17013      * <ol>
17014      *     <li>Resolve and bind to a Gba implementation.</li>
17015      *     <li>Run bootstrapping if no valid keys are available or bootstrapping is forced.</li>
17016      *     <li>Generate the ks_NAF/ ks_Ext_NAF to be returned via the callback.</li>
17017      * </ol>
17018      *
17019      * <p> Requires Permission:
17020      * <ul>
17021      *     <li>{@link android.Manifest.permission#MODIFY_PHONE_STATE},</li>
17022      *     <li>{@link android.Manifest.permission#PERFORM_IMS_SINGLE_REGISTRATION},</li>
17023      *     <li>or that the caller has carrier privileges (see
17024      *         {@link TelephonyManager#hasCarrierPrivileges()}).</li>
17025      * </ul>
17026      * @param appType icc application type, like {@link #APPTYPE_USIM} or {@link
17027      * #APPTYPE_ISIM} or {@link#APPTYPE_UNKNOWN}
17028      * @param nafId A URI to specify Network Application Function(NAF) fully qualified domain
17029      * name (FQDN) and the selected GBA mode. The authority of the URI must contain two parts
17030      * delimited by "@" sign. The first part is the constant string "3GPP-bootstrapping" (GBA_ME),
17031      * "3GPP-bootstrapping-uicc" (GBA_ U), or "3GPP-bootstrapping-digest" (GBA_Digest).
17032      * The second part shall be the FQDN of the NAF. The scheme of the URI is not actually used
17033      * for the authentication, which may be set the same as the resource that the application is
17034      * going to access. For example, the nafId can be
17035      * "https://3GPP-bootstrapping@naf1.operator.com",
17036      * "https://3GPP-bootstrapping-uicc@naf1.operator.com",
17037      * "https://3GPP-bootstrapping-digest@naf1.operator.com",
17038      * "ftps://3GPP-bootstrapping-digest@naf1.operator.com".
17039      * @param securityProtocol Security protocol identifier between UE and NAF.  See
17040      * 3GPP TS 33.220 Annex H. Application can use
17041      * {@link UaSecurityProtocolIdentifier#createDefaultUaSpId},
17042      * {@link UaSecurityProtocolIdentifier#create3GppUaSpId},
17043      * to create the ua security protocol identifier as needed
17044      * @param forceBootStrapping true=force bootstrapping, false=do not force
17045      * bootstrapping. Bootstrapping shouldn't be forced unless the application sees
17046      * authentication errors from the server.
17047      * @param e The {@link Executor} that will be used to call the Gba callback.
17048      * @param callback A callback called on the supplied {@link Executor} that will
17049      * contain the GBA Ks_NAF/Ks_ext_NAF when available. If the NAF keys are
17050      * available and valid at the time of call and bootstrapping is not requested,
17051      * then the callback shall be invoked with the available keys.
17052      * @hide
17053      */
17054     @SystemApi
17055     @WorkerThread
17056     @RequiresPermission(anyOf = {android.Manifest.permission.MODIFY_PHONE_STATE,
17057             Manifest.permission.PERFORM_IMS_SINGLE_REGISTRATION})
17058     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
bootstrapAuthenticationRequest( @iccAppTypeExt int appType, @NonNull Uri nafId, @NonNull UaSecurityProtocolIdentifier securityProtocol, boolean forceBootStrapping, @NonNull Executor e, @NonNull BootstrapAuthenticationCallback callback)17059     public void bootstrapAuthenticationRequest(
17060             @UiccAppTypeExt int appType, @NonNull Uri nafId,
17061             @NonNull UaSecurityProtocolIdentifier securityProtocol,
17062             boolean forceBootStrapping, @NonNull Executor e,
17063             @NonNull BootstrapAuthenticationCallback callback) {
17064         try {
17065             ITelephony service = getITelephony();
17066             if (service == null) {
17067                 e.execute(() -> callback.onAuthenticationFailure(
17068                         GBA_FAILURE_REASON_FEATURE_NOT_READY));
17069                 return;
17070             }
17071             service.bootstrapAuthenticationRequest(
17072                     getSubId(), appType, nafId, securityProtocol, forceBootStrapping,
17073                     new IBootstrapAuthenticationCallback.Stub() {
17074                         @Override
17075                         public void onKeysAvailable(int token, byte[] gbaKey,
17076                                 String transactionId) {
17077                             final long identity = Binder.clearCallingIdentity();
17078                             try {
17079                                 e.execute(() -> callback.onKeysAvailable(gbaKey, transactionId));
17080                             } finally {
17081                                 Binder.restoreCallingIdentity(identity);
17082                             }
17083                         }
17084 
17085                         @Override
17086                         public void onAuthenticationFailure(int token, int reason) {
17087                             final long identity = Binder.clearCallingIdentity();
17088                             try {
17089                                 e.execute(() -> callback.onAuthenticationFailure(reason));
17090                             } finally {
17091                                 Binder.restoreCallingIdentity(identity);
17092                             }
17093                         }
17094                     });
17095         } catch (RemoteException exception) {
17096             Log.e(TAG, "Error calling ITelephony#bootstrapAuthenticationRequest", exception);
17097             e.execute(() -> callback.onAuthenticationFailure(GBA_FAILURE_REASON_FEATURE_NOT_READY));
17098         }
17099     }
17100 
17101     /**
17102      * The network type is valid or not.
17103      *
17104      * @param networkType The network type {@link NetworkType}.
17105      * @return {@code true} if valid, {@code false} otherwise.
17106      *
17107      * @hide
17108      */
isNetworkTypeValid(@etworkType int networkType)17109     public static boolean isNetworkTypeValid(@NetworkType int networkType) {
17110         return networkType >= TelephonyManager.NETWORK_TYPE_UNKNOWN &&
17111                 networkType <= TelephonyManager.NETWORK_TYPE_NR;
17112     }
17113 
17114     /**
17115      * Set a {@link SignalStrengthUpdateRequest} to receive notification when signal quality
17116      * measurements breach the specified thresholds.
17117      *
17118      * To be notified, set the signal strength update request and then register
17119      * {@link TelephonyManager#listen(PhoneStateListener, int)} with
17120      * {@link PhoneStateListener#LISTEN_SIGNAL_STRENGTHS}. The notification will arrive through
17121      * {@link PhoneStateListener#onSignalStrengthsChanged(SignalStrength)}.
17122      *
17123      * To stop receiving the notification over the specified thresholds, pass the same
17124      * {@link SignalStrengthUpdateRequest} object to
17125      * {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
17126      *
17127      * System will clean up the {@link SignalStrengthUpdateRequest} if the caller process died
17128      * without calling {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
17129      *
17130      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
17131      * applies to the given subId. Otherwise, applies to
17132      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To request for multiple subIds,
17133      * pass a request object to each TelephonyManager object created with
17134      * {@link #createForSubscriptionId}.
17135      *
17136      * <p>Requires Permission:
17137      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
17138      * or that the calling app has carrier privileges (see
17139      * {@link TelephonyManager#hasCarrierPrivileges}).
17140      *
17141      * Note that the thresholds in the request will be used on a best-effort basis; the system may
17142      * modify requests to multiplex various request sources or to optimize power consumption. The
17143      * caller should not expect to be notified with the exactly the same thresholds.
17144      *
17145      * @see #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
17146      *
17147      * @param request the SignalStrengthUpdateRequest to be set into the System
17148      *
17149      * @throws IllegalStateException if a new request is set with same subId from the same caller
17150      */
17151     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
17152     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17153     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)17154     public void setSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
17155         Objects.requireNonNull(request, "request must not be null");
17156 
17157         try {
17158             ITelephony service = getITelephony();
17159             if (service != null) {
17160                 service.setSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
17161             }
17162         } catch (RemoteException e) {
17163             Log.e(TAG, "Error calling ITelephony#setSignalStrengthUpdateRequest", e);
17164         }
17165     }
17166 
17167     /**
17168      * Clear a {@link SignalStrengthUpdateRequest} from the system.
17169      *
17170      * <p>Requires Permission:
17171      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
17172      * or that the calling app has carrier privileges (see
17173      * {@link TelephonyManager#hasCarrierPrivileges}).
17174      *
17175      * <p>If the given request was not set before, this operation is a no-op.
17176      *
17177      * @see #setSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
17178      *
17179      * @param request the SignalStrengthUpdateRequest to be cleared from the System
17180      */
17181     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
17182     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17183     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
clearSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)17184     public void clearSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
17185         Objects.requireNonNull(request, "request must not be null");
17186 
17187         try {
17188             ITelephony service = getITelephony();
17189             if (service != null) {
17190                 service.clearSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
17191             }
17192         } catch (RemoteException e) {
17193             Log.e(TAG, "Error calling ITelephony#clearSignalStrengthUpdateRequest", e);
17194         }
17195     }
17196 
17197     /**
17198      * Gets the current phone capability.
17199      *
17200      * @return the PhoneCapability which describes the data connection capability of modem.
17201      * It's used to evaluate possible phone config change, for example from single
17202      * SIM device to multi-SIM device.
17203      * @hide
17204      */
17205     @SystemApi
17206     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPhoneCapability()17207     public @NonNull PhoneCapability getPhoneCapability() {
17208         try {
17209             ITelephony telephony = getITelephony();
17210             if (telephony != null) {
17211                 return telephony.getPhoneCapability();
17212             } else {
17213                 throw new IllegalStateException("telephony service is null.");
17214             }
17215         } catch (RemoteException ex) {
17216             ex.rethrowAsRuntimeException();
17217         }
17218         if (getActiveModemCount() > 1) {
17219             return PhoneCapability.DEFAULT_DSDS_CAPABILITY;
17220         } else {
17221             return PhoneCapability.DEFAULT_SSSS_CAPABILITY;
17222         }
17223     }
17224 
17225     /**
17226      * The unattended reboot was prepared successfully.
17227      * @hide
17228      */
17229     @SystemApi
17230     public static final int PREPARE_UNATTENDED_REBOOT_SUCCESS = 0;
17231 
17232     /**
17233      * The unattended reboot was prepared, but the user will need to manually
17234      * enter the PIN code of at least one SIM card present in the device.
17235      * @hide
17236      */
17237     @SystemApi
17238     public static final int PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED = 1;
17239 
17240     /**
17241      * The unattended reboot was not prepared due to a non-recoverable error. After this error,
17242      * the client that manages the unattended reboot should not try to invoke the API again
17243      * until the next power cycle.
17244      * @hide
17245      */
17246     @SystemApi
17247     public static final int PREPARE_UNATTENDED_REBOOT_ERROR = 2;
17248 
17249     /** @hide */
17250     @Retention(RetentionPolicy.SOURCE)
17251     @IntDef(prefix = {"PREPARE_UNATTENDED_REBOOT_"},
17252             value = {
17253                     PREPARE_UNATTENDED_REBOOT_SUCCESS,
17254                     PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED,
17255                     PREPARE_UNATTENDED_REBOOT_ERROR
17256             })
17257     public @interface PrepareUnattendedRebootResult {}
17258 
17259     /**
17260      * Prepare TelephonyManager for an unattended reboot. The reboot is required to be done
17261      * shortly (e.g. within 15 seconds) after the API is invoked.
17262      *
17263      * <p>Requires Permission:
17264      *   {@link android.Manifest.permission#REBOOT}
17265      *
17266      * @return {@link #PREPARE_UNATTENDED_REBOOT_SUCCESS} in case of success.
17267      * {@link #PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED} if the device contains
17268      * at least one SIM card for which the user needs to manually enter the PIN
17269      * code after the reboot. {@link #PREPARE_UNATTENDED_REBOOT_ERROR} in case
17270      * of error.
17271      * @hide
17272      */
17273     @SystemApi
17274     @RequiresPermission(android.Manifest.permission.REBOOT)
17275     @PrepareUnattendedRebootResult
prepareForUnattendedReboot()17276     public int prepareForUnattendedReboot() {
17277         try {
17278             ITelephony service = getITelephony();
17279             if (service != null) {
17280                 return service.prepareForUnattendedReboot();
17281             }
17282         } catch (RemoteException e) {
17283             Log.e(TAG, "Telephony#prepareForUnattendedReboot RemoteException", e);
17284             e.rethrowFromSystemServer();
17285         }
17286         return PREPARE_UNATTENDED_REBOOT_ERROR;
17287     }
17288 
17289     /**
17290      * Exception that may be supplied to the callback in {@link #getNetworkSlicingConfiguration} if
17291      * something goes awry.
17292      */
17293     public static class NetworkSlicingException extends Exception {
17294         /**
17295          * Getting the current slicing configuration successfully. Used internally only.
17296          * @hide
17297          */
17298         public static final int SUCCESS = 0;
17299 
17300         /**
17301          * The system timed out waiting for a response from the Radio.
17302          * @hide
17303          */
17304         public static final int ERROR_TIMEOUT = 1;
17305 
17306         /**
17307          * The modem returned a failure.
17308          * @hide
17309          */
17310         public static final int ERROR_MODEM_ERROR = 2;
17311 
17312         /** @hide */
17313         @IntDef(prefix = {"ERROR_"}, value = {
17314                 ERROR_TIMEOUT,
17315                 ERROR_MODEM_ERROR,
17316         })
17317         @Retention(RetentionPolicy.SOURCE)
17318         public @interface NetworkSlicingError {}
17319 
17320         private final int mErrorCode;
17321 
17322         /** @hide */
NetworkSlicingException(@etworkSlicingError int errorCode)17323         public NetworkSlicingException(@NetworkSlicingError int errorCode) {
17324             mErrorCode = errorCode;
17325         }
17326 
17327         @Override
toString()17328         public String toString() {
17329             switch (mErrorCode) {
17330                 case ERROR_TIMEOUT: return "ERROR_TIMEOUT";
17331                 case ERROR_MODEM_ERROR: return "ERROR_MODEM_ERROR";
17332                 default: return "UNDEFINED";
17333             }
17334         }
17335     }
17336 
17337     /**
17338      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
17339      * system timed out waiting for a response from the Radio.
17340      */
17341     public class TimeoutException extends NetworkSlicingException {
17342         /** @hide */
TimeoutException(int errorCode)17343         public TimeoutException(int errorCode) {
17344             super(errorCode);
17345         }
17346     }
17347 
17348     /**
17349      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
17350      * modem returned a failure.
17351      */
17352     public class ModemErrorException extends NetworkSlicingException {
17353         /** @hide */
ModemErrorException(int errorCode)17354         public ModemErrorException(int errorCode) {
17355             super(errorCode);
17356         }
17357     }
17358 
17359     /** @hide */
17360     public static final String KEY_SLICING_CONFIG_HANDLE = "slicing_config_handle";
17361 
17362     /**
17363      * Request to get the current slicing configuration including URSP rules and
17364      * NSSAIs (configured, allowed and rejected).
17365      *
17366      * This method can be invoked if one of the following requirements is met:
17367      * <ul>
17368      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
17369      *     is a privileged permission that can only be granted to apps preloaded on the device.
17370      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
17371      * </ul>
17372      *
17373      * This will be invalid if the device does not support
17374      * android.telephony.TelephonyManager#CAPABILITY_SLICING_CONFIG_SUPPORTED.
17375      *
17376      * @param executor the executor on which callback will be invoked.
17377      * @param callback a callback to receive the current slicing configuration.
17378      */
17379     @RequiresFeature(
17380             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
17381             value = TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED)
17382     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
17383     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNetworkSlicingConfiguration( @onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback)17384     public void getNetworkSlicingConfiguration(
17385             @NonNull @CallbackExecutor Executor executor,
17386             @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback) {
17387         Objects.requireNonNull(executor);
17388         Objects.requireNonNull(callback);
17389 
17390         try {
17391             ITelephony telephony = getITelephony();
17392             if (telephony == null) {
17393                 throw new IllegalStateException("telephony service is null.");
17394             }
17395             telephony.getSlicingConfig(new ResultReceiver(null) {
17396                     @Override
17397                     protected void onReceiveResult(int resultCode, Bundle result) {
17398                         if (resultCode == NetworkSlicingException.ERROR_TIMEOUT) {
17399                             executor.execute(() -> callback.onError(
17400                                     new TimeoutException(resultCode)));
17401                             return;
17402                         } else if (resultCode == NetworkSlicingException.ERROR_MODEM_ERROR) {
17403                             executor.execute(() -> callback.onError(
17404                                     new ModemErrorException(resultCode)));
17405                             return;
17406                         }
17407 
17408                         NetworkSlicingConfig slicingConfig =
17409                                 result.getParcelable(KEY_SLICING_CONFIG_HANDLE, android.telephony.data.NetworkSlicingConfig.class);
17410                         executor.execute(() -> callback.onResult(slicingConfig));
17411                     }
17412             });
17413         } catch (RemoteException ex) {
17414             ex.rethrowAsRuntimeException();
17415         }
17416     }
17417 
17418     /**
17419      * A premium capability that boosts the network to allow for real-time interactive traffic
17420      * by prioritizing low latency communication.
17421      * Corresponds to {@link NetworkCapabilities#NET_CAPABILITY_PRIORITIZE_LATENCY}.
17422      */
17423     public static final int PREMIUM_CAPABILITY_PRIORITIZE_LATENCY =
17424             NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY;
17425 
17426     /**
17427      * Purchasable premium capabilities.
17428      * @hide
17429      */
17430     @Retention(RetentionPolicy.SOURCE)
17431     @IntDef(prefix = { "PREMIUM_CAPABILITY_" }, value = {
17432             PREMIUM_CAPABILITY_PRIORITIZE_LATENCY})
17433     public @interface PremiumCapability {}
17434 
17435     /**
17436      * Returns the premium capability {@link PremiumCapability} as a String.
17437      *
17438      * @param capability The premium capability.
17439      * @return The premium capability as a String.
17440      * @hide
17441      */
convertPremiumCapabilityToString(@remiumCapability int capability)17442     public static String convertPremiumCapabilityToString(@PremiumCapability int capability) {
17443         switch (capability) {
17444             case PREMIUM_CAPABILITY_PRIORITIZE_LATENCY:
17445                 return "PRIORITIZE_LATENCY";
17446             default:
17447                 return "UNKNOWN (" + capability + ")";
17448         }
17449     }
17450 
17451     /**
17452      * Check whether the given premium capability is available for purchase from the carrier.
17453      * If this is {@code true}, the capability can be purchased from the carrier using
17454      * {@link #purchasePremiumCapability(int, Executor, Consumer)}.
17455      *
17456      * @param capability The premium capability to check.
17457      * @return Whether the given premium capability is available to purchase.
17458      * @throws SecurityException if the caller does not hold permission READ_BASIC_PHONE_STATE.
17459      */
17460     @RequiresPermission(android.Manifest.permission.READ_BASIC_PHONE_STATE)
isPremiumCapabilityAvailableForPurchase(@remiumCapability int capability)17461     public boolean isPremiumCapabilityAvailableForPurchase(@PremiumCapability int capability) {
17462         try {
17463             ITelephony telephony = getITelephony();
17464             if (telephony == null) {
17465                 throw new IllegalStateException("telephony service is null.");
17466             }
17467             return telephony.isPremiumCapabilityAvailableForPurchase(capability, getSubId());
17468         } catch (RemoteException ex) {
17469             ex.rethrowAsRuntimeException();
17470         }
17471         return false;
17472     }
17473 
17474     /**
17475      * Purchase premium capability request was successful.
17476      * Once the purchase result is successful, the network must set up a slicing configuration
17477      * for the purchased premium capability within the timeout specified by
17478      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NETWORK_SETUP_TIME_MILLIS_LONG}.
17479      * During the setup time, subsequent attempts will return
17480      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP}.
17481      * After setup is complete, subsequent attempts will return
17482      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED} until the boost expires.
17483      * The expiry time is determined by the type or duration of boost purchased from the carrier,
17484      * provided at {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_PURCHASE_URL_STRING}.
17485      */
17486     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS = 1;
17487 
17488     /**
17489      * Purchase premium capability failed because the request is throttled.
17490      * If purchasing premium capabilities is throttled, it will be for the amount of time
17491      * specified by {@link CarrierConfigManager
17492      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}.
17493      * If displaying the performance boost notification is throttled, it will be for the amount of
17494      * time specified by {@link CarrierConfigManager
17495      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}.
17496      * We will show the performance boost notification to the user up to the daily and monthly
17497      * maximum number of times specified by
17498      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_MAXIMUM_DAILY_NOTIFICATION_COUNT_INT} and
17499      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_MAXIMUM_MONTHLY_NOTIFICATION_COUNT_INT}.
17500      * Subsequent attempts will return the same error until the request is no longer throttled
17501      * or throttling conditions change.
17502      */
17503     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED = 2;
17504 
17505     /**
17506      * Purchase premium capability failed because it is already purchased and available.
17507      * Subsequent attempts will return the same error until the performance boost expires.
17508      */
17509     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED = 3;
17510 
17511     /**
17512      * Purchase premium capability failed because a request was already made and is in progress.
17513      * This may have been requested by either the same app or another app.
17514      * Subsequent attempts will return the same error until the previous request completes.
17515      */
17516     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS = 4;
17517 
17518     /**
17519      * Purchase premium capability failed because the requesting application is not in the
17520      * foreground. Subsequent attempts will return the same error until the requesting application
17521      * moves to the foreground.
17522      */
17523     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND = 5;
17524 
17525     /**
17526      * Purchase premium capability failed because the user canceled the operation.
17527      * Subsequent attempts will be throttled for the amount of time specified by
17528      * {@link CarrierConfigManager
17529      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
17530      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
17531      */
17532     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED = 6;
17533 
17534     /**
17535      * Purchase premium capability failed because the carrier disabled or does not support
17536      * the capability, as specified in
17537      * {@link CarrierConfigManager#KEY_SUPPORTED_PREMIUM_CAPABILITIES_INT_ARRAY}.
17538      * Subsequent attempts will return the same error until the carrier enables the feature.
17539      */
17540     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED = 7;
17541 
17542     /**
17543      * Purchase premium capability failed because the carrier app did not indicate success.
17544      * Subsequent attempts will be throttled for the amount of time specified by
17545      * {@link CarrierConfigManager
17546      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
17547      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
17548      */
17549     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR = 8;
17550 
17551     /**
17552      * Purchase premium capability failed because we did not receive a response from the user
17553      * for the performance boost notification within the time specified by
17554      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NOTIFICATION_DISPLAY_TIMEOUT_MILLIS_LONG}.
17555      * The performance boost notification will be automatically dismissed and subsequent attempts
17556      * will be throttled for the amount of time specified by
17557      * {@link CarrierConfigManager
17558      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
17559      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
17560      */
17561     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT = 9;
17562 
17563     /**
17564      * Purchase premium capability failed because the device does not support the feature.
17565      * Subsequent attempts will return the same error.
17566      */
17567     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED = 10;
17568 
17569     /**
17570      * Purchase premium capability failed because the telephony service is unavailable
17571      * or there was an error in the phone process.
17572      * Subsequent attempts will return the same error until request conditions are satisfied.
17573      */
17574     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED = 11;
17575 
17576     /**
17577      * Purchase premium capability failed because the network is not available.
17578      * Subsequent attempts will return the same error until network conditions change.
17579      */
17580     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE = 12;
17581 
17582     /**
17583      * Purchase premium capability failed because the entitlement check failed.
17584      * Subsequent attempts will be throttled for the amount of time specified by
17585      * {@link CarrierConfigManager
17586      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
17587      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
17588      * Throttling will be reevaluated when the network is no longer congested.
17589      */
17590     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED = 13;
17591 
17592     /**
17593      * Purchase premium capability failed because the request was not made on the default data
17594      * subscription, indicated by {@link SubscriptionManager#getDefaultDataSubscriptionId()}.
17595      * Subsequent attempts will return the same error until the request is made on the default
17596      * data subscription.
17597      */
17598     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION = 14;
17599 
17600     /**
17601      * Purchase premium capability was successful and is waiting for the network to setup the
17602      * slicing configuration. If the setup is complete within the time specified by
17603      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NETWORK_SETUP_TIME_MILLIS_LONG},
17604      * subsequent requests will return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED}
17605      * until the purchase expires. If the setup is not complete within the time specified above,
17606      * applications can request the premium capability again.
17607      */
17608     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP = 15;
17609 
17610     /**
17611      * Purchase premium capability failed because the user disabled the feature.
17612      * Subsequent attempts will be throttled for the amount of time specified by
17613      * {@link CarrierConfigManager
17614      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
17615      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
17616      * @hide
17617      */
17618     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_DISABLED = 16;
17619 
17620     /**
17621      * Results of the purchase premium capability request.
17622      * @hide
17623      */
17624     @Retention(RetentionPolicy.SOURCE)
17625     @IntDef(prefix = { "PURCHASE_PREMIUM_CAPABILITY_RESULT_" }, value = {
17626             PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS,
17627             PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED,
17628             PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED,
17629             PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS,
17630             PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND,
17631             PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED,
17632             PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED,
17633             PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR,
17634             PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT,
17635             PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED,
17636             PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE,
17637             PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED,
17638             PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION,
17639             PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP,
17640             PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_DISABLED})
17641     public @interface PurchasePremiumCapabilityResult {}
17642 
17643     /**
17644      * Returns the purchase result {@link PurchasePremiumCapabilityResult} as a String.
17645      *
17646      * @param result The purchase premium capability result.
17647      * @return The purchase result as a String.
17648      * @hide
17649      */
convertPurchaseResultToString( @urchasePremiumCapabilityResult int result)17650     public static String convertPurchaseResultToString(
17651             @PurchasePremiumCapabilityResult int result) {
17652         switch (result) {
17653             case PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS:
17654                 return "SUCCESS";
17655             case PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED:
17656                 return "THROTTLED";
17657             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED:
17658                 return "ALREADY_PURCHASED";
17659             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS:
17660                 return "ALREADY_IN_PROGRESS";
17661             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND:
17662                 return "NOT_FOREGROUND";
17663             case PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED:
17664                 return "USER_CANCELED";
17665             case PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED:
17666                 return "CARRIER_DISABLED";
17667             case PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR:
17668                 return "CARRIER_ERROR";
17669             case PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT:
17670                 return "TIMEOUT";
17671             case PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED:
17672                 return "FEATURE_NOT_SUPPORTED";
17673             case PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED:
17674                 return "REQUEST_FAILED";
17675             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE:
17676                 return "NETWORK_NOT_AVAILABLE";
17677             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED:
17678                 return "ENTITLEMENT_CHECK_FAILED";
17679             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION:
17680                 return "NOT_DEFAULT_DATA_SUBSCRIPTION";
17681             case PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP:
17682                 return "PENDING_NETWORK_SETUP";
17683             default:
17684                 return "UNKNOWN (" + result + ")";
17685         }
17686     }
17687 
17688     /**
17689      * Purchase the given premium capability from the carrier.
17690      * This requires user action to purchase the boost from the carrier.
17691      * If this returns {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS} or
17692      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED}, applications can request
17693      * the premium capability via {@link ConnectivityManager#requestNetwork}.
17694      *
17695      * @param capability The premium capability to purchase.
17696      * @param executor The callback executor for the response.
17697      * @param callback The result of the purchase request.
17698      *                 One of {@link PurchasePremiumCapabilityResult}.
17699      * @throws SecurityException if the caller does not hold permissions
17700      *         READ_BASIC_PHONE_STATE or INTERNET.
17701      * @see #isPremiumCapabilityAvailableForPurchase(int) to check whether the capability is valid.
17702      */
17703     @RequiresPermission(allOf = {android.Manifest.permission.READ_BASIC_PHONE_STATE,
17704             android.Manifest.permission.INTERNET})
purchasePremiumCapability(@remiumCapability int capability, @NonNull @CallbackExecutor Executor executor, @NonNull @PurchasePremiumCapabilityResult Consumer<Integer> callback)17705     public void purchasePremiumCapability(@PremiumCapability int capability,
17706             @NonNull @CallbackExecutor Executor executor,
17707             @NonNull @PurchasePremiumCapabilityResult Consumer<Integer> callback) {
17708         Objects.requireNonNull(executor);
17709         Objects.requireNonNull(callback);
17710 
17711         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
17712             @Override
17713             public void accept(int result) {
17714                 executor.execute(() -> callback.accept(result));
17715             }
17716         };
17717 
17718         try {
17719             ITelephony telephony = getITelephony();
17720             if (telephony == null) {
17721                 callback.accept(PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED);
17722                 return;
17723             }
17724             telephony.purchasePremiumCapability(capability, internalCallback, getSubId());
17725         } catch (RemoteException ex) {
17726             callback.accept(PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED);
17727         }
17728     }
17729 
17730     /**
17731      * Get last known cell identity.
17732      * Require {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
17733      * com.android.phone.permission.ACCESS_LAST_KNOWN_CELL_ID, otherwise throws SecurityException.
17734      * If there is current registered network this value will be same as the registered cell
17735      * identity. If the device goes out of service the previous cell identity is cached and
17736      * will be returned. If the cache age of the Cell identity is more than 24 hours
17737      * it will be cleared and null will be returned.
17738      * @return last known cell identity {@CellIdentity}.
17739      * @hide
17740      */
17741     @RequiresPermission(allOf = {Manifest.permission.ACCESS_FINE_LOCATION,
17742             "com.android.phone.permission.ACCESS_LAST_KNOWN_CELL_ID"})
getLastKnownCellIdentity()17743     public @Nullable CellIdentity getLastKnownCellIdentity() {
17744         try {
17745             ITelephony telephony = getITelephony();
17746             if (telephony == null) {
17747                 throw new IllegalStateException("telephony service is null.");
17748             }
17749             return telephony.getLastKnownCellIdentity(getSubId(), getOpPackageName(),
17750                     getAttributionTag());
17751         } catch (RemoteException ex) {
17752             ex.rethrowAsRuntimeException();
17753         }
17754         return null;
17755     }
17756 
17757     /**
17758      * Callbacks to listen for when the set of packages with carrier privileges for a SIM changes.
17759      *
17760      * <p>Of note, when multiple callbacks are registered, they may be triggered one after another.
17761      * The ordering of them is not guaranteed and thus should not be depend on.
17762      *
17763      * @hide
17764      */
17765     @SystemApi
17766     public interface CarrierPrivilegesCallback {
17767         /**
17768          * Called when the set of packages with carrier privileges has changed.
17769          *
17770          * <p>Of note, this callback will <b>not</b> be fired if a carrier triggers a SIM profile
17771          * switch and the same set of packages remains privileged after the switch.
17772          *
17773          * <p>At registration, the callback will receive the current set of privileged packages.
17774          *
17775          * @param privilegedPackageNames The updated set of package names that have carrier
17776          *                               privileges
17777          * @param privilegedUids         The updated set of UIDs that have carrier privileges
17778          */
onCarrierPrivilegesChanged( @onNull Set<String> privilegedPackageNames, @NonNull Set<Integer> privilegedUids)17779         void onCarrierPrivilegesChanged(
17780                 @NonNull Set<String> privilegedPackageNames, @NonNull Set<Integer> privilegedUids);
17781 
17782         /**
17783          * Called when the {@link CarrierService} for the current user profile has changed.
17784          *
17785          * <p>This method does nothing by default. Clients that are interested in the carrier
17786          * service change should override this method to get package name and UID info.
17787          *
17788          * <p>At registration, the callback will receive the current carrier service info.
17789          *
17790          * <p>Of note, this callback will <b>not</b> be fired if a carrier triggers a SIM profile
17791          * switch and the same carrier service remains after switch.
17792          *
17793          * @param carrierServicePackageName package name of the {@link CarrierService}. May be
17794          *                                  {@code null} when no carrier service is detected.
17795          * @param carrierServiceUid         UID of the {@link CarrierService}. May be
17796          *                                  {@link android.os.Process#INVALID_UID} if no carrier
17797          *                                  service is detected.
17798          */
onCarrierServiceChanged( @ullable String carrierServicePackageName, int carrierServiceUid)17799         default void onCarrierServiceChanged(
17800                 @Nullable String carrierServicePackageName, int carrierServiceUid) {
17801             // do nothing by default
17802         }
17803     }
17804 
17805     /**
17806      * Sets a voice service state override from telecom based on the current {@link PhoneAccount}s
17807      * registered. See {@link PhoneAccount#CAPABILITY_VOICE_CALLING_AVAILABLE}.
17808      *
17809      * <p>Currently, this API is only called to indicate over-the-top voice calling capability of
17810      * the SIM call manager, which will get merged into {@link ServiceState#getState} and propagated
17811      * to interested callers via {@link #getServiceState} and {@link
17812      * TelephonyCallback.ServiceStateListener}.
17813      *
17814      * <p>If callers are truly interested in the actual device <-> tower connection status and not
17815      * an overall "device can make voice calls" boolean, they can use {@link
17816      * ServiceState#getNetworkRegistrationInfo} to check CS registration state.
17817      *
17818      * <p>TODO(b/215240050) In the future, this API will be removed and replaced with a new superset
17819      * API to disentangle the "true" {@link ServiceState} meaning of "this is the connection status
17820      * to the tower" from IMS registration state and over-the-top voice calling capabilities.
17821      *
17822      * @hide
17823      */
17824     @TestApi
17825     @RequiresPermission(Manifest.permission.BIND_TELECOM_CONNECTION_SERVICE)
setVoiceServiceStateOverride(boolean hasService)17826     public void setVoiceServiceStateOverride(boolean hasService) {
17827         try {
17828             ITelephony telephony = getITelephony();
17829             if (telephony == null) {
17830                 throw new IllegalStateException("Telephony service is null");
17831             }
17832             telephony.setVoiceServiceStateOverride(getSubId(), hasService, getOpPackageName());
17833         } catch (RemoteException ex) {
17834             ex.rethrowAsRuntimeException();
17835         }
17836     }
17837 
17838     /**
17839      * Registers a {@link CarrierPrivilegesCallback} on the given {@code logicalSlotIndex} to
17840      * receive callbacks when the set of packages with carrier privileges changes. The callback will
17841      * immediately be called with the latest state.
17842      *
17843      * @param logicalSlotIndex The SIM slot to listen on
17844      * @param executor The executor where {@code callback} will be invoked
17845      * @param callback The callback to register
17846      * @hide
17847      */
17848     @SystemApi
17849     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
registerCarrierPrivilegesCallback( int logicalSlotIndex, @NonNull @CallbackExecutor Executor executor, @NonNull CarrierPrivilegesCallback callback)17850     public void registerCarrierPrivilegesCallback(
17851             int logicalSlotIndex,
17852             @NonNull @CallbackExecutor Executor executor,
17853             @NonNull CarrierPrivilegesCallback callback) {
17854         if (mContext == null) {
17855             throw new IllegalStateException("Telephony service is null");
17856         } else if (executor == null || callback == null) {
17857             throw new IllegalArgumentException(
17858                     "CarrierPrivilegesCallback and executor must be non-null");
17859         }
17860         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
17861         if (mTelephonyRegistryMgr == null) {
17862             throw new IllegalStateException("Telephony registry service is null");
17863         }
17864         mTelephonyRegistryMgr.addCarrierPrivilegesCallback(logicalSlotIndex, executor, callback);
17865     }
17866 
17867     /**
17868      * Unregisters an existing {@link CarrierPrivilegesCallback}.
17869      *
17870      * @hide
17871      */
17872     @SystemApi
17873     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
unregisterCarrierPrivilegesCallback(@onNull CarrierPrivilegesCallback callback)17874     public void unregisterCarrierPrivilegesCallback(@NonNull CarrierPrivilegesCallback callback) {
17875         if (mContext == null) {
17876             throw new IllegalStateException("Telephony service is null");
17877         } else if (callback == null) {
17878             throw new IllegalArgumentException("CarrierPrivilegesCallback must be non-null");
17879         }
17880         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
17881         if (mTelephonyRegistryMgr == null) {
17882             throw new IllegalStateException("Telephony registry service is null");
17883         }
17884         mTelephonyRegistryMgr.removeCarrierPrivilegesCallback(callback);
17885     }
17886 
17887     /**
17888      * set removable eSIM as default eUICC.
17889      *
17890      * @hide
17891      */
17892     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
17893     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
setRemovableEsimAsDefaultEuicc(boolean isDefault)17894     public void setRemovableEsimAsDefaultEuicc(boolean isDefault) {
17895         try {
17896             ITelephony telephony = getITelephony();
17897             if (telephony != null) {
17898                 telephony.setRemovableEsimAsDefaultEuicc(isDefault, getOpPackageName());
17899             }
17900         } catch (RemoteException e) {
17901             Log.e(TAG, "Error in setRemovableEsimAsDefault: " + e);
17902         }
17903     }
17904 
17905     /**
17906      * Returns whether the removable eSIM is default eUICC or not.
17907      *
17908      * @hide
17909      */
17910     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
17911     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
isRemovableEsimDefaultEuicc()17912     public boolean isRemovableEsimDefaultEuicc() {
17913         try {
17914             ITelephony telephony = getITelephony();
17915             if (telephony != null) {
17916                 return telephony.isRemovableEsimDefaultEuicc(getOpPackageName());
17917             }
17918         } catch (RemoteException e) {
17919             Log.e(TAG, "Error in isRemovableEsimDefaultEuicc: " + e);
17920         }
17921         return false;
17922     }
17923 
17924     /**
17925      * Returns a constant indicating the state of sim for the slot index.
17926      *
17927      * @param slotIndex Logical SIM slot index.
17928      *
17929      * @see TelephonyManager.SimState
17930      *
17931      * @hide
17932      */
17933     @SimState
getSimStateForSlotIndex(int slotIndex)17934     public static int getSimStateForSlotIndex(int slotIndex) {
17935         try {
17936             ITelephony telephony = ITelephony.Stub.asInterface(
17937                     TelephonyFrameworkInitializer
17938                             .getTelephonyServiceManager()
17939                             .getTelephonyServiceRegisterer()
17940                             .get());
17941             if (telephony != null) {
17942                 return telephony.getSimStateForSlotIndex(slotIndex);
17943             }
17944         } catch (RemoteException e) {
17945             Log.e(TAG, "Error in getSimStateForSlotIndex: " + e);
17946         }
17947         return TelephonyManager.SIM_STATE_UNKNOWN;
17948     }
17949 
17950     /**
17951      * Captures parameters for collection of emergency
17952      * call diagnostic data
17953      * @hide
17954      */
17955     public static class EmergencyCallDiagnosticParams {
17956 
17957        private boolean mCollectTelecomDumpSys;
17958        private boolean mCollectTelephonyDumpsys;
17959        private boolean mCollectLogcat;
17960 
17961         //logcat lines with this time or greater are collected
17962         //how much is collected is dependent on internal implementation.
17963         //Time represented as milliseconds since January 1, 1970 UTC
17964         private long mLogcatStartTimeMillis;
17965 
17966 
isTelecomDumpSysCollectionEnabled()17967         public boolean isTelecomDumpSysCollectionEnabled() {
17968             return mCollectTelecomDumpSys;
17969         }
17970 
setTelecomDumpSysCollection(boolean collectTelecomDumpSys)17971         public void setTelecomDumpSysCollection(boolean collectTelecomDumpSys) {
17972             mCollectTelecomDumpSys = collectTelecomDumpSys;
17973         }
17974 
isTelephonyDumpSysCollectionEnabled()17975         public boolean isTelephonyDumpSysCollectionEnabled() {
17976             return mCollectTelephonyDumpsys;
17977         }
17978 
setTelephonyDumpSysCollection(boolean collectTelephonyDumpsys)17979         public void setTelephonyDumpSysCollection(boolean collectTelephonyDumpsys) {
17980             mCollectTelephonyDumpsys = collectTelephonyDumpsys;
17981         }
17982 
isLogcatCollectionEnabled()17983         public boolean isLogcatCollectionEnabled() {
17984             return mCollectLogcat;
17985         }
17986 
getLogcatStartTime()17987         public long getLogcatStartTime()
17988         {
17989             return mLogcatStartTimeMillis;
17990         }
17991 
setLogcatCollection(boolean collectLogcat, long startTimeMillis)17992         public void setLogcatCollection(boolean collectLogcat, long startTimeMillis) {
17993             mCollectLogcat = collectLogcat;
17994             if(mCollectLogcat)
17995             {
17996                 mLogcatStartTimeMillis = startTimeMillis;
17997             }
17998         }
17999 
18000         @Override
toString()18001         public String toString() {
18002             return "EmergencyCallDiagnosticParams{" +
18003                     "mCollectTelecomDumpSys=" + mCollectTelecomDumpSys +
18004                     ", mCollectTelephonyDumpsys=" + mCollectTelephonyDumpsys +
18005                     ", mCollectLogcat=" + mCollectLogcat +
18006                     ", mLogcatStartTimeMillis=" + mLogcatStartTimeMillis +
18007                     '}';
18008         }
18009     }
18010 
18011     /**
18012      * Request telephony to persist state for debugging emergency call failures.
18013      *
18014      * @param dropboxTag Tag to use when persisting data to dropbox service.
18015      *
18016      * @see params Parameters controlling what is collected
18017      *
18018      * @hide
18019      */
18020     @RequiresPermission(android.Manifest.permission.DUMP)
persistEmergencyCallDiagnosticData(@onNull String dropboxTag, @NonNull EmergencyCallDiagnosticParams params)18021     public void persistEmergencyCallDiagnosticData(@NonNull String dropboxTag,
18022             @NonNull EmergencyCallDiagnosticParams params) {
18023         try {
18024             ITelephony telephony = ITelephony.Stub.asInterface(
18025                     TelephonyFrameworkInitializer
18026                             .getTelephonyServiceManager()
18027                             .getTelephonyServiceRegisterer()
18028                             .get());
18029             if (telephony != null) {
18030                 telephony.persistEmergencyCallDiagnosticData(dropboxTag,
18031                         params.isLogcatCollectionEnabled(),
18032                         params.getLogcatStartTime(),
18033                         params.isTelecomDumpSysCollectionEnabled(),
18034                         params.isTelephonyDumpSysCollectionEnabled());
18035             }
18036         } catch (RemoteException e) {
18037             Log.e(TAG, "Error while persistEmergencyCallDiagnosticData: " + e);
18038         }
18039     }
18040 
18041     /**
18042      * Set the UE's ability to accept/reject null ciphered and null integrity-protected connections.
18043      *
18044      * The modem is required to ignore this in case of an emergency call.
18045      *
18046      * <p>Requires permission: android.Manifest.MODIFY_PHONE_STATE</p>
18047      *
18048      * @param enabled if null ciphered and null integrity protected connections are permitted
18049      * @throws IllegalStateException if the Telephony process is not currently available
18050      * @throws SecurityException if the caller does not have the required privileges
18051      * @throws UnsupportedOperationException if the modem does not support disabling null ciphers.
18052      * @hide
18053      */
18054     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNullCipherAndIntegrityEnabled(boolean enabled)18055     public void setNullCipherAndIntegrityEnabled(boolean enabled) {
18056         try {
18057             ITelephony telephony = getITelephony();
18058             if (telephony != null) {
18059                 telephony.setNullCipherAndIntegrityEnabled(enabled);
18060             } else {
18061                 throw new IllegalStateException("telephony service is null.");
18062             }
18063         } catch (RemoteException ex) {
18064             Rlog.e(TAG, "setNullCipherAndIntegrityEnabled RemoteException", ex);
18065             ex.rethrowFromSystemServer();
18066         }
18067     }
18068 
18069     /**
18070      * Get the value of the global preference for null cipher and integriy enablement.
18071      * Note: This does not return the state of the modem, only the persisted global preference.
18072      *
18073      * <p>Requires permission: android.Manifest.READ_PHONE_STATE</p>
18074      *
18075      * @throws IllegalStateException if the Telephony process is not currently available
18076      * @throws SecurityException if the caller does not have the required privileges
18077      * @throws UnsupportedOperationException if the modem does not support disabling null ciphers.
18078      * @hide
18079      */
18080     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
isNullCipherAndIntegrityPreferenceEnabled()18081     public boolean isNullCipherAndIntegrityPreferenceEnabled() {
18082         try {
18083             ITelephony telephony = getITelephony();
18084             if (telephony != null) {
18085                 return telephony.isNullCipherAndIntegrityPreferenceEnabled();
18086             } else {
18087                 throw new IllegalStateException("telephony service is null.");
18088             }
18089         } catch (RemoteException ex) {
18090             Rlog.e(TAG, "isNullCipherAndIntegrityPreferenceEnabled RemoteException", ex);
18091             ex.rethrowFromSystemServer();
18092         }
18093         return true;
18094     }
18095 
18096     /**
18097      * Get current cell broadcast message identifier ranges.
18098      *
18099      * @throws SecurityException if the caller does not have the required permission
18100      * @hide
18101      */
18102     @SystemApi
18103     @RequiresPermission(android.Manifest.permission.MODIFY_CELL_BROADCASTS)
18104     @NonNull
getCellBroadcastIdRanges()18105     public List<CellBroadcastIdRange> getCellBroadcastIdRanges() {
18106         try {
18107             ITelephony telephony = getITelephony();
18108             if (telephony != null) {
18109                 return telephony.getCellBroadcastIdRanges(getSubId());
18110             } else {
18111                 throw new IllegalStateException("telephony service is null.");
18112             }
18113         } catch (RemoteException ex) {
18114             ex.rethrowFromSystemServer();
18115         }
18116         return new ArrayList<>();
18117     }
18118 
18119     /** @hide */
18120     @Retention(RetentionPolicy.SOURCE)
18121     @IntDef(prefix = {"CELL_BROADCAST_RESULT_"}, value = {
18122             CELL_BROADCAST_RESULT_UNKNOWN,
18123             CELL_BROADCAST_RESULT_SUCCESS,
18124             CELL_BROADCAST_RESULT_UNSUPPORTED,
18125             CELL_BROADCAST_RESULT_FAIL_CONFIG,
18126             CELL_BROADCAST_RESULT_FAIL_ACTIVATION})
18127     public @interface CellBroadcastResult {}
18128 
18129     /**
18130      * The result of the cell broadcast request is unknown
18131      * @hide
18132      */
18133     @SystemApi
18134     public static final int CELL_BROADCAST_RESULT_UNKNOWN = -1;
18135 
18136     /**
18137      * The cell broadcast request is successful.
18138      * @hide
18139      */
18140     @SystemApi
18141     public static final int CELL_BROADCAST_RESULT_SUCCESS = 0;
18142 
18143     /**
18144      * The cell broadcast request is not supported.
18145      * @hide
18146      */
18147     @SystemApi
18148     public static final int CELL_BROADCAST_RESULT_UNSUPPORTED = 1;
18149 
18150     /**
18151      * The cell broadcast request is failed due to the error to set config
18152      * @hide
18153      */
18154     @SystemApi
18155     public static final int CELL_BROADCAST_RESULT_FAIL_CONFIG = 2;
18156 
18157     /**
18158      * The cell broadcast request is failed due to the error to set activation
18159      * @hide
18160      */
18161     @SystemApi
18162     public static final int CELL_BROADCAST_RESULT_FAIL_ACTIVATION = 3;
18163 
18164     /**
18165      * Callback mode type
18166      * @hide
18167      */
18168     @Retention(RetentionPolicy.SOURCE)
18169     @IntDef(prefix = {"EMERGENCY_CALLBACK_MODE_"}, value = {
18170             EMERGENCY_CALLBACK_MODE_CALL,
18171             EMERGENCY_CALLBACK_MODE_SMS})
18172     public @interface EmergencyCallbackModeType {}
18173 
18174     /**
18175      * The callback mode is due to emergency call.
18176      * @hide
18177      */
18178     public static final int EMERGENCY_CALLBACK_MODE_CALL = 1;
18179 
18180     /**
18181      * The callback mode is due to emergency SMS.
18182      * @hide
18183      */
18184     public static final int EMERGENCY_CALLBACK_MODE_SMS = 2;
18185 
18186     /**
18187      * The reason for changing callback mode.
18188      * @hide
18189      */
18190     @Retention(RetentionPolicy.SOURCE)
18191     @IntDef(prefix = {"STOP_REASON_"},
18192             value = {
18193                     STOP_REASON_UNKNOWN,
18194                     STOP_REASON_OUTGOING_NORMAL_CALL_INITIATED,
18195                     STOP_REASON_NORMAL_SMS_SENT,
18196                     STOP_REASON_OUTGOING_EMERGENCY_CALL_INITIATED,
18197                     STOP_REASON_EMERGENCY_SMS_SENT,
18198                     STOP_REASON_TIMER_EXPIRED,
18199                     STOP_REASON_USER_ACTION,
18200             })
18201     public @interface EmergencyCallbackModeStopReason {}
18202 
18203     /**
18204      * unknown reason.
18205      * @hide
18206      */
18207     public static final int STOP_REASON_UNKNOWN = 0;
18208 
18209     /**
18210      * The call back mode is exited due to a new normal call is originated.
18211      * @hide
18212      */
18213     public static final int STOP_REASON_OUTGOING_NORMAL_CALL_INITIATED = 1;
18214 
18215     /**
18216      * The call back mode is exited due to a new normal SMS is originated.
18217      * @hide
18218      */
18219     public static final int STOP_REASON_NORMAL_SMS_SENT = 2;
18220 
18221     /**
18222      * The call back mode is exited due to a new emergency call is originated.
18223      * @hide
18224      */
18225     public static final int STOP_REASON_OUTGOING_EMERGENCY_CALL_INITIATED = 3;
18226 
18227     /**
18228      * The call back mode is exited due to a new emergency SMS is originated.
18229      * @hide
18230      */
18231     public static final int STOP_REASON_EMERGENCY_SMS_SENT = 4;
18232 
18233     /**
18234      * The call back mode is exited due to timer expiry.
18235      * @hide
18236      */
18237     public static final int STOP_REASON_TIMER_EXPIRED = 5;
18238 
18239     /**
18240      * The call back mode is exited due to user action.
18241      * @hide
18242      */
18243     public static final int STOP_REASON_USER_ACTION = 6;
18244 
18245     /**
18246      * Set reception of cell broadcast messages with the list of the given ranges
18247      *
18248      * <p>The ranges set previously will be overridden by the new one. Empty list
18249      * can be used to clear the ranges.
18250      *
18251      * @param ranges the list of {@link CellBroadcastIdRange} to be set.
18252      * @param executor The {@link Executor} that will be used to call the callback.
18253      * @param callback A callback called on the supplied {@link Executor} to notify
18254      * the result when the operation completes.
18255      * @throws SecurityException if the caller does not have the required permission
18256      * @throws IllegalArgumentException when the ranges are invalid.
18257      * @hide
18258      */
18259     @SystemApi
18260     @RequiresPermission(android.Manifest.permission.MODIFY_CELL_BROADCASTS)
setCellBroadcastIdRanges(@onNull List<CellBroadcastIdRange> ranges, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Integer> callback)18261     public void setCellBroadcastIdRanges(@NonNull List<CellBroadcastIdRange> ranges,
18262             @NonNull @CallbackExecutor Executor executor,
18263             @NonNull Consumer<Integer> callback) {
18264         IIntegerConsumer consumer = callback == null ? null : new IIntegerConsumer.Stub() {
18265             @Override
18266             public void accept(int result) {
18267                 final long identity = Binder.clearCallingIdentity();
18268                 try {
18269                     executor.execute(() -> callback.accept(result));
18270                 } finally {
18271                     Binder.restoreCallingIdentity(identity);
18272                 }
18273             }
18274         };
18275 
18276         try {
18277             ITelephony telephony = getITelephony();
18278             if (telephony != null) {
18279                 telephony.setCellBroadcastIdRanges(getSubId(), ranges, consumer);
18280             } else {
18281                 throw new IllegalStateException("telephony service is null.");
18282             }
18283         } catch (RemoteException ex) {
18284             ex.rethrowFromSystemServer();
18285         }
18286     }
18287 
18288     /**
18289      * Returns whether the domain selection service is supported.
18290      *
18291      * <p>Requires Permission:
18292      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}.
18293      *
18294      * @return {@code true} if the domain selection service is supported.
18295      * @hide
18296      */
18297     @TestApi
18298     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
18299     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isDomainSelectionSupported()18300     public boolean isDomainSelectionSupported() {
18301         try {
18302             ITelephony telephony = getITelephony();
18303             if (telephony != null) {
18304                 return telephony.isDomainSelectionSupported();
18305             }
18306         } catch (RemoteException ex) {
18307             Rlog.w(TAG, "RemoteException", ex);
18308         }
18309         return false;
18310     }
18311 
18312     /**
18313      * Returns the primary IMEI (International Mobile Equipment Identity) of the device as
18314      * mentioned in GSMA TS.37. {@link #getImei(int)} returns the IMEI that belongs to the selected
18315      * slotID whereas this API {@link #getPrimaryImei()} returns primary IMEI of the device.
18316      * A single SIM device with only one IMEI will be set by default as primary IMEI.
18317      * A multi-SIM device with multiple IMEIs will have one of the IMEIs set as primary as
18318      * mentioned in GSMA TS37_2.2_REQ_8.
18319      *
18320      * <p>Requires one of the following permissions
18321      * <ul>
18322      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
18323      *     is a privileged permission that can only be granted to apps preloaded on the device.
18324      *     <li>If the calling app is the device owner of a fully-managed device, a profile
18325      *     owner of an organization-owned device, or their delegates (see {@link
18326      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
18327      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
18328      *     active subscription.
18329      *     <li>If the calling app is the default SMS role holder (see {@link
18330      *     RoleManager#isRoleHeld(String)}).
18331      *     <li>If the calling app has been granted the
18332      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
18333      * </ul>
18334      *
18335      * @return Primary IMEI of type string
18336      * @throws UnsupportedOperationException if the radio doesn't support this feature.
18337      * @throws SecurityException if the caller does not have the required permission/privileges
18338      */
18339     @NonNull
18340     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
getPrimaryImei()18341     public String getPrimaryImei() {
18342         try {
18343             ITelephony telephony = getITelephony();
18344             if (telephony == null) {
18345                 Rlog.e(TAG, "getPrimaryImei(): IPhoneSubInfo instance is NULL");
18346                 throw new IllegalStateException("Telephony service not available.");
18347             }
18348             return telephony.getPrimaryImei(getOpPackageName(), getAttributionTag());
18349         } catch (RemoteException ex) {
18350             Rlog.e(TAG, "getPrimaryImei() RemoteException : " + ex);
18351             throw ex.rethrowAsRuntimeException();
18352         }
18353     }
18354 
18355     /**
18356      * Convert SIM state into string.
18357      *
18358      * @param state SIM state.
18359      * @return SIM state in string format.
18360      *
18361      * @hide
18362      */
18363     @NonNull
simStateToString(@imState int state)18364     public static String simStateToString(@SimState int state) {
18365         switch (state) {
18366             case TelephonyManager.SIM_STATE_UNKNOWN:
18367                 return "UNKNOWN";
18368             case TelephonyManager.SIM_STATE_ABSENT:
18369                 return "ABSENT";
18370             case TelephonyManager.SIM_STATE_PIN_REQUIRED:
18371                 return "PIN_REQUIRED";
18372             case TelephonyManager.SIM_STATE_PUK_REQUIRED:
18373                 return "PUK_REQUIRED";
18374             case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
18375                 return "NETWORK_LOCKED";
18376             case TelephonyManager.SIM_STATE_READY:
18377                 return "READY";
18378             case TelephonyManager.SIM_STATE_NOT_READY:
18379                 return "NOT_READY";
18380             case TelephonyManager.SIM_STATE_PERM_DISABLED:
18381                 return "PERM_DISABLED";
18382             case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
18383                 return "CARD_IO_ERROR";
18384             case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
18385                 return "CARD_RESTRICTED";
18386             case TelephonyManager.SIM_STATE_LOADED:
18387                 return "LOADED";
18388             case TelephonyManager.SIM_STATE_PRESENT:
18389                 return "PRESENT";
18390             default:
18391                 return "UNKNOWN(" + state + ")";
18392         }
18393     }
18394 }
18395