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.CurrentTimeMillisLong;
29 import android.annotation.FlaggedApi;
30 import android.annotation.IntDef;
31 import android.annotation.LongDef;
32 import android.annotation.NonNull;
33 import android.annotation.Nullable;
34 import android.annotation.RequiresFeature;
35 import android.annotation.RequiresPermission;
36 import android.annotation.SdkConstant;
37 import android.annotation.SdkConstant.SdkConstantType;
38 import android.annotation.StringDef;
39 import android.annotation.SuppressAutoDoc;
40 import android.annotation.SuppressLint;
41 import android.annotation.SystemApi;
42 import android.annotation.SystemService;
43 import android.annotation.TestApi;
44 import android.annotation.WorkerThread;
45 import android.app.PendingIntent;
46 import android.app.PropertyInvalidatedCache;
47 import android.app.role.RoleManager;
48 import android.compat.Compatibility;
49 import android.compat.annotation.ChangeId;
50 import android.compat.annotation.EnabledAfter;
51 import android.compat.annotation.EnabledSince;
52 import android.compat.annotation.UnsupportedAppUsage;
53 import android.content.ComponentName;
54 import android.content.Context;
55 import android.content.ContextParams;
56 import android.content.Intent;
57 import android.content.pm.PackageManager;
58 import android.database.Cursor;
59 import android.net.ConnectivityManager;
60 import android.net.NetworkCapabilities;
61 import android.net.Uri;
62 import android.os.AsyncTask;
63 import android.os.Binder;
64 import android.os.Build;
65 import android.os.Bundle;
66 import android.os.Handler;
67 import android.os.IBinder;
68 import android.os.Looper;
69 import android.os.OutcomeReceiver;
70 import android.os.ParcelFileDescriptor;
71 import android.os.ParcelUuid;
72 import android.os.Parcelable;
73 import android.os.PersistableBundle;
74 import android.os.RemoteException;
75 import android.os.ResultReceiver;
76 import android.os.SystemProperties;
77 import android.os.WorkSource;
78 import android.provider.Settings.SettingNotFoundException;
79 import android.service.carrier.CarrierIdentifier;
80 import android.service.carrier.CarrierService;
81 import android.sysprop.TelephonyProperties;
82 import android.telecom.Call;
83 import android.telecom.CallScreeningService;
84 import android.telecom.Connection;
85 import android.telecom.InCallService;
86 import android.telecom.PhoneAccount;
87 import android.telecom.PhoneAccountHandle;
88 import android.telecom.TelecomManager;
89 import android.telephony.Annotation.ApnType;
90 import android.telephony.Annotation.CallState;
91 import android.telephony.Annotation.CarrierPrivilegeStatus;
92 import android.telephony.Annotation.NetworkType;
93 import android.telephony.Annotation.RadioPowerState;
94 import android.telephony.Annotation.SimActivationState;
95 import android.telephony.Annotation.ThermalMitigationResult;
96 import android.telephony.Annotation.UiccAppType;
97 import android.telephony.Annotation.UiccAppTypeExt;
98 import android.telephony.CallForwardingInfo.CallForwardingReason;
99 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
100 import android.telephony.data.ApnSetting;
101 import android.telephony.data.ApnSetting.MvnoType;
102 import android.telephony.data.NetworkSlicingConfig;
103 import android.telephony.emergency.EmergencyNumber;
104 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
105 import android.telephony.gba.UaSecurityProtocolIdentifier;
106 import android.telephony.ims.ImsMmTelManager;
107 import android.telephony.ims.aidl.IImsConfig;
108 import android.telephony.ims.aidl.IImsRegistration;
109 import android.telephony.ims.feature.MmTelFeature;
110 import android.telephony.ims.stub.ImsRegistrationImplBase;
111 import android.text.TextUtils;
112 import android.util.Log;
113 import android.util.Pair;
114 
115 import com.android.internal.annotations.GuardedBy;
116 import com.android.internal.annotations.VisibleForTesting;
117 import com.android.internal.os.BackgroundThread;
118 import com.android.internal.telephony.CellNetworkScanResult;
119 import com.android.internal.telephony.IBooleanConsumer;
120 import com.android.internal.telephony.ICallForwardingInfoCallback;
121 import com.android.internal.telephony.IIntegerConsumer;
122 import com.android.internal.telephony.INumberVerificationCallback;
123 import com.android.internal.telephony.IOns;
124 import com.android.internal.telephony.IPhoneSubInfo;
125 import com.android.internal.telephony.ISetOpportunisticDataCallback;
126 import com.android.internal.telephony.ISms;
127 import com.android.internal.telephony.ISub;
128 import com.android.internal.telephony.ITelephony;
129 import com.android.internal.telephony.IUpdateAvailableNetworksCallback;
130 import com.android.internal.telephony.IccLogicalChannelRequest;
131 import com.android.internal.telephony.OperatorInfo;
132 import com.android.internal.telephony.PhoneConstants;
133 import com.android.internal.telephony.RILConstants;
134 import com.android.internal.telephony.flags.Flags;
135 import com.android.telephony.Rlog;
136 
137 import java.io.IOException;
138 import java.io.InputStream;
139 import java.io.OutputStream;
140 import java.lang.annotation.Retention;
141 import java.lang.annotation.RetentionPolicy;
142 import java.nio.file.Files;
143 import java.nio.file.Path;
144 import java.util.ArrayList;
145 import java.util.Arrays;
146 import java.util.Collection;
147 import java.util.Collections;
148 import java.util.HashMap;
149 import java.util.HashSet;
150 import java.util.List;
151 import java.util.Locale;
152 import java.util.Map;
153 import java.util.Objects;
154 import java.util.Optional;
155 import java.util.Set;
156 import java.util.UUID;
157 import java.util.concurrent.Executor;
158 import java.util.concurrent.RejectedExecutionException;
159 import java.util.function.Consumer;
160 import java.util.stream.Collectors;
161 import java.util.stream.IntStream;
162 
163 /**
164  * Provides access to information about the telephony services on
165  * the device. Applications can use the methods in this class to
166  * determine telephony services and states, as well as to access some
167  * types of subscriber information. Applications can also register
168  * a listener to receive notification of telephony state changes.
169  * <p>
170  * The returned TelephonyManager will use the default subscription for all calls.
171  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
172  * <code>
173  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
174  * </code>
175  * <p>
176  * Note that access to some telephony information is
177  * permission-protected. Your application cannot access the protected
178  * information unless it has the appropriate permissions declared in
179  * its manifest file. Where permissions apply, they are noted in the
180  * the methods through which you access the protected information.
181  *
182  * <p>TelephonyManager is intended for use on devices that implement
183  * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
184  * that do not implement this feature, the behavior is not reliable.
185  */
186 @SystemService(Context.TELEPHONY_SERVICE)
187 @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
188 public class TelephonyManager {
189     private static final String TAG = "TelephonyManager";
190 
191     private TelephonyRegistryManager mTelephonyRegistryMgr;
192     /**
193      * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
194      * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
195      */
196     @ChangeId
197     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
198     private static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
199 
200     /**
201      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
202      * into the ResultReceiver Bundle.
203      * @hide
204      */
205     public static final String MODEM_ACTIVITY_RESULT_KEY = "controller_activity";
206 
207     /** @hide */
208     public static final String EXCEPTION_RESULT_KEY = "exception";
209 
210     /**
211      * The process name of the Phone app as well as many other apps that use this process name, such
212      * as settings and vendor components.
213      * @hide
214      */
215     public static final String PHONE_PROCESS_NAME = "com.android.phone";
216 
217     /**
218      * The allowed states of Wi-Fi calling.
219      *
220      * @hide
221      */
222     public interface WifiCallingChoices {
223         /** Always use Wi-Fi calling */
224         static final int ALWAYS_USE = 0;
225         /** Ask the user whether to use Wi-Fi on every call */
226         static final int ASK_EVERY_TIME = 1;
227         /** Never use Wi-Fi calling */
228         static final int NEVER_USE = 2;
229     }
230 
231     /** @hide */
232     @Retention(RetentionPolicy.SOURCE)
233     @IntDef(prefix = {"NETWORK_SELECTION_MODE_"},
234             value = {
235                     NETWORK_SELECTION_MODE_UNKNOWN,
236                     NETWORK_SELECTION_MODE_AUTO,
237                     NETWORK_SELECTION_MODE_MANUAL})
238     public @interface NetworkSelectionMode {}
239 
240     public static final int NETWORK_SELECTION_MODE_UNKNOWN = 0;
241     public static final int NETWORK_SELECTION_MODE_AUTO = 1;
242     public static final int NETWORK_SELECTION_MODE_MANUAL = 2;
243 
244     /**
245      * Reasons for Radio being powered off.
246      *
247      * @hide
248      */
249     @Retention(RetentionPolicy.SOURCE)
250     @IntDef(prefix = {"RADIO_POWER_REASON_"},
251             value = {
252                     RADIO_POWER_REASON_USER,
253                     RADIO_POWER_REASON_THERMAL,
254                     RADIO_POWER_REASON_CARRIER,
255                     RADIO_POWER_REASON_NEARBY_DEVICE})
256     public @interface RadioPowerReason {}
257 
258     /**
259      * This reason is used when users want to turn off radio, e.g., users turn on airplane mode.
260      *
261      * @hide
262      */
263     @SystemApi
264     public static final int RADIO_POWER_REASON_USER = 0;
265     /**
266      * This reason is used when radio needs to be turned off due to thermal.
267      *
268      * @hide
269      */
270     @SystemApi
271     public static final int RADIO_POWER_REASON_THERMAL = 1;
272     /**
273      * This reason is used when carriers want to turn off radio. A privileged app can request to
274      * turn off radio via the system service
275      * {@link com.android.carrierdefaultapp.CaptivePortalLoginActivity}, which subsequently calls
276      * the system APIs {@link requestRadioPowerOffForReason} and
277      * {@link clearRadioPowerOffForReason}.
278      *
279      * @hide
280      */
281     @SystemApi
282     public static final int RADIO_POWER_REASON_CARRIER = 2;
283     /**
284      * Used to reduce power on a battery-constrained device when Telephony services are available
285      * via a paired device which is nearby.
286      *
287      * @hide
288      */
289     @SystemApi
290     public static final int RADIO_POWER_REASON_NEARBY_DEVICE = 3;
291 
292     /** The otaspMode passed to SercvieState changes */
293     /** @hide */
294     static public final int OTASP_UNINITIALIZED = 0;
295     /** @hide */
296     static public final int OTASP_UNKNOWN = 1;
297     /** @hide */
298     static public final int OTASP_NEEDED = 2;
299     /** @hide */
300     static public final int OTASP_NOT_NEEDED = 3;
301     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
302     /** @hide */
303     static public final int OTASP_SIM_UNPROVISIONED = 5;
304 
305     /**
306      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
307      * available for use in ePDG links.
308      *
309      * @hide
310      */
311     @SystemApi
312     static public final int KEY_TYPE_EPDG = 1;
313 
314     /**
315      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
316      * available for use in WLAN links.
317      *
318      * @hide
319      */
320     @SystemApi
321     static public final int KEY_TYPE_WLAN = 2;
322 
323     /** @hide */
324     @Retention(RetentionPolicy.SOURCE)
325     @IntDef(prefix = {"KEY_TYPE_"}, value = {KEY_TYPE_EPDG, KEY_TYPE_WLAN})
326     public @interface KeyType {}
327 
328     /**
329      * No Single Radio Voice Call Continuity (SRVCC) handover is active.
330      * See TS 23.216 for more information.
331      * @hide
332      */
333     @SystemApi
334     public static final int SRVCC_STATE_HANDOVER_NONE  = -1;
335 
336     /**
337      * Single Radio Voice Call Continuity (SRVCC) handover has been started on the network.
338      * See TS 23.216 for more information.
339      * @hide
340      */
341     @SystemApi
342     public static final int SRVCC_STATE_HANDOVER_STARTED  = 0;
343 
344     /**
345      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has successfully completed.
346      * See TS 23.216 for more information.
347      * @hide
348      */
349     @SystemApi
350     public static final int SRVCC_STATE_HANDOVER_COMPLETED = 1;
351 
352     /**
353      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has failed.
354      * See TS 23.216 for more information.
355      * @hide
356      */
357     @SystemApi
358     public static final int SRVCC_STATE_HANDOVER_FAILED   = 2;
359 
360     /**
361      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has been canceled.
362      * See TS 23.216 for more information.
363      * @hide
364      */
365     @SystemApi
366     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
367 
368     /**
369      * Convert srvcc handover state to string.
370      *
371      * @param state The srvcc handover state.
372      * @return The srvcc handover state in string format.
373      *
374      * @hide
375      */
srvccStateToString(int state)376     public static @NonNull String srvccStateToString(int state) {
377         switch (state) {
378             case TelephonyManager.SRVCC_STATE_HANDOVER_NONE:
379                 return "NONE";
380             case TelephonyManager.SRVCC_STATE_HANDOVER_STARTED:
381                 return "STARTED";
382             case TelephonyManager.SRVCC_STATE_HANDOVER_COMPLETED:
383                 return "COMPLETED";
384             case TelephonyManager.SRVCC_STATE_HANDOVER_FAILED:
385                 return "FAILED";
386             case TelephonyManager.SRVCC_STATE_HANDOVER_CANCELED:
387                 return "CANCELED";
388             default:
389                 return "UNKNOWN(" + state + ")";
390         }
391     }
392 
393     /**
394      * A UICC card identifier used if the device does not support the operation.
395      * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
396      * eUICC, or the eUICC cannot be read.
397      */
398     public static final int UNSUPPORTED_CARD_ID = -1;
399 
400     /**
401      * A UICC card identifier used before the UICC card is loaded. See
402      * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
403      * <p>
404      * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
405      */
406     public static final int UNINITIALIZED_CARD_ID = -2;
407 
408     /**
409      * Default port index for a UICC.
410      *
411      * On physical SIM cards the only available port is 0.
412      * See {@link android.telephony.UiccPortInfo} for more information on ports.
413      *
414      * See {@link android.telephony.euicc.EuiccManager#isSimPortAvailable(int)} for information on
415      * how portIndex is used on eUICCs.
416      */
417     public static final int DEFAULT_PORT_INDEX = 0;
418 
419     /** @hide */
420     public static final int INVALID_PORT_INDEX = -1;
421 
422     /** @hide */
423     public static final String PROPERTY_ENABLE_NULL_CIPHER_TOGGLE = "enable_null_cipher_toggle";
424 
425     /**
426      * To apply the enforcement telephony feature and API
427      * @hide
428      */
429     @ChangeId
430     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM)
431     public static final long ENABLE_FEATURE_MAPPING = 297989574L;
432 
433     private final Context mContext;
434     private final int mSubId;
435     @UnsupportedAppUsage
436     private SubscriptionManager mSubscriptionManager;
437     private TelephonyScanManager mTelephonyScanManager;
438 
439     /** Cached service handles, cleared by resetServiceHandles() at death */
440     private static final Object sCacheLock = new Object();
441 
442     /** @hide */
443     private static boolean sServiceHandleCacheEnabled = true;
444 
445     @GuardedBy("sCacheLock")
446     private static ITelephony sITelephony;
447     @GuardedBy("sCacheLock")
448     private static IPhoneSubInfo sIPhoneSubInfo;
449     @GuardedBy("sCacheLock")
450     private static ISub sISub;
451     @GuardedBy("sCacheLock")
452     private static ISms sISms;
453     @GuardedBy("sCacheLock")
454     private static final DeathRecipient sServiceDeath = new DeathRecipient();
455 
456     /**
457      * Cache key for a {@link PropertyInvalidatedCache} which maps from {@link PhoneAccountHandle}
458      * to subscription Id.  The cache is initialized in {@code PhoneInterfaceManager}'s constructor
459      * when {@link PropertyInvalidatedCache#invalidateCache(String)} is called.
460      * The cache is cleared from {@code TelecomAccountRegistry#tearDown} when all phone accounts are
461      * removed from Telecom.
462      * @hide
463      */
464     public static final String CACHE_KEY_PHONE_ACCOUNT_TO_SUBID =
465             "cache_key.telephony.phone_account_to_subid";
466     private static final int CACHE_MAX_SIZE = 4;
467 
468     /**
469      * A {@link PropertyInvalidatedCache} which lives in an app's {@link TelephonyManager} instance.
470      * Caches any queries for a mapping between {@link PhoneAccountHandle} and {@code subscription
471      * id}.  The cache may be invalidated from Telephony when phone account re-registration takes
472      * place.
473      */
474     private PropertyInvalidatedCache<PhoneAccountHandle, Integer> mPhoneAccountHandleToSubIdCache =
475             new PropertyInvalidatedCache<PhoneAccountHandle, Integer>(CACHE_MAX_SIZE,
476                     CACHE_KEY_PHONE_ACCOUNT_TO_SUBID) {
477                 @Override
478                 public Integer recompute(PhoneAccountHandle phoneAccountHandle) {
479                     try {
480                         ITelephony telephony = getITelephony();
481                         if (telephony != null) {
482                             return telephony.getSubIdForPhoneAccountHandle(phoneAccountHandle,
483                                     mContext.getOpPackageName(), mContext.getAttributionTag());
484                         }
485                     } catch (RemoteException e) {
486                         throw e.rethrowAsRuntimeException();
487                     }
488                     return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
489                 }
490             };
491 
492     /** Enum indicating multisim variants
493      *  DSDS - Dual SIM Dual Standby
494      *  DSDA - Dual SIM Dual Active
495      *  TSTS - Triple SIM Triple Standby
496      **/
497     /** @hide */
498     @UnsupportedAppUsage(implicitMember =
499             "values()[Landroid/telephony/TelephonyManager$MultiSimVariants;")
500     public enum MultiSimVariants {
501         @UnsupportedAppUsage
502         DSDS,
503         @UnsupportedAppUsage
504         DSDA,
505         @UnsupportedAppUsage
506         TSTS,
507         @UnsupportedAppUsage
508         UNKNOWN
509     };
510 
511     /** @hide */
512     @UnsupportedAppUsage
TelephonyManager(Context context)513     public TelephonyManager(Context context) {
514         this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
515     }
516 
517     /** @hide */
518     @UnsupportedAppUsage
TelephonyManager(Context context, int subId)519     public TelephonyManager(Context context, int subId) {
520         mSubId = subId;
521         mContext = mergeAttributionAndRenouncedPermissions(context.getApplicationContext(),
522             context);
523         mSubscriptionManager = SubscriptionManager.from(mContext);
524     }
525 
526     /** @hide */
527     @UnsupportedAppUsage
TelephonyManager()528     private TelephonyManager() {
529         mContext = null;
530         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
531     }
532 
533     private static TelephonyManager sInstance = new TelephonyManager();
534 
535     /** @hide
536     /* @deprecated - use getSystemService as described above */
537     @Deprecated
538     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDefault()539     public static TelephonyManager getDefault() {
540         return sInstance;
541     }
542 
543     // This method takes the Application context and adds the attributionTag
544     // and renouncedPermissions from the given context.
mergeAttributionAndRenouncedPermissions(Context to, Context from)545     private Context mergeAttributionAndRenouncedPermissions(Context to, Context from) {
546         Context contextToReturn = from;
547         if (to != null) {
548             if (!Objects.equals(from.getAttributionTag(), to.getAttributionTag())) {
549                 contextToReturn = to.createAttributionContext(from.getAttributionTag());
550             } else {
551                 contextToReturn = to;
552             }
553 
554             Set<String> renouncedPermissions =
555                     from.getAttributionSource().getRenouncedPermissions();
556             if (!renouncedPermissions.isEmpty()) {
557                 if (to.getParams() != null) {
558                     contextToReturn = contextToReturn.createContext(
559                             new ContextParams.Builder(to.getParams())
560                                     .setRenouncedPermissions(renouncedPermissions).build());
561                 } else {
562                     contextToReturn = contextToReturn.createContext(
563                             new ContextParams.Builder()
564                                     .setRenouncedPermissions(renouncedPermissions).build());
565                 }
566             }
567         }
568         return contextToReturn;
569     }
570 
getOpPackageName()571     private String getOpPackageName() {
572         // For legacy reasons the TelephonyManager has API for getting
573         // a static instance with no context set preventing us from
574         // getting the op package name. As a workaround we do a best
575         // effort and get the context from the current activity thread.
576         if (mContext != null) {
577             return mContext.getOpPackageName();
578         } else {
579             ITelephony telephony = getITelephony();
580             if (telephony == null) return null;
581             try {
582                 return telephony.getCurrentPackageName();
583             } catch (RemoteException ex) {
584                 return null;
585             } catch (NullPointerException ex) {
586                 return null;
587             }
588         }
589     }
590 
getAttributionTag()591     private String getAttributionTag() {
592         // For legacy reasons the TelephonyManager has API for getting
593         // a static instance with no context set preventing us from
594         // getting the attribution tag.
595         if (mContext != null) {
596             return mContext.getAttributionTag();
597         }
598         return null;
599     }
600 
getRenouncedPermissions()601     private Set<String> getRenouncedPermissions() {
602         // For legacy reasons the TelephonyManager has API for getting
603         // a static instance with no context set preventing us from
604         // getting the attribution source.
605         if (mContext != null) {
606             return mContext.getAttributionSource().getRenouncedPermissions();
607         }
608         return Collections.emptySet();
609     }
610 
611     /**
612      * Post a runnable to the BackgroundThread.
613      *
614      * Used to invoke user callbacks without calling into the caller's executor from the caller's
615      * calling thread context, for example to provide asynchronous error information that is
616      * generated locally (not over a binder thread).
617      *
618      * <p>This is not necessary unless you are invoking caller's code asynchronously from within
619      * the caller's thread context.
620      *
621      * @param r a runnable.
622      */
runOnBackgroundThread(@onNull Runnable r)623     private static void runOnBackgroundThread(@NonNull Runnable r) {
624         try {
625             BackgroundThread.getExecutor().execute(r);
626         } catch (RejectedExecutionException e) {
627             throw new IllegalStateException(
628                     "Failed to post a callback from the caller's thread context.", e);
629         }
630     }
631 
632     /**
633      * Returns the multi SIM variant
634      * Returns DSDS for Dual SIM Dual Standby
635      * Returns DSDA for Dual SIM Dual Active
636      * Returns TSTS for Triple SIM Triple Standby
637      * Returns UNKNOWN for others
638      */
639     /** {@hide} */
640     @UnsupportedAppUsage
getMultiSimConfiguration()641     public MultiSimVariants getMultiSimConfiguration() {
642         String mSimConfig =
643                 TelephonyProperties.multi_sim_config().orElse("");
644         if (mSimConfig.equals("dsds")) {
645             return MultiSimVariants.DSDS;
646         } else if (mSimConfig.equals("dsda")) {
647             return MultiSimVariants.DSDA;
648         } else if (mSimConfig.equals("tsts")) {
649             return MultiSimVariants.TSTS;
650         } else {
651             return MultiSimVariants.UNKNOWN;
652         }
653     }
654 
655     /**
656      * Returns the number of phones available.
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      * @deprecated Use {@link #getActiveModemCount} instead.
662      */
663     @Deprecated
getPhoneCount()664     public int getPhoneCount() {
665         return getActiveModemCount();
666     }
667 
668     /**
669      * Returns the number of logical modems currently configured to be activated.
670      *
671      * Returns 0 if none of voice, sms, data is not supported
672      * Returns 1 for Single standby mode (Single SIM functionality).
673      * Returns 2 for Dual standby mode (Dual SIM functionality).
674      * Returns 3 for Tri standby mode (Tri SIM functionality).
675      */
getActiveModemCount()676     public int getActiveModemCount() {
677         int modemCount = 1;
678         switch (getMultiSimConfiguration()) {
679             case UNKNOWN:
680                 modemCount = 1;
681                 // check for voice and data support, 0 if not supported
682                 if (!isVoiceCapable() && !isSmsCapable() && !isDataCapable()) {
683                     modemCount = 0;
684                 }
685                 break;
686             case DSDS:
687             case DSDA:
688                 modemCount = 2;
689                 break;
690             case TSTS:
691                 modemCount = 3;
692                 break;
693         }
694         return modemCount;
695     }
696 
697     /**
698      * Return how many logical modem can be potentially active simultaneously, in terms of hardware
699      * capability.
700      * It might return different value from {@link #getActiveModemCount}. For example, for a
701      * dual-SIM capable device operating in single SIM mode (only one logical modem is turned on),
702      * {@link #getActiveModemCount} returns 1 while this API returns 2.
703      */
getSupportedModemCount()704     public int getSupportedModemCount() {
705         return TelephonyProperties.max_active_modems().orElse(getActiveModemCount());
706     }
707 
708     /**
709      * Gets the maximum number of SIMs that can be active, based on the device's multisim
710      * configuration.
711      * @return 1 for single-SIM, DSDS, and TSTS devices. 2 for DSDA devices.
712      * @hide
713      */
714     @SystemApi
getMaxNumberOfSimultaneouslyActiveSims()715     public int getMaxNumberOfSimultaneouslyActiveSims() {
716         switch (getMultiSimConfiguration()) {
717             case UNKNOWN:
718             case DSDS:
719             case TSTS:
720                 return 1;
721             case DSDA:
722                 return 2;
723         }
724         return 1;
725     }
726 
727     /** {@hide} */
728     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)729     public static TelephonyManager from(Context context) {
730         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
731     }
732 
733     /**
734      * Create a new TelephonyManager object pinned to the given subscription ID.
735      *
736      * @return a TelephonyManager that uses the given subId for all calls.
737      */
createForSubscriptionId(int subId)738     public TelephonyManager createForSubscriptionId(int subId) {
739       // Don't reuse any TelephonyManager objects.
740       return new TelephonyManager(mContext, subId);
741     }
742 
743     /**
744      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
745      * phone account.
746      *
747      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
748      * if the phone account does not correspond to a valid subscription ID.
749      */
750     @Nullable
createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle)751     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
752         int subId = getSubscriptionId(phoneAccountHandle);
753         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
754             return null;
755         }
756         return new TelephonyManager(mContext, subId);
757     }
758 
759     /** {@hide} */
760     @UnsupportedAppUsage
isMultiSimEnabled()761     public boolean isMultiSimEnabled() {
762         return getPhoneCount() > 1;
763     }
764 
765     private static final int MAXIMUM_CALL_COMPOSER_PICTURE_SIZE = 80000;
766 
767     /**
768      * Indicates the maximum size of the call composure picture.
769      *
770      * Pictures sent via
771      * {@link #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)}
772      * or {@link #uploadCallComposerPicture(Path, String, Executor, OutcomeReceiver)} must not
773      * exceed this size, or an error will be returned via the callback in those methods.
774      *
775      * @return Maximum file size in bytes.
776      */
getMaximumCallComposerPictureSize()777     public static @BytesLong long getMaximumCallComposerPictureSize() {
778         return MAXIMUM_CALL_COMPOSER_PICTURE_SIZE;
779     }
780 
781     //
782     // Broadcast Intent actions
783     //
784 
785     /**
786      * Broadcast intent action indicating that the call state
787      * on the device has changed.
788      *
789      * <p>
790      * The {@link #EXTRA_STATE} extra indicates the new call state.
791      * If a receiving app has {@link android.Manifest.permission#READ_CALL_LOG} permission, a second
792      * extra {@link #EXTRA_INCOMING_NUMBER} provides the phone number for incoming and outgoing
793      * calls as a String.
794      * <p>
795      * If the receiving app has
796      * {@link android.Manifest.permission#READ_CALL_LOG} and
797      * {@link android.Manifest.permission#READ_PHONE_STATE} permission, it will receive the
798      * broadcast twice; one with the {@link #EXTRA_INCOMING_NUMBER} populated with the phone number,
799      * and another with it blank.  Due to the nature of broadcasts, you cannot assume the order
800      * in which these broadcasts will arrive, however you are guaranteed to receive two in this
801      * case.  Apps which are interested in the {@link #EXTRA_INCOMING_NUMBER} can ignore the
802      * broadcasts where {@link #EXTRA_INCOMING_NUMBER} is not present in the extras (e.g. where
803      * {@link Intent#hasExtra(String)} returns {@code false}).
804      * <p class="note">
805      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
806      * broadcast in version 1.0, but it is no longer sticky.
807      * Instead, use {@link #getCallState} to synchronously query the current call state.
808      *
809      * @see #EXTRA_STATE
810      * @see #EXTRA_INCOMING_NUMBER
811      * @see #getCallState
812      */
813     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
814     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
815     public static final String ACTION_PHONE_STATE_CHANGED =
816             "android.intent.action.PHONE_STATE";
817 
818     /**
819      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
820      * call. By default, the device's default SMS app consumes this message and sends a text message
821      * to the caller. A third party app can also provide this functionality by consuming this Intent
822      * with a {@link android.app.Service} and sending the message using its own messaging system.
823      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
824      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
825      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
826      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
827      * set of phone numbers if there are multiple recipients. For example, {@code
828      * smsto:2065551234}.</p>
829      *
830      * <p>The intent may also contain extras for the message text (in {@link
831      * android.content.Intent#EXTRA_TEXT}) and a message subject
832      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
833      *
834      * <p class="note"><strong>Note:</strong>
835      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
836      * that requires the
837      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
838      * <p>For example, the service that receives this intent can be declared in the manifest file
839      * with an intent filter like this:</p>
840      * <pre>
841      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
842      * &lt;service android:name=".HeadlessSmsSendService"
843      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
844      *          android:exported="true" >
845      *   &lt;intent-filter>
846      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
847      *     &lt;category android:name="android.intent.category.DEFAULT" />
848      *     &lt;data android:scheme="sms" />
849      *     &lt;data android:scheme="smsto" />
850      *     &lt;data android:scheme="mms" />
851      *     &lt;data android:scheme="mmsto" />
852      *   &lt;/intent-filter>
853      * &lt;/service></pre>
854      * <p>
855      * Output: nothing.
856      */
857     @SdkConstant(SdkConstantType.SERVICE_ACTION)
858     public static final String ACTION_RESPOND_VIA_MESSAGE =
859             "android.intent.action.RESPOND_VIA_MESSAGE";
860 
861     /**
862      * The emergency dialer may choose to present activities with intent filters for this
863      * action as emergency assistance buttons that launch the activity when clicked.
864      *
865      * @hide
866      */
867     @SystemApi
868     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
869     public static final String ACTION_EMERGENCY_ASSISTANCE =
870             "android.telephony.action.EMERGENCY_ASSISTANCE";
871 
872     /**
873      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
874      * call settings page launched by
875      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
876      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
877      * which would also like to manage voicemail settings should set this meta-data to {@code true}
878      * in the manifest registration of their application.
879      *
880      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
881      * @see #ACTION_CONFIGURE_VOICEMAIL
882      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
883      */
884     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
885             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
886 
887     /**
888      * Open the voicemail settings activity to make changes to voicemail configuration.
889      *
890      * <p>
891      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} to
892      * configure voicemail.
893      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
894      * API if set.
895      *
896      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
897      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
898      */
899     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
900     public static final String ACTION_CONFIGURE_VOICEMAIL =
901             "android.telephony.action.CONFIGURE_VOICEMAIL";
902 
903     /**
904      * The boolean value indicating whether the voicemail settings activity launched by {@link
905      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
906      * used by dialer implementations which provides their own voicemail settings UI, but still
907      * needs to expose device specific voicemail settings to the user.
908      *
909      * @see #ACTION_CONFIGURE_VOICEMAIL
910      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
911      */
912     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
913             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
914 
915     /**
916      * @hide
917      */
918     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
919 
920     /**
921      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
922      * for a String containing the new call state.
923      *
924      * <p class="note">
925      * Retrieve with
926      * {@link android.content.Intent#getStringExtra(String)}.
927      *
928      * @see #EXTRA_STATE_IDLE
929      * @see #EXTRA_STATE_RINGING
930      * @see #EXTRA_STATE_OFFHOOK
931      */
932     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
933 
934     /**
935      * Value used with {@link #EXTRA_STATE} corresponding to
936      * {@link #CALL_STATE_IDLE}.
937      */
938     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
939 
940     /**
941      * Value used with {@link #EXTRA_STATE} corresponding to
942      * {@link #CALL_STATE_RINGING}.
943      */
944     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
945 
946     /**
947      * Value used with {@link #EXTRA_STATE} corresponding to
948      * {@link #CALL_STATE_OFFHOOK}.
949      */
950     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
951 
952     /**
953      * Extra key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
954      * for a String containing the incoming or outgoing phone number.
955      * <p>
956      * This extra is only populated for receivers of the {@link #ACTION_PHONE_STATE_CHANGED}
957      * broadcast which have been granted the {@link android.Manifest.permission#READ_CALL_LOG} and
958      * {@link android.Manifest.permission#READ_PHONE_STATE} permissions.
959      * <p>
960      * For incoming calls, the phone number is only guaranteed to be populated when the
961      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_RINGING}.
962      * If the incoming caller is from an unknown number, the extra will be populated with an empty
963      * string.
964      * For outgoing calls, the phone number is only guaranteed to be populated when the
965      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_OFFHOOK}.
966      * <p class="note">
967      * Retrieve with
968      * {@link android.content.Intent#getStringExtra(String)}.
969      * <p>
970      *
971      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
972      * to retrieve the phone number for calls instead.  Apps performing call screening should use
973      * the {@link CallScreeningService} API instead.
974      */
975     @Deprecated
976     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
977 
978     /**
979      * Broadcast intent action indicating that call disconnect cause has changed.
980      *
981      * <p>
982      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
983      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
984      *
985      * <p class="note">
986      * Requires the READ_PRECISE_PHONE_STATE permission.
987      *
988      * @see #EXTRA_DISCONNECT_CAUSE
989      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
990      *
991      * @hide
992      */
993     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
994     public static final String ACTION_CALL_DISCONNECT_CAUSE_CHANGED =
995             "android.intent.action.CALL_DISCONNECT_CAUSE";
996 
997     /**
998      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and {@link
999      * TelephonyCallback.PreciseCallStateListener#onPreciseCallStateChanged(PreciseCallState)} for
1000      * an integer containing the disconnect cause.
1001      *
1002      * @see DisconnectCause
1003      *
1004      * <p class="note">
1005      * Retrieve with
1006      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
1007      *
1008      * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
1009      * @hide
1010      */
1011     @Deprecated
1012     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
1013 
1014     /**
1015      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and {@link
1016      * TelephonyCallback.PreciseCallStateListener#onPreciseCallStateChanged(PreciseCallState)} for
1017      * an integer containing the disconnect cause provided by the RIL.
1018      *
1019      * @see PreciseDisconnectCause
1020      *
1021      * <p class="note">
1022      * Retrieve with
1023      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
1024      *
1025      * @hide
1026      */
1027     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
1028 
1029     /**
1030      * Broadcast intent action for letting the default dialer to know to show voicemail
1031      * notification.
1032      *
1033      * <p>
1034      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
1035      * voicemail is received on.
1036      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
1037      * voicemails.
1038      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
1039      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
1040      * will call the voicemail number when sent. This extra will be empty if the voicemail number
1041      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
1042      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
1043      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
1044      * available when the voicemail number is not set.
1045      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
1046      * notification.
1047      *
1048      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
1049      * @see #EXTRA_NOTIFICATION_COUNT
1050      * @see #EXTRA_VOICEMAIL_NUMBER
1051      * @see #EXTRA_CALL_VOICEMAIL_INTENT
1052      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
1053      * @see #EXTRA_IS_REFRESH
1054      */
1055     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
1056             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
1057 
1058     /**
1059      * The extra used with an {@link #ACTION_CONFIGURE_VOICEMAIL} and
1060      * {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify the
1061      * {@link PhoneAccountHandle} the configuration or notification is for.
1062      * <p class="note">
1063      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
1064      */
1065     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
1066             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
1067 
1068     /**
1069      * The number of voice messages associated with the notification.
1070      */
1071     public static final String EXTRA_NOTIFICATION_COUNT =
1072             "android.telephony.extra.NOTIFICATION_COUNT";
1073 
1074     /**
1075      * The voicemail number.
1076      */
1077     public static final String EXTRA_VOICEMAIL_NUMBER =
1078             "android.telephony.extra.VOICEMAIL_NUMBER";
1079 
1080     /**
1081      * The intent to call voicemail.
1082      */
1083     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
1084             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
1085 
1086     /**
1087      * The intent to launch voicemail settings.
1088      */
1089     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
1090             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
1091 
1092     /**
1093      * Boolean value representing whether the {@link
1094      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
1095      * notification. Notification refresh happens after reboot or connectivity changes. The user has
1096      * already been notified for the voicemail so it should not alert the user, and should not be
1097      * shown again if the user has dismissed it.
1098      */
1099     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
1100 
1101     /**
1102      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
1103      * successfully handed over from WIFI to LTE.
1104      * <p>
1105      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1106      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1107      * @hide
1108      */
1109     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
1110             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
1111 
1112     /**
1113      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
1114      * successfully handed over from LTE to WIFI.
1115      * <p>
1116      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1117      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1118      * @hide
1119      */
1120     public static final String EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI =
1121             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI";
1122 
1123     /**
1124      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
1125      * handed over from LTE to WIFI.
1126      * <p>
1127      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1128      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1129      * @hide
1130      */
1131     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
1132             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
1133 
1134     /**
1135      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
1136      * audio because the data limit was reached.
1137      * <p>
1138      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1139      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1140      * @hide
1141      */
1142     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
1143             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
1144 
1145     /**
1146      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
1147      * audio because the data was disabled.
1148      * <p>
1149      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1150      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1151      * @hide
1152      */
1153     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
1154             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
1155 
1156     /**
1157      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
1158      * the user when an international call is placed while on WFC only.
1159      * <p>
1160      * Used when the carrier config value
1161      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
1162      * is on WFC (VoLTE not available) and an international number is dialed.
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_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
1169             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
1170 
1171     /**
1172      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
1173      * forwarded to another number.
1174      * <p>
1175      * Sent in response to an IMS supplementary service notification indicating the call has been
1176      * forwarded.
1177      * <p>
1178      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1179      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1180      * @hide
1181      */
1182     public static final String EVENT_CALL_FORWARDED =
1183             "android.telephony.event.EVENT_CALL_FORWARDED";
1184 
1185     /**
1186      * {@link android.telecom.Connection} event used to indicate that a supplementary service
1187      * notification has been received.
1188      * <p>
1189      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1190      * The {@link Bundle} parameter is expected to include the following extras:
1191      * <ul>
1192      *     <li>{@link #EXTRA_NOTIFICATION_TYPE} - the notification type.</li>
1193      *     <li>{@link #EXTRA_NOTIFICATION_CODE} - the notification code.</li>
1194      *     <li>{@link #EXTRA_NOTIFICATION_MESSAGE} - human-readable message associated with the
1195      *     supplementary service notification.</li>
1196      * </ul>
1197      * @hide
1198      */
1199     public static final String EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION =
1200             "android.telephony.event.EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION";
1201 
1202     /**
1203      * Event reported from the Telephony stack to indicate that the {@link Connection} is not
1204      * able to find any network and likely will not get connected. Upon receiving this event,
1205      * the dialer app should start the app included in the extras bundle of this event if satellite
1206      * is provisioned.
1207      * <p>
1208      * The dialer app receives this event via
1209      * {@link Call.Callback#onConnectionEvent(Call, String, Bundle)}.
1210      * <p>
1211      * The {@link Bundle} parameter is guaranteed to include the following extras if the below
1212      * conditions are met:
1213      * <ul>
1214      *     <li>{@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE} - the recommending handover
1215      *         type.</li>
1216      *     <li>{@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT} - the {@link PendingIntent}
1217      *         which will be launched by the Dialer app when receiving this connection event.</li>
1218      * </ul>
1219      * <p>
1220      * If the device is connected to satellite via carrier within the hysteresis time defined by
1221      * the carrier config
1222      * {@link CarrierConfigManager#KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT}, the component of
1223      * the {@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT} will be set to the default SMS
1224      * app.
1225      * <p>
1226      * Otherwise, if the overlay config {@code config_oem_enabled_satellite_handover_app} is
1227      * present, the app defined by this config will be used as the component of the
1228      * {@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT}. If this overlay config is empty,
1229      * {@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT} will not be included in the event
1230      * {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE}.
1231      */
1232     @FlaggedApi(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
1233     public static final String EVENT_DISPLAY_EMERGENCY_MESSAGE =
1234             "android.telephony.event.DISPLAY_EMERGENCY_MESSAGE";
1235 
1236     /**
1237      * Integer extra key used with {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE} which indicates
1238      * the type of handover from emergency call to satellite messaging.
1239      * <p>
1240      * Will be either
1241      * android.telephony.satellite.SatelliteManager#EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE_SOS
1242      * or
1243      * android.telephony.satellite.SatelliteManager#EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE_T911
1244      * <p>
1245      * Set in the extras for the {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE} connection event.
1246      */
1247     @FlaggedApi(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
1248     public static final String EXTRA_EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE =
1249             "android.telephony.extra.EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE";
1250 
1251     /**
1252      * Extra key used with the {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE} for a {@link PendingIntent}
1253      * which will be launched by the Dialer app.
1254      */
1255     @FlaggedApi(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
1256     public static final String EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT =
1257             "android.telephony.extra.EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT";
1258 
1259     /**
1260      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1261      * the type of supplementary service notification which occurred.
1262      * Will be either
1263      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_1}
1264      * or
1265      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_2}
1266      * <p>
1267      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1268      * @hide
1269      */
1270     public static final String EXTRA_NOTIFICATION_TYPE =
1271             "android.telephony.extra.NOTIFICATION_TYPE";
1272 
1273     /**
1274      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1275      * the supplementary service notification which occurred.
1276      * <p>
1277      * Depending on the {@link #EXTRA_NOTIFICATION_TYPE}, the code will be one of the {@code CODE_*}
1278      * codes defined in {@link com.android.internal.telephony.gsm.SuppServiceNotification}.
1279      * <p>
1280      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1281      * @hide
1282      */
1283     public static final String EXTRA_NOTIFICATION_CODE =
1284             "android.telephony.extra.NOTIFICATION_CODE";
1285 
1286     /**
1287      * {@link CharSequence} extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION}
1288      * which contains a human-readable message which can be displayed to the user for the
1289      * supplementary service notification.
1290      * <p>
1291      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1292      * @hide
1293      */
1294     public static final String EXTRA_NOTIFICATION_MESSAGE =
1295             "android.telephony.extra.NOTIFICATION_MESSAGE";
1296 
1297     /* Visual voicemail protocols */
1298 
1299     /**
1300      * The OMTP protocol.
1301      */
1302     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
1303 
1304     /**
1305      * A flavor of OMTP protocol with a different mobile originated (MO) format
1306      */
1307     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
1308 
1309     /**
1310      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
1311      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
1312      * setting, this key will not exist.
1313      *
1314      * @see #getVisualVoicemailSettings()
1315      * @hide
1316      */
1317     @SystemApi
1318     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
1319             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
1320 
1321     /**
1322      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
1323      * access PIN scrambled during the auto provisioning process. The user is expected to reset
1324      * their PIN if this value is not {@code null}.
1325      *
1326      * @see #getVisualVoicemailSettings()
1327      * @hide
1328      */
1329     @SystemApi
1330     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
1331             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
1332 
1333     /**
1334      * Broadcast action to be received by Broadcast receivers.
1335      *
1336      * Indicates multi-SIM configuration is changed. For example, it changed
1337      * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
1338      *
1339      * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
1340      * or that all steps during multi-SIM change are done. To know those information you still need
1341      * to listen to SIM_STATE changes or active subscription changes.
1342      *
1343      * See extra of {@link #EXTRA_ACTIVE_SIM_SUPPORTED_COUNT} for updated value.
1344      */
1345     public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
1346             "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
1347 
1348 
1349     /**
1350      * The number of active SIM supported by current multi-SIM config. It's not related to how many
1351      * SIM/subscriptions are currently active.
1352      *
1353      * Same value will be returned by {@link #getActiveModemCount()}.
1354      *
1355      * For single SIM mode, it's 1.
1356      * For DSDS or DSDA mode, it's 2.
1357      * For triple-SIM mode, it's 3.
1358      *
1359      * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
1360      *
1361      * type: integer
1362      */
1363     public static final String EXTRA_ACTIVE_SIM_SUPPORTED_COUNT =
1364             "android.telephony.extra.ACTIVE_SIM_SUPPORTED_COUNT";
1365 
1366     /**
1367      * @hide
1368      */
1369     public static final String USSD_RESPONSE = "USSD_RESPONSE";
1370 
1371     /**
1372      * USSD return code success.
1373      * @hide
1374      */
1375     public static final int USSD_RETURN_SUCCESS = 100;
1376 
1377     /**
1378      * Failed code returned when the mobile network has failed to complete a USSD request.
1379      * <p>
1380      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1381      * TelephonyManager, String, int)}.
1382      */
1383     public static final int USSD_RETURN_FAILURE = -1;
1384 
1385     /**
1386      * Failure code returned when a USSD request has failed to execute because the Telephony
1387      * service is unavailable.
1388      * <p>
1389      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1390      * TelephonyManager, String, int)}.
1391      */
1392     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
1393 
1394     /**
1395      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which leaves the roaming
1396      * mode set to the radio default or to the user's preference if they've indicated one.
1397      */
1398     public static final int CDMA_ROAMING_MODE_RADIO_DEFAULT = -1;
1399     /**
1400      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which only permits
1401      * connections on home networks.
1402      */
1403     public static final int CDMA_ROAMING_MODE_HOME = 0;
1404     /**
1405      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1406      * affiliated networks.
1407      */
1408     public static final int CDMA_ROAMING_MODE_AFFILIATED = 1;
1409     /**
1410      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1411      * any network.
1412      */
1413     public static final int CDMA_ROAMING_MODE_ANY = 2;
1414 
1415     /** @hide */
1416     @IntDef(prefix = { "CDMA_ROAMING_MODE_" }, value = {
1417             CDMA_ROAMING_MODE_RADIO_DEFAULT,
1418             CDMA_ROAMING_MODE_HOME,
1419             CDMA_ROAMING_MODE_AFFILIATED,
1420             CDMA_ROAMING_MODE_ANY
1421     })
1422     @Retention(RetentionPolicy.SOURCE)
1423     public @interface CdmaRoamingMode{}
1424 
1425     /**
1426      * An unknown carrier id. It could either be subscription unavailable or the subscription
1427      * carrier cannot be recognized. Unrecognized carriers here means
1428      * {@link #getSimOperator() MCC+MNC} cannot be identified.
1429      */
1430     public static final int UNKNOWN_CARRIER_ID = -1;
1431 
1432     /**
1433      * An unknown carrier id list version.
1434      * @hide
1435      */
1436     @TestApi
1437     public static final int UNKNOWN_CARRIER_ID_LIST_VERSION = -1;
1438 
1439     /**
1440      * Broadcast Action: The subscription carrier identity has changed.
1441      * This intent could be sent on the following events:
1442      * <ul>
1443      *   <li>Subscription absent. Carrier identity could change from a valid id to
1444      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID}.</li>
1445      *   <li>Subscription loaded. Carrier identity could change from
1446      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID} to a valid id.</li>
1447      *   <li>The subscription carrier is recognized after a remote update.</li>
1448      * </ul>
1449      * The intent will have the following extra values:
1450      * <ul>
1451      *   <li>{@link #EXTRA_CARRIER_ID} The up-to-date carrier id of the current subscription id.
1452      *   </li>
1453      *   <li>{@link #EXTRA_CARRIER_NAME} The up-to-date carrier name of the current subscription.
1454      *   </li>
1455      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1456      *   identity.
1457      *   </li>
1458      * </ul>
1459      * <p class="note">This is a protected intent that can only be sent by the system.
1460      */
1461     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1462     public static final String ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED =
1463             "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED";
1464 
1465     /**
1466      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which indicates
1467      * the updated carrier id returned by {@link TelephonyManager#getSimCarrierId()}.
1468      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1469      * the carrier cannot be identified.
1470      */
1471     public static final String EXTRA_CARRIER_ID = "android.telephony.extra.CARRIER_ID";
1472 
1473     /**
1474      * An string extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which
1475      * indicates the updated carrier name of the current subscription.
1476      * @see TelephonyManager#getSimCarrierIdName()
1477      * <p>Carrier name is a user-facing name of the carrier id {@link #EXTRA_CARRIER_ID},
1478      * usually the brand name of the subsidiary (e.g. T-Mobile).
1479      */
1480     public static final String EXTRA_CARRIER_NAME = "android.telephony.extra.CARRIER_NAME";
1481 
1482     /**
1483      * Broadcast Action: The subscription specific carrier identity has changed.
1484      *
1485      * A specific carrier ID returns the fine-grained carrier ID of the current subscription.
1486      * It can represent the fact that a carrier may be in effect an aggregation of other carriers
1487      * (ie in an MVNO type scenario) where each of these specific carriers which are used to make
1488      * up the actual carrier service may have different carrier configurations.
1489      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
1490      * different carrier configuration for different service offering such as a prepaid plan.
1491      *
1492      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
1493      * about the carrier itself should use the regular carrier ID returned by
1494      * {@link #getSimCarrierId()}.
1495      *
1496      * <p>Similar like {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED}, this intent will be
1497      * sent on the event of {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} while its also
1498      * possible to be sent without {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} when
1499      * specific carrier ID changes while carrier ID remains the same.
1500      * e.g, the same subscription switches to different IMSI could potentially change its
1501      * specific carrier ID while carrier id remains the same.
1502      * @see #getSimSpecificCarrierId()
1503      * @see #getSimCarrierId()
1504      *
1505      * The intent will have the following extra values:
1506      * <ul>
1507      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_ID} The up-to-date specific carrier id of the
1508      *   current subscription.
1509      *   </li>
1510      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_NAME} The up-to-date name of the specific carrier id.
1511      *   </li>
1512      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1513      *   identity.
1514      *   </li>
1515      * </ul>
1516      * <p class="note">This is a protected intent that can only be sent by the system.
1517      */
1518     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1519     public static final String ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED =
1520             "android.telephony.action.SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED";
1521 
1522     /**
1523      * An int extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED} which
1524      * indicates the updated specific carrier id returned by
1525      * {@link TelephonyManager#getSimSpecificCarrierId()}. Note, its possible specific carrier id
1526      * changes while {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} remains the same
1527      * e.g, when subscription switch to different IMSIs.
1528      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1529      * the carrier cannot be identified.
1530      */
1531     public static final String EXTRA_SPECIFIC_CARRIER_ID =
1532             "android.telephony.extra.SPECIFIC_CARRIER_ID";
1533 
1534     /**
1535      * An string extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED}
1536      * which indicates the updated specific carrier name returned by
1537      * {@link TelephonyManager#getSimSpecificCarrierIdName()}.
1538      * <p>it's a user-facing name of the specific carrier id {@link #EXTRA_SPECIFIC_CARRIER_ID}
1539      * e.g, Tracfone-AT&T
1540      */
1541     public static final String EXTRA_SPECIFIC_CARRIER_NAME =
1542             "android.telephony.extra.SPECIFIC_CARRIER_NAME";
1543 
1544     /**
1545      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} to indicate the
1546      * subscription which has changed; or in general whenever a subscription ID needs specified.
1547      */
1548     public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
1549 
1550     /**
1551      * Broadcast Action: The Service Provider string(s) have been updated. Activities or
1552      * services that use these strings should update their display.
1553      *
1554      * <p>The intent will have the following extra values:
1555      * <dl>
1556      *   <dt>{@link #EXTRA_SHOW_PLMN}</dt>
1557      *   <dd>Boolean that indicates whether the PLMN should be shown.</dd>
1558      *   <dt>{@link #EXTRA_PLMN}</dt>
1559      *   <dd>The operator name of the registered network, as a string.</dd>
1560      *   <dt>{@link #EXTRA_SHOW_SPN}</dt>
1561      *   <dd>Boolean that indicates whether the SPN should be shown.</dd>
1562      *   <dt>{@link #EXTRA_SPN}</dt>
1563      *   <dd>The service provider name, as a string.</dd>
1564      *   <dt>{@link #EXTRA_DATA_SPN}</dt>
1565      *   <dd>The service provider name for data service, as a string.</dd>
1566      * </dl>
1567      *
1568      * Note that {@link #EXTRA_SHOW_PLMN} may indicate that {@link #EXTRA_PLMN} should be displayed,
1569      * even though the value for {@link #EXTRA_PLMN} is null. This can happen, for example, if the
1570      * phone has not registered to a network yet. In this case the receiver may substitute an
1571      * appropriate placeholder string (eg, "No service").
1572      *
1573      * It is recommended to display {@link #EXTRA_PLMN} before / above {@link #EXTRA_SPN} if
1574      * both are displayed.
1575      *
1576      * <p>Note: this is a protected intent that can only be sent by the system.
1577      * @hide
1578      */
1579     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1580     public static final String ACTION_SERVICE_PROVIDERS_UPDATED =
1581             "android.telephony.action.SERVICE_PROVIDERS_UPDATED";
1582 
1583     /**
1584      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1585      * whether the PLMN should be shown.
1586      * @hide
1587      */
1588     public static final String EXTRA_SHOW_PLMN = "android.telephony.extra.SHOW_PLMN";
1589 
1590     /**
1591      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1592      * the operator name of the registered network.
1593      * @hide
1594      */
1595     public static final String EXTRA_PLMN = "android.telephony.extra.PLMN";
1596 
1597     /**
1598      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1599      * whether the PLMN should be shown.
1600      * @hide
1601      */
1602     public static final String EXTRA_SHOW_SPN = "android.telephony.extra.SHOW_SPN";
1603 
1604     /**
1605      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1606      * the service provider name.
1607      * @hide
1608      */
1609     public static final String EXTRA_SPN = "android.telephony.extra.SPN";
1610 
1611     /**
1612      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1613      * the service provider name for data service.
1614      * @hide
1615      */
1616     public static final String EXTRA_DATA_SPN = "android.telephony.extra.DATA_SPN";
1617 
1618     /**
1619      * Broadcast intent action indicating that when data stall recovery is attempted by Telephony,
1620      * intended for report every data stall recovery step attempted.
1621      *
1622      * <p>
1623      * The {@link #EXTRA_RECOVERY_ACTION} extra indicates the action associated with the data
1624      * stall recovery.
1625      * The phone id where the data stall recovery is attempted.
1626      *
1627      * <p class="note">
1628      * Requires the READ_PHONE_STATE permission.
1629      *
1630      * <p class="note">
1631      * This is a protected intent that can only be sent by the system.
1632      *
1633      * @see #EXTRA_RECOVERY_ACTION
1634      *
1635      * @hide
1636      */
1637     // TODO(b/78370030) : Restrict this to system applications only
1638     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1639     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1640     public static final String ACTION_DATA_STALL_DETECTED =
1641             "android.intent.action.DATA_STALL_DETECTED";
1642 
1643     /**
1644      * A service action that identifies
1645      * a {@link android.service.carrier.CarrierMessagingClientService} subclass in the
1646      * AndroidManifest.xml.
1647      *
1648      * <p>See {@link android.service.carrier.CarrierMessagingClientService} for the details.
1649      */
1650     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1651     public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE =
1652             "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
1653 
1654     /**
1655      * An int extra used with {@link #ACTION_DATA_STALL_DETECTED} to indicate the
1656      * action associated with the data stall recovery.
1657      *
1658      * @see #ACTION_DATA_STALL_DETECTED
1659      *
1660      * @hide
1661      */
1662     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
1663 
1664     private static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000;
1665 
1666     /**
1667      * Intent sent when an error occurs that debug tools should log and possibly take further
1668      * action such as capturing vendor-specific logs.
1669      *
1670      * A privileged application that reads these events should take appropriate vendor-specific
1671      * action to record the event and collect further information to assist in analysis, debugging,
1672      * and resolution of any associated issue.
1673      *
1674      * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
1675      * should generally be sent at a low rate. Instead, this mechanism should be used for the
1676      * framework to notify a debugging application that an event (such as a bug) has occured
1677      * within the framework if that event should trigger the collection and preservation of other
1678      * more detailed device state for debugging.
1679      *
1680      * <p>At most one application can receive these events and should register a receiver in
1681      * in the application manifest. For performance reasons, if no application to receive these
1682      * events is detected at boot, then these events will not be sent.
1683      *
1684      * <p>Each event will include an {@link EXTRA_ANOMALY_ID} that will uniquely identify the
1685      * event that has occurred. Each event will be sent to the diagnostic monitor only once per
1686      * boot cycle (as another optimization).
1687      *
1688      * @see #EXTRA_ANOMALY_ID
1689      * @see #EXTRA_ANOMALY_DESCRIPTION
1690      * @hide
1691      */
1692     @SystemApi
1693     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1694     public static final String ACTION_ANOMALY_REPORTED =
1695             "android.telephony.action.ANOMALY_REPORTED";
1696 
1697     /**
1698      * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
1699      *
1700      * This field must be included in all {@link ACTION_ANOMALY_REPORTED} events.
1701      *
1702      * @see #ACTION_ANOMALY_REPORTED
1703      * @hide
1704      */
1705     @SystemApi
1706     public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
1707 
1708     /**
1709      * A freeform string description of the Anomaly.
1710      *
1711      * This field is optional for all {@link ACTION_ANOMALY_REPORTED}s, as a guideline should not
1712      * exceed 80 characters, and should be as short as possible to convey the essence of the event.
1713      *
1714      * @see #ACTION_ANOMALY_REPORTED
1715      * @hide
1716      */
1717     @SystemApi
1718     public static final String EXTRA_ANOMALY_DESCRIPTION =
1719             "android.telephony.extra.ANOMALY_DESCRIPTION";
1720 
1721     /**
1722      * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
1723      *
1724      * @hide
1725      */
1726     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1727     public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
1728             "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
1729 
1730     /**
1731      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1732      * to indicate what type of SIM selection is needed.
1733      *
1734      * @hide
1735      */
1736     public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
1737             "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
1738 
1739     /** @hide */
1740     @IntDef({
1741             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE,
1742             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
1743             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE,
1744             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS,
1745             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL
1746     })
1747     @Retention(RetentionPolicy.SOURCE)
1748     public @interface DefaultSubscriptionSelectType{}
1749 
1750     /**
1751      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1752      * to indicate there's no need to re-select any default subscription.
1753      * @hide
1754      */
1755     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
1756 
1757     /**
1758      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1759      * to indicate there's a need to select default data subscription.
1760      * @hide
1761      */
1762     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
1763 
1764     /**
1765      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1766      * to indicate there's a need to select default voice call subscription.
1767      * @hide
1768      */
1769     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
1770 
1771     /**
1772      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1773      * to indicate there's a need to select default sms subscription.
1774      * @hide
1775      */
1776     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
1777 
1778     /**
1779      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1780      * to indicate user to decide whether current SIM should be preferred for all
1781      * data / voice / sms. {@link #EXTRA_SUBSCRIPTION_ID} will specified to indicate
1782      * which subscription should be the default subscription.
1783      * @hide
1784      */
1785     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL = 4;
1786 
1787     /**
1788      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1789      * to indicate that default subscription for data/sms/voice is now determined, that
1790      * it should dismiss any dialog or pop-ups that is asking user to select default sub.
1791      * This is used when, for example, opportunistic subscription is configured. At that
1792      * time the primary becomes default sub there's no need to ask user to select anymore.
1793      * @hide
1794      */
1795     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS = 5;
1796 
1797     /**
1798      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1799      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1800      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1801      *
1802      * @hide
1803      */
1804     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1805             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1806 
1807     /** @hide */
1808     @IntDef({
1809             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1810             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1811     })
1812     @Retention(RetentionPolicy.SOURCE)
1813     public @interface SimCombinationWarningType{}
1814 
1815     /**
1816      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1817      * to indicate there's no SIM combination warning.
1818      * @hide
1819      */
1820     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1821 
1822     /**
1823      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1824      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1825      * @hide
1826      */
1827     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1828 
1829     /**
1830      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1831      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1832      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1833      * name will be "operator1 & operator2".
1834      *
1835      * @hide
1836      */
1837     public static final String EXTRA_SIM_COMBINATION_NAMES =
1838             "android.telephony.extra.SIM_COMBINATION_NAMES";
1839 
1840     /**
1841      * <p>Broadcast Action: The emergency callback mode is changed.
1842      * <ul>
1843      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1844      *   false=ECM off</li>
1845      * </ul>
1846      * <p class="note">
1847      * You can <em>not</em> receive this through components declared
1848      * in manifests, only by explicitly registering for it with
1849      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1850      * android.content.IntentFilter) Context.registerReceiver()}.
1851      *
1852      * <p class="note">This is a protected intent that can only be sent by the system.
1853      *
1854      * @see #EXTRA_PHONE_IN_ECM_STATE
1855      *
1856      * @hide
1857      */
1858     @SystemApi
1859     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1860     @SuppressLint("ActionValue")
1861     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1862             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1863 
1864 
1865     /**
1866      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1867      * Indicates whether the phone is in an emergency phone state.
1868      *
1869      * @hide
1870      */
1871     @SystemApi
1872     public static final String EXTRA_PHONE_IN_ECM_STATE =
1873             "android.telephony.extra.PHONE_IN_ECM_STATE";
1874 
1875     /**
1876      * Broadcast action sent when a data connection is redirected with validation failure.
1877      *
1878      * This action is intended for sim/account status checks and only sent to the carrier apps
1879      * specified in the carrier config for the subscription ID that's attached to this intent.
1880      *
1881      * The intent will have the following extra values:
1882      * <ul>
1883      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1884      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>A string indicating the redirection url</dd>
1885      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1886      *          <dd>The subscription ID on which the validation failure happened.</dd>
1887      * </ul>
1888      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1889      */
1890     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1891     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1892             "android.telephony.action.CARRIER_SIGNAL_REDIRECTED";
1893 
1894     /**
1895      * Broadcast action sent when a data connection setup fails.
1896      *
1897      * This action is intended for sim/account status checks and only sent to the carrier apps
1898      * specified in the carrier config for the subscription ID that's attached to this intent.
1899      *
1900      * The intent will have the following extra values:
1901      * <ul>
1902      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1903      *   <li>{@link #EXTRA_DATA_FAIL_CAUSE}</li><dd>A integer indicating the data fail cause.</dd>
1904      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1905      *          <dd>The subscription ID on which the data setup failure happened.</dd>
1906      * </ul>
1907      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1908      */
1909     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1910     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1911             "android.telephony.action.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1912 
1913     /**
1914      * Broadcast action sent when a PCO value becomes available from the modem.
1915      *
1916      * This action is intended for sim/account status checks and only sent to the carrier apps
1917      * specified in the carrier config for the subscription ID that's attached to this intent.
1918      *
1919      * The intent will have the following extra values:</p>
1920      * <ul>
1921      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1922      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>An integer indicating the protocol of the apn
1923      *      connection</dd>
1924      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the PCO id for the data.</dd>
1925      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of PCO data read from modem.</dd>
1926      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1927      *          <dd>The subscription ID for which the PCO info was received.</dd>
1928      * </ul>
1929      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1930      */
1931     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1932     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1933             "android.telephony.action.CARRIER_SIGNAL_PCO_VALUE";
1934 
1935     /**
1936      * Broadcast action sent when the availability of the system default network changes.
1937      *
1938      * @see ConnectivityManager#registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)
1939      *
1940      * This action is intended for carrier apps to set/reset carrier actions. It is only sent to the
1941      * carrier apps specified in the carrier config for the subscription ID attached to this intent.
1942      *
1943      * The intent will have the following extra values:</p>
1944      * <ul>
1945      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1946      *   <dd>{@code true} if the default network is now available, {@code false} otherwise.</dd>
1947      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1948      *          <dd>The subscription ID on which the default network availability changed.</dd>
1949      * </ul>
1950      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1951      */
1952     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1953     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1954             "android.telephony.action.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1955 
1956     /**
1957      * Broadcast action sent when carrier apps should reset their internal state.
1958      *
1959      * Sent when certain events such as turning on/off mobile data, removing the SIM, etc. require
1960      * carrier apps to reset their state.
1961      *
1962      * This action is intended to signal carrier apps to perform cleanup operations. It is only sent
1963      * to the carrier apps specified in the carrier config for the subscription ID attached to
1964      * this intent.
1965      *
1966      * The intent will have the following extra values:</p>
1967      * <ul>
1968      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1969      *          <dd>The subscription ID for which state should be reset.</dd>
1970      * </ul>
1971      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1972      */
1973     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1974     public static final String ACTION_CARRIER_SIGNAL_RESET =
1975             "android.telephony.action.CARRIER_SIGNAL_RESET";
1976 
1977     /**
1978      * String extra containing the redirection URL sent with
1979      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
1980      */
1981     public static final String EXTRA_REDIRECTION_URL = "android.telephony.extra.REDIRECTION_URL";
1982 
1983     /**
1984      * An integer extra containing the data fail cause.
1985      *
1986      * Sent with {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}. See {@link DataFailCause}
1987      * for a list of possible values.
1988      */
1989     public static final String EXTRA_DATA_FAIL_CAUSE = "android.telephony.extra.DATA_FAIL_CAUSE";
1990 
1991     /**
1992      * An integer extra containing the APN type.
1993      *
1994      * Sent with the  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1995      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}, and {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE}
1996      * broadcasts.
1997      * See the {@code TYPE_} constants in {@link ApnSetting} for a list of possible values.
1998      */
1999     public static final String EXTRA_APN_TYPE = "android.telephony.extra.APN_TYPE";
2000 
2001     /**
2002      * An integer extra containing the protocol of the apn connection.
2003      *
2004      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
2005      * See the {@code PROTOCOL_*} constants in {@link ApnSetting} for a list of possible values.
2006      */
2007     public static final String EXTRA_APN_PROTOCOL = "android.telephony.extra.APN_PROTOCOL";
2008 
2009     /**
2010      * An integer extra indicating the ID for the PCO data.
2011      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
2012      */
2013     public static final String EXTRA_PCO_ID = "android.telephony.extra.PCO_ID";
2014 
2015     /**
2016      * A byte array extra containing PCO data read from the modem.
2017      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
2018      */
2019     public static final String EXTRA_PCO_VALUE = "android.telephony.extra.PCO_VALUE";
2020 
2021     /**
2022      * A boolean extra indicating the availability of the default network.
2023      * Sent with the {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcast.
2024      */
2025     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE =
2026             "android.telephony.extra.DEFAULT_NETWORK_AVAILABLE";
2027 
2028     /**
2029      * <p>Broadcast Action: The emergency call state is changed.
2030      * <ul>
2031      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
2032      *   call, false otherwise</li>
2033      * </ul>
2034      * <p class="note">
2035      * You can <em>not</em> receive this through components declared
2036      * in manifests, only by explicitly registering for it with
2037      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
2038      * android.content.IntentFilter) Context.registerReceiver()}.
2039      *
2040      * <p class="note">This is a protected intent that can only be sent by the system.
2041      *
2042      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
2043      *
2044      * @hide
2045      */
2046     @SystemApi
2047     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2048     @SuppressLint("ActionValue")
2049     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
2050             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
2051 
2052 
2053     /**
2054      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
2055      * It indicates whether the phone is making an emergency call.
2056      *
2057      * @hide
2058      */
2059     @SystemApi
2060     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
2061             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
2062 
2063     /**
2064      * <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
2065      * <p class="note">.
2066      * This is to pop up a notice to show user that the phone is in emergency callback mode
2067      * and data calls and outgoing sms are blocked.
2068      *
2069      * <p class="note">This is a protected intent that can only be sent by the system.
2070      *
2071      * @hide
2072      */
2073     @SystemApi
2074     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS =
2075             "android.telephony.action.SHOW_NOTICE_ECM_BLOCK_OTHERS";
2076 
2077     /**
2078      * Broadcast Action: The default data subscription has changed in a multi-SIM device.
2079      * This has the following extra values:</p>
2080      * <ul>
2081      *   <li><em>subscription</em> - A int, the current data default subscription.</li>
2082      * </ul>
2083      *
2084      * @hide
2085      */
2086     @SystemApi
2087     @SuppressLint("ActionValue")
2088     public static final String ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED =
2089             "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED";
2090 
2091     /**
2092      * Broadcast Action: The default voice subscription has changed in a mult-SIm device.
2093      * This has the following extra values:</p>
2094      * <ul>
2095      *   <li><em>subscription</em> - A int, the current voice default subscription.</li>
2096      * </ul>
2097      *
2098      * @hide
2099      */
2100     @SystemApi
2101     @SuppressLint("ActionValue")
2102     public static final String ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED =
2103             "android.intent.action.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED";
2104 
2105     /**
2106      * Broadcast Action: This triggers a client initiated OMA-DM session to the OMA server.
2107      * <p class="note">
2108      * Open Mobile Alliance (OMA) Device Management (DM).
2109      *
2110      * This intent is used by the system components to trigger OMA-DM
2111      *
2112      * @hide
2113      */
2114     @SystemApi
2115     @SuppressLint("ActionValue")
2116     public static final String ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE =
2117             "com.android.omadm.service.CONFIGURATION_UPDATE";
2118 
2119     /**
2120      * Activity action: Show setting to reset mobile networks.
2121      *
2122      * <p>On devices with a settings activity to reset mobile networks, the activity should be
2123      * launched without additional permissions.
2124      *
2125      * <p>On some devices, this settings activity may not exist. Callers should ensure that this
2126      * case is appropriately handled.
2127      */
2128     @FlaggedApi(Flags.FLAG_RESET_MOBILE_NETWORK_SETTINGS)
2129     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
2130     public static final String ACTION_RESET_MOBILE_NETWORK_SETTINGS =
2131             "android.telephony.action.RESET_MOBILE_NETWORK_SETTINGS";
2132 
2133     //
2134     //
2135     // Device Info
2136     //
2137     //
2138 
2139     /**
2140      * Returns the software version number for the device, for example,
2141      * the IMEI/SV for GSM phones. Return null if the software version is
2142      * not available.
2143      * <p>
2144      *
2145      * @throws UnsupportedOperationException If the device does not have
2146      *          {@link PackageManager#FEATURE_TELEPHONY}.
2147      */
2148     @RequiresPermission(anyOf = {
2149             android.Manifest.permission.READ_PHONE_STATE,
2150             android.Manifest.permission.READ_BASIC_PHONE_STATE})
2151     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
2152     @Nullable
getDeviceSoftwareVersion()2153     public String getDeviceSoftwareVersion() {
2154         return getDeviceSoftwareVersion(getSlotIndex());
2155     }
2156 
2157     /**
2158      * Returns the software version number for the device, for example,
2159      * the IMEI/SV for GSM phones. Return null if the software version is
2160      * not available.
2161      * <p>
2162      * Requires Permission: READ_PHONE_STATE.
2163      *
2164      * @param slotIndex of which deviceID is returned
2165      *
2166      * @throws UnsupportedOperationException If the device does not have
2167      *          {@link PackageManager#FEATURE_TELEPHONY}.
2168      * @hide
2169      */
2170     @SystemApi
2171     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2172     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
2173     @Nullable
getDeviceSoftwareVersion(int slotIndex)2174     public String getDeviceSoftwareVersion(int slotIndex) {
2175         ITelephony telephony = getITelephony();
2176         if (telephony == null) return null;
2177 
2178         try {
2179             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
2180                     getAttributionTag());
2181         } catch (RemoteException ex) {
2182             return null;
2183         } catch (NullPointerException ex) {
2184             return null;
2185         }
2186     }
2187 
2188     /**
2189      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
2190      * or ESN for CDMA phones. Return null if device ID is not available.
2191      *
2192      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2193      * restrictions, and apps are recommended to use resettable identifiers (see <a
2194      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2195      * method can be invoked if one of the following requirements is met:
2196      * <ul>
2197      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2198      *     is a privileged permission that can only be granted to apps preloaded on the device.
2199      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2200      *     owner of an organization-owned device, or their delegates (see {@link
2201      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2202      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2203      *     active subscription.
2204      *     <li>If the calling app is the default SMS role holder (see {@link
2205      *     RoleManager#isRoleHeld(String)}).
2206      * </ul>
2207      *
2208      * <p>If the calling app does not meet one of these requirements then this method will behave
2209      * as follows:
2210      *
2211      * <ul>
2212      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2213      *     READ_PHONE_STATE permission then null is returned.</li>
2214      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2215      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2216      *     higher, then a SecurityException is thrown.</li>
2217      * </ul>
2218      *
2219      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2220      * MEID for CDMA.
2221      */
2222     @Deprecated
2223     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2224     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()2225     public String getDeviceId() {
2226         try {
2227             ITelephony telephony = getITelephony();
2228             if (telephony == null)
2229                 return null;
2230             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
2231                     mContext.getAttributionTag());
2232         } catch (RemoteException ex) {
2233             return null;
2234         } catch (NullPointerException ex) {
2235             return null;
2236         }
2237     }
2238 
2239     /**
2240      * Returns the unique device ID of a subscription, for example, the IMEI for
2241      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
2242      *
2243      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2244      * restrictions, and apps are recommended to use resettable identifiers (see <a
2245      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2246      * method can be invoked if one of the following requirements is met:
2247      * <ul>
2248      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2249      *     is a privileged permission that can only be granted to apps preloaded on the device.
2250      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2251      *     owner of an organization-owned device, or their delegates (see {@link
2252      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2253      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2254      *     active subscription.
2255      *     <li>If the calling app is the default SMS role holder (see {@link
2256      *     RoleManager#isRoleHeld(String)}).
2257      * </ul>
2258      *
2259      * <p>If the calling app does not meet one of these requirements then this method will behave
2260      * as follows:
2261      *
2262      * <ul>
2263      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2264      *     READ_PHONE_STATE permission then null is returned.</li>
2265      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2266      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2267      *     higher, then a SecurityException is thrown.</li>
2268      * </ul>
2269      *
2270      * @param slotIndex of which deviceID is returned
2271      *
2272      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2273      * MEID for CDMA.
2274      */
2275     @Deprecated
2276     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2277     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)2278     public String getDeviceId(int slotIndex) {
2279         // FIXME this assumes phoneId == slotIndex
2280         try {
2281             IPhoneSubInfo info = getSubscriberInfoService();
2282             if (info == null)
2283                 return null;
2284             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
2285                     mContext.getAttributionTag());
2286         } catch (RemoteException ex) {
2287             return null;
2288         } catch (NullPointerException ex) {
2289             return null;
2290         }
2291     }
2292 
2293     /**
2294      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2295      * available.
2296      *
2297      * See {@link #getImei(int)} for details on the required permissions and behavior
2298      * when the caller does not hold sufficient permissions.
2299      *
2300      * @throws UnsupportedOperationException If the device does not have
2301      *          {@link PackageManager#FEATURE_TELEPHONY_GSM}.
2302      */
2303     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2304     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2305     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
getImei()2306     public String getImei() {
2307         return getImei(getSlotIndex());
2308     }
2309 
2310     /**
2311      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2312      * available.
2313      *
2314      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2315      * restrictions, and apps are recommended to use resettable identifiers (see <a
2316      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2317      * method can be invoked if one of the following requirements is met:
2318      * <ul>
2319      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2320      *     is a privileged permission that can only be granted to apps preloaded on the device.
2321      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2322      *     owner of an organization-owned device, or their delegates (see {@link
2323      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2324      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2325      *     active subscription.
2326      *     <li>If the calling app is the default SMS role holder (see {@link
2327      *     RoleManager#isRoleHeld(String)}).
2328      *     <li>If the calling app has been granted the
2329      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
2330      * </ul>
2331      *
2332      * <p>If the calling app does not meet one of these requirements then this method will behave
2333      * as follows:
2334      *
2335      * <ul>
2336      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2337      *     READ_PHONE_STATE permission then null is returned.</li>
2338      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2339      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2340      *     higher, then a SecurityException is thrown.</li>
2341      * </ul>
2342      *
2343      * @param slotIndex of which IMEI is returned
2344      *
2345      * @throws UnsupportedOperationException If the device does not have
2346      *          {@link PackageManager#FEATURE_TELEPHONY_GSM}.
2347      */
2348     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2349     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2350     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
getImei(int slotIndex)2351     public String getImei(int slotIndex) {
2352         ITelephony telephony = getITelephony();
2353         if (telephony == null) return null;
2354 
2355         try {
2356             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
2357         } catch (RemoteException ex) {
2358             return null;
2359         } catch (NullPointerException ex) {
2360             return null;
2361         }
2362     }
2363 
2364     /**
2365      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2366      * available.
2367      *
2368      * @throws UnsupportedOperationException If the device does not have
2369      *          {@link PackageManager#FEATURE_TELEPHONY_GSM}.
2370      */
2371     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
2372     @Nullable
getTypeAllocationCode()2373     public String getTypeAllocationCode() {
2374         return getTypeAllocationCode(getSlotIndex());
2375     }
2376 
2377     /**
2378      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2379      * available.
2380      *
2381      * @param slotIndex of which Type Allocation Code is returned
2382      *
2383      * @throws UnsupportedOperationException If the device does not have
2384      *          {@link PackageManager#FEATURE_TELEPHONY_GSM}.
2385      */
2386     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
2387     @Nullable
getTypeAllocationCode(int slotIndex)2388     public String getTypeAllocationCode(int slotIndex) {
2389         ITelephony telephony = getITelephony();
2390         if (telephony == null) return null;
2391 
2392         try {
2393             return telephony.getTypeAllocationCodeForSlot(slotIndex);
2394         } catch (RemoteException ex) {
2395             return null;
2396         } catch (NullPointerException ex) {
2397             return null;
2398         }
2399     }
2400 
2401     /**
2402      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2403      *
2404      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2405      * restrictions, and apps are recommended to use resettable identifiers (see <a
2406      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2407      * method can be invoked if one of the following requirements is met:
2408      * <ul>
2409      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2410      *     is a privileged permission that can only be granted to apps preloaded on the device.
2411      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2412      *     owner of an organization-owned device, or their delegates (see {@link
2413      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2414      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2415      *     active subscription.
2416      *     <li>If the calling app is the default SMS role holder (see {@link
2417      *     RoleManager#isRoleHeld(String)}).
2418      * </ul>
2419      *
2420      * <p>If the calling app does not meet one of these requirements then this method will behave
2421      * as follows:
2422      *
2423      * <ul>
2424      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2425      *     READ_PHONE_STATE permission then null is returned.</li>
2426      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2427      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2428      *     higher, then a SecurityException is thrown.</li>
2429      * </ul>
2430      *
2431      * @throws UnsupportedOperationException If the device does not have
2432      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2433      */
2434     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2435     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2436     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getMeid()2437     public String getMeid() {
2438         return getMeid(getSlotIndex());
2439     }
2440 
2441     /**
2442      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2443      *
2444      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2445      * restrictions, and apps are recommended to use resettable identifiers (see <a
2446      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2447      * method can be invoked if one of the following requirements is met:
2448      * <ul>
2449      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2450      *     is a privileged permission that can only be granted to apps preloaded on the device.
2451      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2452      *     owner of an organization-owned device, or their delegates (see {@link
2453      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2454      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2455      *     active subscription.
2456      *     <li>If the calling app is the default SMS role holder (see {@link
2457      *     RoleManager#isRoleHeld(String)}).
2458      * </ul>
2459      *
2460      * <p>If the calling app does not meet one of these requirements then this method will behave
2461      * as follows:
2462      *
2463      * <ul>
2464      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2465      *     READ_PHONE_STATE permission then null is returned.</li>
2466      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2467      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2468      *     higher, then a SecurityException is thrown.</li>
2469      * </ul>
2470      *
2471      * @param slotIndex of which MEID is returned
2472      *
2473      * @throws UnsupportedOperationException If the device does not have
2474      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2475      */
2476     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2477     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2478     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getMeid(int slotIndex)2479     public String getMeid(int slotIndex) {
2480         ITelephony telephony = getITelephony();
2481         if (telephony == null) return null;
2482 
2483         try {
2484             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
2485                     getAttributionTag());
2486             if (TextUtils.isEmpty(meid)) {
2487                 Log.d(TAG, "getMeid: return null because MEID is not available");
2488                 return null;
2489             }
2490             return meid;
2491         } catch (RemoteException ex) {
2492             return null;
2493         } catch (NullPointerException ex) {
2494             return null;
2495         }
2496     }
2497 
2498     /**
2499      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2500      * available.
2501      *
2502      * @throws UnsupportedOperationException If the device does not have
2503      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2504      */
2505     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
2506     @Nullable
getManufacturerCode()2507     public String getManufacturerCode() {
2508         return getManufacturerCode(getSlotIndex());
2509     }
2510 
2511     /**
2512      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2513      * available.
2514      *
2515      * @param slotIndex of which Type Allocation Code is returned
2516      *
2517      * @throws UnsupportedOperationException If the device does not have
2518      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2519      */
2520     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
2521     @Nullable
getManufacturerCode(int slotIndex)2522     public String getManufacturerCode(int slotIndex) {
2523         ITelephony telephony = getITelephony();
2524         if (telephony == null) return null;
2525 
2526         try {
2527             return telephony.getManufacturerCodeForSlot(slotIndex);
2528         } catch (RemoteException ex) {
2529             return null;
2530         } catch (NullPointerException ex) {
2531             return null;
2532         }
2533     }
2534 
2535     /**
2536      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2537      *
2538      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2539      * restrictions, and apps are recommended to use resettable identifiers (see <a
2540      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2541      * method can be invoked if one of the following requirements is met:
2542      * <ul>
2543      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2544      *     is a privileged permission that can only be granted to apps preloaded on the device.
2545      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2546      *     owner of an organization-owned device, or their delegates (see {@link
2547      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2548      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2549      *     <li>If the calling app is the default SMS role holder (see {@link
2550      *     RoleManager#isRoleHeld(String)}).
2551      * </ul>
2552      *
2553      * <p>If the calling app does not meet one of these requirements then this method will behave
2554      * as follows:
2555      *
2556      * <ul>
2557      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2558      *     READ_PHONE_STATE permission then null is returned.</li>
2559      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2560      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2561      *     higher, then a SecurityException is thrown.</li>
2562      * </ul>
2563      *
2564      * @throws UnsupportedOperationException If the device does not have
2565      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
2566      */
2567     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2568     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2569     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getNai()2570     public String getNai() {
2571         return getNaiBySubscriberId(getSubId());
2572     }
2573 
getNaiBySubscriberId(int subId)2574     private String getNaiBySubscriberId(int subId) {
2575         try {
2576             IPhoneSubInfo info = getSubscriberInfoService();
2577             if (info == null)
2578                 return null;
2579             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2580                     mContext.getAttributionTag());
2581             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2582                 Rlog.v(TAG, "Nai = " + nai);
2583             }
2584             return nai;
2585         } catch (RemoteException ex) {
2586             return null;
2587         } catch (NullPointerException ex) {
2588             return null;
2589         }
2590     }
2591 
2592     /**
2593      * Returns the current location of the device.
2594      *<p>
2595      * If there is only one radio in the device and that radio has an LTE connection,
2596      * this method will return null. The implementation must not to try add LTE
2597      * identifiers into the existing cdma/gsm classes.
2598      *<p>
2599      * @return Current location of the device or null if not available.
2600      *
2601      * @throws UnsupportedOperationException If the device does not have
2602      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
2603      *
2604      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2605      */
2606     @Deprecated
2607     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
2608     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getCellLocation()2609     public CellLocation getCellLocation() {
2610         try {
2611             ITelephony telephony = getITelephony();
2612             if (telephony == null) {
2613                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2614                 return null;
2615             }
2616 
2617             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2618                     mContext.getAttributionTag());
2619             CellLocation cl = cellIdentity.asCellLocation();
2620             if (cl == null || cl.isEmpty()) {
2621                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2622                         + " phone type doesn't match CellLocation type");
2623                 return null;
2624             }
2625 
2626             return cl;
2627         } catch (RemoteException ex) {
2628             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2629             return null;
2630         }
2631     }
2632 
2633     /**
2634      * Returns the neighboring cell information of the device.
2635      *
2636      * @return List of NeighboringCellInfo or null if info unavailable.
2637      *
2638      * @throws UnsupportedOperationException If the device does not have
2639      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
2640      * @removed
2641      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2642      *             from NeighboringCellInfo, including LTE cell information.
2643      */
2644     @Deprecated
2645     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
2646     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNeighboringCellInfo()2647     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2648         try {
2649             ITelephony telephony = getITelephony();
2650             if (telephony == null)
2651                 return null;
2652             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2653                     mContext.getAttributionTag());
2654         } catch (RemoteException ex) {
2655             return null;
2656         } catch (NullPointerException ex) {
2657             return null;
2658         }
2659     }
2660 
2661     /** No phone radio. */
2662     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2663     /** Phone radio is GSM. */
2664     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2665     /** Phone radio is CDMA. */
2666     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2667     /** Phone is via SIP. */
2668     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2669 
2670     /**
2671      * Phone is via IMS.
2672      *
2673      * @hide
2674      */
2675     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2676 
2677     /**
2678      * Phone is via Third Party.
2679      *
2680      * @hide
2681      */
2682     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2683 
2684     /**
2685      * Returns the current phone type.
2686      * TODO: This is a last minute change and hence hidden.
2687      *
2688      * @see #PHONE_TYPE_NONE
2689      * @see #PHONE_TYPE_GSM
2690      * @see #PHONE_TYPE_CDMA
2691      * @see #PHONE_TYPE_SIP
2692      *
2693      * @throws UnsupportedOperationException If the device does not have
2694      *          {@link PackageManager#FEATURE_TELEPHONY}.
2695      * {@hide}
2696      */
2697     @SystemApi
2698     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
getCurrentPhoneType()2699     public int getCurrentPhoneType() {
2700         return getCurrentPhoneType(getSubId());
2701     }
2702 
2703     /**
2704      * Returns a constant indicating the device phone type for a subscription.
2705      *
2706      * @see #PHONE_TYPE_NONE
2707      * @see #PHONE_TYPE_GSM
2708      * @see #PHONE_TYPE_CDMA
2709      *
2710      * @param subId for which phone type is returned
2711      *
2712      * @throws UnsupportedOperationException If the device does not have
2713      *          {@link PackageManager#FEATURE_TELEPHONY}.
2714      * @hide
2715      */
2716     @SystemApi
2717     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
getCurrentPhoneType(int subId)2718     public int getCurrentPhoneType(int subId) {
2719         int phoneId;
2720         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2721             // if we don't have any sims, we don't have subscriptions, but we
2722             // still may want to know what type of phone we've got.
2723             phoneId = 0;
2724         } else {
2725             phoneId = SubscriptionManager.getPhoneId(subId);
2726         }
2727 
2728         return getCurrentPhoneTypeForSlot(phoneId);
2729     }
2730 
2731     /**
2732      * See getCurrentPhoneType.
2733      *
2734      * @hide
2735      */
getCurrentPhoneTypeForSlot(int slotIndex)2736     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2737         try{
2738             ITelephony telephony = getITelephony();
2739             if (telephony != null) {
2740                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2741             } else {
2742                 // This can happen when the ITelephony interface is not up yet.
2743                 return getPhoneTypeFromProperty(slotIndex);
2744             }
2745         } catch (RemoteException ex) {
2746             // This shouldn't happen in the normal case, as a backup we
2747             // read from the system property.
2748             return getPhoneTypeFromProperty(slotIndex);
2749         } catch (NullPointerException ex) {
2750             // This shouldn't happen in the normal case, as a backup we
2751             // read from the system property.
2752             return getPhoneTypeFromProperty(slotIndex);
2753         }
2754     }
2755 
2756     /**
2757      * Returns a constant indicating the device phone type.  This
2758      * indicates the type of radio used to transmit voice calls.
2759      *
2760      * @see #PHONE_TYPE_NONE
2761      * @see #PHONE_TYPE_GSM
2762      * @see #PHONE_TYPE_CDMA
2763      * @see #PHONE_TYPE_SIP
2764      *
2765      * @throws UnsupportedOperationException If the device does not have
2766      *          {@link PackageManager#FEATURE_TELEPHONY}.
2767      */
2768     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
getPhoneType()2769     public int getPhoneType() {
2770         if (!isVoiceCapable()) {
2771             return PHONE_TYPE_NONE;
2772         }
2773         return getCurrentPhoneType();
2774     }
2775 
2776     /** {@hide} */
2777     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2778     private int getPhoneTypeFromProperty(int phoneId) {
2779         Integer type = getTelephonyProperty(
2780                 phoneId, TelephonyProperties.current_active_phone(), null);
2781         if (type != null) return type;
2782         return getPhoneTypeFromNetworkType(phoneId);
2783     }
2784 
2785     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2786     private int getPhoneTypeFromNetworkType(int phoneId) {
2787         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2788         // use the system property for default network type.
2789         // This is a fail safe, and can only happen at first boot.
2790         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2791         if (mode != null) {
2792             return TelephonyManager.getPhoneType(mode);
2793         }
2794         return TelephonyManager.PHONE_TYPE_NONE;
2795     }
2796 
2797     /**
2798      * This function returns the type of the phone, depending
2799      * on the network mode.
2800      *
2801      * @param networkMode
2802      * @return Phone Type
2803      *
2804      * @hide
2805      */
2806     @UnsupportedAppUsage
getPhoneType(int networkMode)2807     public static int getPhoneType(int networkMode) {
2808         switch(networkMode) {
2809         case RILConstants.NETWORK_MODE_CDMA:
2810         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2811         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2812             return PhoneConstants.PHONE_TYPE_CDMA;
2813 
2814         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2815         case RILConstants.NETWORK_MODE_GSM_ONLY:
2816         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2817         case RILConstants.NETWORK_MODE_GSM_UMTS:
2818         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2819         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2820         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2821         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2822         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2823         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2824         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2825         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2826         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2827         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2828         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2829         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2830             return PhoneConstants.PHONE_TYPE_GSM;
2831 
2832         // Use CDMA Phone for the global mode including CDMA
2833         case RILConstants.NETWORK_MODE_GLOBAL:
2834         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2835         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2836             return PhoneConstants.PHONE_TYPE_CDMA;
2837 
2838         case RILConstants.NETWORK_MODE_LTE_ONLY:
2839             if (TelephonyProperties.lte_on_cdma_device().orElse(
2840                     PhoneConstants.LTE_ON_CDMA_FALSE) == PhoneConstants.LTE_ON_CDMA_TRUE) {
2841                 return PhoneConstants.PHONE_TYPE_CDMA;
2842             } else {
2843                 return PhoneConstants.PHONE_TYPE_GSM;
2844             }
2845         default:
2846             return PhoneConstants.PHONE_TYPE_GSM;
2847         }
2848     }
2849 
2850     /**
2851      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2852      * @hide
2853      */
2854     @SystemApi
getMaxNumberVerificationTimeoutMillis()2855     public static long getMaxNumberVerificationTimeoutMillis() {
2856         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2857     }
2858 
2859     //
2860     //
2861     // Current Network
2862     //
2863     //
2864 
2865     /**
2866      * Returns the alphabetic name of current registered operator.
2867      * <p>
2868      * Availability: Only when user is registered to a network. Result may be
2869      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2870      * on a CDMA network).
2871      */
2872     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkOperatorName()2873     public String getNetworkOperatorName() {
2874         return getNetworkOperatorName(getSubId());
2875     }
2876 
2877     /**
2878      * Returns the alphabetic name of current registered operator
2879      * for a particular subscription.
2880      * <p>
2881      * Availability: Only when user is registered to a network. Result may be
2882      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2883      * on a CDMA network).
2884      * @param subId
2885      * @hide
2886      */
2887     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2888     public String getNetworkOperatorName(int subId) {
2889         int phoneId = SubscriptionManager.getPhoneId(subId);
2890         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2891     }
2892 
2893     /**
2894      * Returns the numeric name (MCC+MNC) of current registered operator.
2895      * <p>
2896      * Availability: Only when user is registered to a network. Result may be
2897      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2898      * on a CDMA network).
2899      */
2900     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkOperator()2901     public String getNetworkOperator() {
2902         return getNetworkOperatorForPhone(getPhoneId());
2903     }
2904 
2905     /**
2906      * Returns the numeric name (MCC+MNC) of current registered operator
2907      * for a particular subscription.
2908      * <p>
2909      * Availability: Only when user is registered to a network. Result may be
2910      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2911      * on a CDMA network).
2912      *
2913      * @param subId
2914      * @hide
2915      */
2916     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2917     public String getNetworkOperator(int subId) {
2918         int phoneId = SubscriptionManager.getPhoneId(subId);
2919         return getNetworkOperatorForPhone(phoneId);
2920      }
2921 
2922     /**
2923      * Returns the numeric name (MCC+MNC) of current registered operator
2924      * for a particular subscription.
2925      * <p>
2926      * Availability: Only when user is registered to a network. Result may be
2927      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2928      * on a CDMA network).
2929      *
2930      * @param phoneId
2931      * @hide
2932      **/
2933     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2934     public String getNetworkOperatorForPhone(int phoneId) {
2935         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2936     }
2937 
2938 
2939     /**
2940      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2941      * network specifier is used by {@link
2942      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2943      * android.net.NetworkRequest} that connects through the subscription.
2944      *
2945      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2946      * @see #createForSubscriptionId(int)
2947      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2948      */
2949     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getNetworkSpecifier()2950     public String getNetworkSpecifier() {
2951         return String.valueOf(getSubId());
2952     }
2953 
2954     /**
2955      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
2956      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
2957      * default values.
2958      *
2959      * <p>This method may take several seconds to complete, so it should only be called from a
2960      * worker thread.
2961      *
2962      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2963      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2964      *
2965      * @see CarrierConfigManager#getConfigForSubId(int)
2966      * @see #createForSubscriptionId(int)
2967      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2968      *
2969      * @throws UnsupportedOperationException If the device does not have
2970      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
2971      */
2972     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2973     @WorkerThread
2974     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2975     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierConfig()2976     public PersistableBundle getCarrierConfig() {
2977         CarrierConfigManager carrierConfigManager = mContext
2978                 .getSystemService(CarrierConfigManager.class);
2979         return carrierConfigManager.getConfigForSubId(getSubId());
2980     }
2981 
2982     /**
2983      * Returns true if the device is considered roaming on the current
2984      * network, for GSM purposes.
2985      * <p>
2986      * Availability: Only when user registered to a network.
2987      */
2988     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isNetworkRoaming()2989     public boolean isNetworkRoaming() {
2990         return isNetworkRoaming(getSubId());
2991     }
2992 
2993     /**
2994      * Returns true if the device is considered roaming on the current
2995      * network for a subscription.
2996      * <p>
2997      * Availability: Only when user registered to a network.
2998      *
2999      * @param subId
3000      * @hide
3001      */
3002     @UnsupportedAppUsage
isNetworkRoaming(int subId)3003     public boolean isNetworkRoaming(int subId) {
3004         int phoneId = SubscriptionManager.getPhoneId(subId);
3005         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
3006     }
3007 
3008     /**
3009      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
3010      * the current registered operator or the cell nearby, if available.
3011      *
3012      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
3013      * if on a CDMA network).
3014      * <p>
3015      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
3016      * available.
3017      *
3018      * @throws UnsupportedOperationException If the device does not have
3019      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3020      */
3021     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkCountryIso()3022     public String getNetworkCountryIso() {
3023         return getNetworkCountryIso(getSlotIndex());
3024     }
3025 
3026     /**
3027      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
3028      * the current registered operator or the cell nearby, if available. This is same as
3029      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
3030      * accessing network country info from the SIM slot that does not have SIM inserted.
3031      *
3032      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
3033      * if on a CDMA network).
3034      * <p>
3035      *
3036      * @param slotIndex the SIM slot index to get network country ISO.
3037      *
3038      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
3039      * available.
3040      *
3041      * @throws IllegalArgumentException when the slotIndex is invalid.
3042      * @throws UnsupportedOperationException If the device does not have
3043      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3044      *
3045      */
3046     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
3047     @NonNull
getNetworkCountryIso(int slotIndex)3048     public String getNetworkCountryIso(int slotIndex) {
3049         try {
3050             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
3051                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
3052                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
3053             }
3054 
3055             ITelephony telephony = getITelephony();
3056             if (telephony == null) return "";
3057             return telephony.getNetworkCountryIsoForPhone(slotIndex);
3058         } catch (RemoteException ex) {
3059             return "";
3060         }
3061     }
3062 
3063     /**
3064      * @hide
3065      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
3066      */
3067     @Deprecated
3068     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
3069             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)3070     public String getNetworkCountryIsoForPhone(int phoneId) {
3071         return getNetworkCountryIso(phoneId);
3072     }
3073 
3074     /*
3075      * When adding a network type to the list below, make sure to add the correct icon to
3076      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
3077      * Do not add negative types.
3078      */
3079     /** Network type is unknown */
3080     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
3081     /** Current network is GPRS */
3082     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
3083     /** Current network is EDGE */
3084     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
3085     /** Current network is UMTS */
3086     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
3087     /** Current network is CDMA: Either IS95A or IS95B*/
3088     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
3089     /** Current network is EVDO revision 0*/
3090     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
3091     /** Current network is EVDO revision A*/
3092     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
3093     /** Current network is 1xRTT*/
3094     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
3095     /** Current network is HSDPA */
3096     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
3097     /** Current network is HSUPA */
3098     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
3099     /** Current network is HSPA */
3100     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
3101     /**
3102      * Current network is iDen
3103      * @deprecated Legacy network type no longer being used starting in Android U.
3104      */
3105     @Deprecated
3106     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
3107     /** Current network is EVDO revision B*/
3108     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
3109     /** Current network is LTE */
3110     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
3111     /** Current network is eHRPD */
3112     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
3113     /** Current network is HSPA+ */
3114     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
3115     /** Current network is GSM */
3116     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
3117     /** Current network is TD_SCDMA */
3118     public static final int NETWORK_TYPE_TD_SCDMA =
3119             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
3120     /** Current network is IWLAN */
3121     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
3122     /** Current network is LTE_CA {@hide} */
3123     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3124     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
3125     /**
3126      * Current network is NR (New Radio) 5G.
3127      * This will only be returned for 5G SA.
3128      * For 5G NSA, the network type will be {@link #NETWORK_TYPE_LTE}.
3129      */
3130     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
3131 
3132     private static final @NetworkType int[] NETWORK_TYPES = {
3133             NETWORK_TYPE_GPRS,
3134             NETWORK_TYPE_EDGE,
3135             NETWORK_TYPE_UMTS,
3136             NETWORK_TYPE_CDMA,
3137             NETWORK_TYPE_EVDO_0,
3138             NETWORK_TYPE_EVDO_A,
3139             NETWORK_TYPE_1xRTT,
3140             NETWORK_TYPE_HSDPA,
3141             NETWORK_TYPE_HSUPA,
3142             NETWORK_TYPE_HSPA,
3143             NETWORK_TYPE_IDEN,
3144             NETWORK_TYPE_EVDO_B,
3145             NETWORK_TYPE_LTE,
3146             NETWORK_TYPE_EHRPD,
3147             NETWORK_TYPE_HSPAP,
3148             NETWORK_TYPE_GSM,
3149             NETWORK_TYPE_TD_SCDMA,
3150             NETWORK_TYPE_IWLAN,
3151             NETWORK_TYPE_LTE_CA,
3152             NETWORK_TYPE_NR
3153     };
3154 
3155     /**
3156      * Returns an array of all valid network types.
3157      *
3158      * @return An integer array containing all valid network types in no particular order.
3159      *
3160      * @hide
3161      */
3162     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getAllNetworkTypes()3163     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
3164         return NETWORK_TYPES.clone();
3165     }
3166 
3167     /**
3168      * Return the current data network type.
3169      *
3170      * @deprecated use {@link #getDataNetworkType()}
3171      * @return the NETWORK_TYPE_xxxx for current data connection.
3172      *
3173      * @throws UnsupportedOperationException If the device does not have
3174      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3175      */
3176     @Deprecated
3177     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3178     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkType()3179     public @NetworkType int getNetworkType() {
3180         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3181     }
3182 
3183     /**
3184      * Returns a constant indicating the radio technology (network type)
3185      * currently in use on the device for a subscription.
3186      * @return the network type
3187      *
3188      * @param subId for which network type is returned
3189      *
3190      * @see #NETWORK_TYPE_UNKNOWN
3191      * @see #NETWORK_TYPE_GPRS
3192      * @see #NETWORK_TYPE_EDGE
3193      * @see #NETWORK_TYPE_UMTS
3194      * @see #NETWORK_TYPE_HSDPA
3195      * @see #NETWORK_TYPE_HSUPA
3196      * @see #NETWORK_TYPE_HSPA
3197      * @see #NETWORK_TYPE_CDMA
3198      * @see #NETWORK_TYPE_EVDO_0
3199      * @see #NETWORK_TYPE_EVDO_A
3200      * @see #NETWORK_TYPE_EVDO_B
3201      * @see #NETWORK_TYPE_1xRTT
3202      * @see #NETWORK_TYPE_IDEN
3203      * @see #NETWORK_TYPE_LTE
3204      * @see #NETWORK_TYPE_EHRPD
3205      * @see #NETWORK_TYPE_HSPAP
3206      * @see #NETWORK_TYPE_NR
3207      *
3208      * @hide
3209      */
3210     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3211     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)3212     public int getNetworkType(int subId) {
3213         try {
3214             ITelephony telephony = getITelephony();
3215             if (telephony != null) {
3216                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
3217                         getAttributionTag());
3218             } else {
3219                 // This can happen when the ITelephony interface is not up yet.
3220                 return NETWORK_TYPE_UNKNOWN;
3221             }
3222         } catch (RemoteException ex) {
3223             // This shouldn't happen in the normal case
3224             return NETWORK_TYPE_UNKNOWN;
3225         } catch (NullPointerException ex) {
3226             // This could happen before phone restarts due to crashing
3227             return NETWORK_TYPE_UNKNOWN;
3228         }
3229     }
3230 
3231     /**
3232      * Returns a constant indicating the radio technology (network type)
3233      * currently in use on the device for data transmission.
3234      *
3235      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
3236      * subId. Otherwise, applies to {@link SubscriptionManager#getActiveDataSubscriptionId()}.
3237      *
3238      * Note: Before {@link SubscriptionManager#getActiveDataSubscriptionId()} was introduced in API
3239      * level 30, it was applied to {@link SubscriptionManager#getDefaultDataSubscriptionId()} which
3240      * may be different now from {@link SubscriptionManager#getActiveDataSubscriptionId()}, e.g.
3241      * when opportunistic network is providing cellular internet connection to the user.
3242      *
3243      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3244      * or {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
3245      * READ_BASIC_PHONE_STATE} or that the calling app has carrier privileges
3246      * (see {@link #hasCarrierPrivileges}).
3247      *
3248      * @return the network type
3249      *
3250      * @see #NETWORK_TYPE_UNKNOWN
3251      * @see #NETWORK_TYPE_GPRS
3252      * @see #NETWORK_TYPE_EDGE
3253      * @see #NETWORK_TYPE_UMTS
3254      * @see #NETWORK_TYPE_HSDPA
3255      * @see #NETWORK_TYPE_HSUPA
3256      * @see #NETWORK_TYPE_HSPA
3257      * @see #NETWORK_TYPE_CDMA
3258      * @see #NETWORK_TYPE_EVDO_0
3259      * @see #NETWORK_TYPE_EVDO_A
3260      * @see #NETWORK_TYPE_EVDO_B
3261      * @see #NETWORK_TYPE_1xRTT
3262      * @see #NETWORK_TYPE_IDEN
3263      * @see #NETWORK_TYPE_LTE
3264      * @see #NETWORK_TYPE_EHRPD
3265      * @see #NETWORK_TYPE_HSPAP
3266      * @see #NETWORK_TYPE_NR
3267      *
3268      * @throws UnsupportedOperationException If the device does not have
3269      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3270      */
3271     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3272     @RequiresPermission(anyOf = {
3273             android.Manifest.permission.READ_PHONE_STATE,
3274             android.Manifest.permission.READ_BASIC_PHONE_STATE})
3275     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getDataNetworkType()3276     public @NetworkType int getDataNetworkType() {
3277         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3278     }
3279 
3280     /**
3281      * Returns a constant indicating the radio technology (network type)
3282      * currently in use on the device for data transmission for a subscription
3283      * @return the network type
3284      *
3285      * @param subId for which network type is returned
3286      * @hide
3287      */
3288     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3289     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)3290     public int getDataNetworkType(int subId) {
3291         try{
3292             ITelephony telephony = getITelephony();
3293             if (telephony != null) {
3294                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
3295                         getAttributionTag());
3296             } else {
3297                 // This can happen when the ITelephony interface is not up yet.
3298                 return NETWORK_TYPE_UNKNOWN;
3299             }
3300         } catch(RemoteException ex) {
3301             // This shouldn't happen in the normal case
3302             return NETWORK_TYPE_UNKNOWN;
3303         } catch (NullPointerException ex) {
3304             // This could happen before phone restarts due to crashing
3305             return NETWORK_TYPE_UNKNOWN;
3306         }
3307     }
3308 
3309     /**
3310      * Returns the NETWORK_TYPE_xxxx for voice
3311      *
3312      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3313      * or {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
3314      * READ_BASIC_PHONE_STATE} or that the calling app has carrier privileges
3315      * (see {@link #hasCarrierPrivileges}).
3316      *
3317      * @throws UnsupportedOperationException If the device does not have
3318      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
3319      */
3320     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3321     @RequiresPermission(anyOf = {
3322             android.Manifest.permission.READ_PHONE_STATE,
3323             android.Manifest.permission.READ_BASIC_PHONE_STATE})
3324     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceNetworkType()3325     public @NetworkType int getVoiceNetworkType() {
3326         return getVoiceNetworkType(getSubId());
3327     }
3328 
3329     /**
3330      * Returns the NETWORK_TYPE_xxxx for voice for a subId
3331      * @hide
3332      */
3333     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3334     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)3335     public int getVoiceNetworkType(int subId) {
3336         try{
3337             ITelephony telephony = getITelephony();
3338             if (telephony != null) {
3339                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
3340                         getAttributionTag());
3341             } else {
3342                 // This can happen when the ITelephony interface is not up yet.
3343                 return NETWORK_TYPE_UNKNOWN;
3344             }
3345         } catch(RemoteException ex) {
3346             // This shouldn't happen in the normal case
3347             return NETWORK_TYPE_UNKNOWN;
3348         } catch (NullPointerException ex) {
3349             // This could happen before phone restarts due to crashing
3350             return NETWORK_TYPE_UNKNOWN;
3351         }
3352     }
3353 
3354     /**
3355      * Returns a string representation of the radio technology (network type)
3356      * currently in use on the device.
3357      * @return the name of the radio technology
3358      *
3359      * @hide pending API council review
3360      */
3361     @UnsupportedAppUsage
getNetworkTypeName()3362     public String getNetworkTypeName() {
3363         return getNetworkTypeName(getNetworkType());
3364     }
3365 
3366     /**
3367      * Returns a string representation of the radio technology (network type)
3368      * currently in use on the device.
3369      * @param subId for which network type is returned
3370      * @return the name of the radio technology
3371      *
3372      */
3373     /** {@hide} */
3374     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)3375     public static String getNetworkTypeName(@NetworkType int type) {
3376         switch (type) {
3377             case NETWORK_TYPE_GPRS:
3378                 return "GPRS";
3379             case NETWORK_TYPE_EDGE:
3380                 return "EDGE";
3381             case NETWORK_TYPE_UMTS:
3382                 return "UMTS";
3383             case NETWORK_TYPE_HSDPA:
3384                 return "HSDPA";
3385             case NETWORK_TYPE_HSUPA:
3386                 return "HSUPA";
3387             case NETWORK_TYPE_HSPA:
3388                 return "HSPA";
3389             case NETWORK_TYPE_CDMA:
3390                 return "CDMA";
3391             case NETWORK_TYPE_EVDO_0:
3392                 return "CDMA - EvDo rev. 0";
3393             case NETWORK_TYPE_EVDO_A:
3394                 return "CDMA - EvDo rev. A";
3395             case NETWORK_TYPE_EVDO_B:
3396                 return "CDMA - EvDo rev. B";
3397             case NETWORK_TYPE_1xRTT:
3398                 return "CDMA - 1xRTT";
3399             case NETWORK_TYPE_LTE:
3400                 return "LTE";
3401             case NETWORK_TYPE_EHRPD:
3402                 return "CDMA - eHRPD";
3403             case NETWORK_TYPE_IDEN:
3404                 return "iDEN";
3405             case NETWORK_TYPE_HSPAP:
3406                 return "HSPA+";
3407             case NETWORK_TYPE_GSM:
3408                 return "GSM";
3409             case NETWORK_TYPE_TD_SCDMA:
3410                 return "TD_SCDMA";
3411             case NETWORK_TYPE_IWLAN:
3412                 return "IWLAN";
3413             case NETWORK_TYPE_LTE_CA:
3414                 return "LTE_CA";
3415             case NETWORK_TYPE_NR:
3416                 return "NR";
3417             case NETWORK_TYPE_UNKNOWN:
3418                 return "UNKNOWN";
3419             default:
3420                 return "UNKNOWN(" + type + ")";
3421         }
3422     }
3423 
3424     /**
3425      * Returns the bitmask for a given technology (network type)
3426      * @param networkType for which bitmask is returned
3427      * @return the network type bitmask
3428      * {@hide}
3429      */
getBitMaskForNetworkType(@etworkType int networkType)3430     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
3431         switch(networkType) {
3432             case NETWORK_TYPE_GSM:
3433                 return NETWORK_TYPE_BITMASK_GSM;
3434             case NETWORK_TYPE_GPRS:
3435                 return NETWORK_TYPE_BITMASK_GPRS;
3436             case NETWORK_TYPE_EDGE:
3437                 return NETWORK_TYPE_BITMASK_EDGE;
3438             case NETWORK_TYPE_CDMA:
3439                 return NETWORK_TYPE_BITMASK_CDMA;
3440             case NETWORK_TYPE_1xRTT:
3441                 return NETWORK_TYPE_BITMASK_1xRTT;
3442             case NETWORK_TYPE_EVDO_0:
3443                 return NETWORK_TYPE_BITMASK_EVDO_0;
3444             case NETWORK_TYPE_EVDO_A:
3445                 return NETWORK_TYPE_BITMASK_EVDO_A;
3446             case NETWORK_TYPE_EVDO_B:
3447                 return NETWORK_TYPE_BITMASK_EVDO_B;
3448             case NETWORK_TYPE_EHRPD:
3449                 return NETWORK_TYPE_BITMASK_EHRPD;
3450             case NETWORK_TYPE_HSUPA:
3451                 return NETWORK_TYPE_BITMASK_HSUPA;
3452             case NETWORK_TYPE_HSDPA:
3453                 return NETWORK_TYPE_BITMASK_HSDPA;
3454             case NETWORK_TYPE_HSPA:
3455                 return NETWORK_TYPE_BITMASK_HSPA;
3456             case NETWORK_TYPE_HSPAP:
3457                 return NETWORK_TYPE_BITMASK_HSPAP;
3458             case NETWORK_TYPE_UMTS:
3459                 return NETWORK_TYPE_BITMASK_UMTS;
3460             case NETWORK_TYPE_TD_SCDMA:
3461                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
3462             case NETWORK_TYPE_LTE:
3463             case NETWORK_TYPE_LTE_CA:
3464                 return NETWORK_TYPE_BITMASK_LTE;
3465             case NETWORK_TYPE_NR:
3466                 return NETWORK_TYPE_BITMASK_NR;
3467             case NETWORK_TYPE_IWLAN:
3468                 return NETWORK_TYPE_BITMASK_IWLAN;
3469             case NETWORK_TYPE_IDEN:
3470                 return NETWORK_TYPE_BITMASK_IDEN;
3471             default:
3472                 return NETWORK_TYPE_BITMASK_UNKNOWN;
3473         }
3474     }
3475 
3476     //
3477     //
3478     // SIM Card
3479     //
3480     //
3481 
3482     /** @hide */
3483     @IntDef(prefix = {"SIM_STATE_"},
3484             value = {
3485                     SIM_STATE_UNKNOWN,
3486                     SIM_STATE_ABSENT,
3487                     SIM_STATE_PIN_REQUIRED,
3488                     SIM_STATE_PUK_REQUIRED,
3489                     SIM_STATE_NETWORK_LOCKED,
3490                     SIM_STATE_READY,
3491                     SIM_STATE_NOT_READY,
3492                     SIM_STATE_PERM_DISABLED,
3493                     SIM_STATE_CARD_IO_ERROR,
3494                     SIM_STATE_CARD_RESTRICTED,
3495                     SIM_STATE_LOADED,
3496                     SIM_STATE_PRESENT,
3497             })
3498     @Retention(RetentionPolicy.SOURCE)
3499     public @interface SimState {}
3500 
3501     /**
3502      * SIM card state: Unknown. Signifies that the SIM is in transition
3503      * between states. For example, when the user inputs the SIM pin
3504      * under PIN_REQUIRED state, a query for sim status returns
3505      * this state before turning to SIM_STATE_READY.
3506      *
3507      * These are the ordinal value of IccCardConstants.State.
3508      */
3509 
3510     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
3511     /** SIM card state: no SIM card is available in the device */
3512     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3513     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3514     public static final int SIM_STATE_PIN_REQUIRED =
3515             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3516     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3517     public static final int SIM_STATE_PUK_REQUIRED =
3518             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3519     /** SIM card state: Locked: requires a network PIN to unlock */
3520     public static final int SIM_STATE_NETWORK_LOCKED =
3521             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3522     /** SIM card state: Ready */
3523     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3524     /** SIM card state: SIM Card is NOT READY */
3525     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3526     /** SIM card state: SIM Card Error, permanently disabled */
3527     public static final int SIM_STATE_PERM_DISABLED =
3528             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3529     /** SIM card state: SIM Card Error, present but faulty */
3530     public static final int SIM_STATE_CARD_IO_ERROR =
3531             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3532     /** SIM card state: SIM Card restricted, present but not usable due to
3533      * carrier restrictions.
3534      */
3535     public static final int SIM_STATE_CARD_RESTRICTED =
3536             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3537     /**
3538      * SIM card state: Loaded: SIM card applications have been loaded
3539      * @hide
3540      */
3541     @SystemApi
3542     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3543     /**
3544      * SIM card state: SIM Card is present
3545      * @hide
3546      */
3547     @SystemApi
3548     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3549 
3550     /**
3551      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3552      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3553      *
3554      * @hide
3555      */
3556     @SystemApi
3557     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3558 
3559     /**
3560      * Broadcast Action: The sim card state has changed.
3561      * The intent will have the following extra values:</p>
3562      * <dl>
3563      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3564      *   <dd>The sim card state. One of:
3565      *     <dl>
3566      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3567      *       <dd>SIM card not found</dd>
3568      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3569      *       <dd>SIM card IO error</dd>
3570      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3571      *       <dd>SIM card is restricted</dd>
3572      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3573      *       <dd>SIM card is present</dd>
3574      *     </dl>
3575      *   </dd>
3576      * </dl>
3577      *
3578      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3579      *
3580      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3581      *
3582      * <p class="note">This is a protected intent that can only be sent by the system.
3583      * @hide
3584      */
3585     @SystemApi
3586     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3587     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3588             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3589 
3590     /**
3591      * Broadcast Action: The sim application state has changed.
3592      * The intent will have the following extra values:</p>
3593      * <dl>
3594      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3595      *   <dd>The sim application state. One of:
3596      *     <dl>
3597      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3598      *       <dd>SIM card applications not ready</dd>
3599      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3600      *       <dd>SIM card PIN locked</dd>
3601      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3602      *       <dd>SIM card PUK locked</dd>
3603      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3604      *       <dd>SIM card network locked</dd>
3605      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3606      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3607      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3608      *       <dd>SIM card data loaded</dd>
3609      *     </dl>
3610      *   </dd>
3611      * </dl>
3612      *
3613      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3614      *
3615      * <p class="note">The current state can also be queried using
3616      * {@link #getSimApplicationState()}.
3617      *
3618      * <p class="note">This is a protected intent that can only be sent by the system.
3619      * @hide
3620      */
3621     @SystemApi
3622     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3623     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3624             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3625 
3626     /**
3627      * Broadcast Action: Status of the SIM slots on the device has changed.
3628      *
3629      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3630      *
3631      * <p class="note">The status can be queried using
3632      * {@link #getUiccSlotsInfo()}
3633      *
3634      * <p class="note">This is a protected intent that can only be sent by the system.
3635      * @hide
3636      */
3637     @SystemApi
3638     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3639     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3640             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3641 
3642     /**
3643      * Broadcast Action: A debug code has been entered in the dialer.
3644      * <p>
3645      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3646      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3647      * (see {@link #hasCarrierPrivileges}).
3648      * <p>
3649      * These "secret codes" are used to activate developer menus by dialing certain codes.
3650      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3651      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3652      * receiver would be woken up even if it is not currently running.
3653      * <p>
3654      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3655      * in the next Android version.
3656      * Before that both of these two actions will be broadcast.
3657      */
3658     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3659     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3660 
3661     /**
3662      * This API is used to check if there is an ICC card present in the device.
3663      *
3664      * An ICC card is a smart card that contains a subscriber identity module (SIM) and is used
3665      * to identify and authenticate users to a mobile network.
3666      *
3667      * Note: In case of embedded SIM there is an ICC card always present irrespective
3668      * of whether an active SIM profile is present or not so this API would always return true.
3669      *
3670      * @return true if a ICC card is present.
3671      *
3672      * @throws UnsupportedOperationException If the device does not have
3673      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3674      */
3675     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
hasIccCard()3676     public boolean hasIccCard() {
3677         return hasIccCard(getSlotIndex());
3678     }
3679 
3680     /**
3681      * @return true if a ICC card is present for a subscription
3682      *
3683      * @param slotIndex for which icc card presence is checked
3684      */
3685     /** {@hide} */
3686     // FIXME Input argument slotIndex should be of type int
3687     @UnsupportedAppUsage
hasIccCard(int slotIndex)3688     public boolean hasIccCard(int slotIndex) {
3689 
3690         try {
3691             ITelephony telephony = getITelephony();
3692             if (telephony == null)
3693                 return false;
3694             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3695         } catch (RemoteException ex) {
3696             // Assume no ICC card if remote exception which shouldn't happen
3697             return false;
3698         } catch (NullPointerException ex) {
3699             // This could happen before phone restarts due to crashing
3700             return false;
3701         }
3702     }
3703 
3704     /**
3705      * Returns a constant indicating the state of the default SIM card.
3706      *
3707      * @see #SIM_STATE_UNKNOWN
3708      * @see #SIM_STATE_ABSENT
3709      * @see #SIM_STATE_PIN_REQUIRED
3710      * @see #SIM_STATE_PUK_REQUIRED
3711      * @see #SIM_STATE_NETWORK_LOCKED
3712      * @see #SIM_STATE_READY
3713      * @see #SIM_STATE_NOT_READY
3714      * @see #SIM_STATE_PERM_DISABLED
3715      * @see #SIM_STATE_CARD_IO_ERROR
3716      * @see #SIM_STATE_CARD_RESTRICTED
3717      *
3718      * @throws UnsupportedOperationException If the device does not have
3719      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3720      */
3721     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimState()3722     public @SimState int getSimState() {
3723         int simState = getSimStateIncludingLoaded();
3724         if (simState == SIM_STATE_LOADED) {
3725             simState = SIM_STATE_READY;
3726         }
3727         return simState;
3728     }
3729 
getSimStateIncludingLoaded()3730     private @SimState int getSimStateIncludingLoaded() {
3731         int slotIndex = getSlotIndex();
3732         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3733         // sim state
3734         if (slotIndex < 0) {
3735             // query for all slots and return absent if all sim states are absent, otherwise
3736             // return unknown
3737             for (int i = 0; i < getPhoneCount(); i++) {
3738                 int simState = getSimState(i);
3739                 if (simState != SIM_STATE_ABSENT) {
3740                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3741                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3742                     return SIM_STATE_UNKNOWN;
3743                 }
3744             }
3745             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3746                     "state as absent");
3747             return SIM_STATE_ABSENT;
3748         }
3749         return getSimStateForSlotIndex(slotIndex);
3750     }
3751 
3752     /**
3753      * Returns a constant indicating the state of the default SIM card.
3754      *
3755      * @see #SIM_STATE_UNKNOWN
3756      * @see #SIM_STATE_ABSENT
3757      * @see #SIM_STATE_CARD_IO_ERROR
3758      * @see #SIM_STATE_CARD_RESTRICTED
3759      * @see #SIM_STATE_PRESENT
3760      *
3761      * @throws UnsupportedOperationException If the device does not have
3762      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3763      * @hide
3764      */
3765     @SystemApi
3766     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCardState()3767     public @SimState int getSimCardState() {
3768         int simState = getSimState();
3769         return getSimCardStateFromSimState(simState);
3770     }
3771 
3772     /**
3773      * Returns a constant indicating the state of the device SIM card in a physical slot.
3774      *
3775      * @param physicalSlotIndex physical slot index
3776      *
3777      * @see #SIM_STATE_UNKNOWN
3778      * @see #SIM_STATE_ABSENT
3779      * @see #SIM_STATE_CARD_IO_ERROR
3780      * @see #SIM_STATE_CARD_RESTRICTED
3781      * @see #SIM_STATE_PRESENT
3782      *
3783      * @throws UnsupportedOperationException If the device does not have
3784      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3785      * @hide
3786      * @deprecated instead use {@link #getSimCardState(int, int)}
3787      */
3788     @SystemApi
3789     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3790     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
3791     @Deprecated
getSimCardState(int physicalSlotIndex)3792     public @SimState int getSimCardState(int physicalSlotIndex) {
3793         int activePort = getFirstActivePortIndex(physicalSlotIndex);
3794         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex, activePort));
3795         return getSimCardStateFromSimState(simState);
3796     }
3797 
3798     /**
3799      * Returns a constant indicating the state of the device SIM card in a physical slot and
3800      * port index.
3801      *
3802      * @param physicalSlotIndex physical slot index
3803      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3804      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3805      *
3806      * @see #SIM_STATE_UNKNOWN
3807      * @see #SIM_STATE_ABSENT
3808      * @see #SIM_STATE_CARD_IO_ERROR
3809      * @see #SIM_STATE_CARD_RESTRICTED
3810      * @see #SIM_STATE_PRESENT
3811      *
3812      * @throws UnsupportedOperationException If the device does not have
3813      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3814      * @hide
3815      */
3816     @SystemApi
3817     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3818     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCardState(int physicalSlotIndex, int portIndex)3819     public @SimState int getSimCardState(int physicalSlotIndex, int portIndex) {
3820         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex, portIndex));
3821         return getSimCardStateFromSimState(simState);
3822     }
3823     /**
3824      * Converts SIM state to SIM card state.
3825      * @param simState
3826      * @return SIM card state
3827      */
getSimCardStateFromSimState(int simState)3828     private @SimState int getSimCardStateFromSimState(int simState) {
3829         switch (simState) {
3830             case SIM_STATE_UNKNOWN:
3831             case SIM_STATE_ABSENT:
3832             case SIM_STATE_CARD_IO_ERROR:
3833             case SIM_STATE_CARD_RESTRICTED:
3834                 return simState;
3835             default:
3836                 return SIM_STATE_PRESENT;
3837         }
3838     }
3839 
3840     /**
3841      * Converts a physical slot index to logical slot index.
3842      * @param physicalSlotIndex physical slot index
3843      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3844      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3845      * @return logical slot index
3846      */
getLogicalSlotIndex(int physicalSlotIndex, int portIndex)3847     private int getLogicalSlotIndex(int physicalSlotIndex, int portIndex) {
3848         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3849         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length
3850                 && slotInfos[physicalSlotIndex] != null) {
3851             for (UiccPortInfo portInfo : slotInfos[physicalSlotIndex].getPorts()) {
3852                 if (portInfo.getPortIndex() == portIndex) {
3853                     return portInfo.getLogicalSlotIndex();
3854                 }
3855             }
3856         }
3857 
3858         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3859     }
3860 
3861     /**
3862      * Returns a constant indicating the state of the card applications on the default SIM card.
3863      *
3864      * @see #SIM_STATE_UNKNOWN
3865      * @see #SIM_STATE_PIN_REQUIRED
3866      * @see #SIM_STATE_PUK_REQUIRED
3867      * @see #SIM_STATE_NETWORK_LOCKED
3868      * @see #SIM_STATE_NOT_READY
3869      * @see #SIM_STATE_PERM_DISABLED
3870      * @see #SIM_STATE_LOADED
3871      *
3872      * @throws UnsupportedOperationException If the device does not have
3873      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3874      * @hide
3875      */
3876     @SystemApi
3877     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimApplicationState()3878     public @SimState int getSimApplicationState() {
3879         int simState = getSimStateIncludingLoaded();
3880         return getSimApplicationStateFromSimState(simState);
3881     }
3882 
3883     /**
3884      * Returns a constant indicating the state of the card applications on the device SIM card in
3885      * a physical slot.
3886      *
3887      * @param physicalSlotIndex physical slot index
3888      *
3889      * @see #SIM_STATE_UNKNOWN
3890      * @see #SIM_STATE_PIN_REQUIRED
3891      * @see #SIM_STATE_PUK_REQUIRED
3892      * @see #SIM_STATE_NETWORK_LOCKED
3893      * @see #SIM_STATE_NOT_READY
3894      * @see #SIM_STATE_PERM_DISABLED
3895      * @see #SIM_STATE_LOADED
3896      *
3897      * @throws UnsupportedOperationException If the device does not have
3898      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3899      * @hide
3900      * @deprecated instead use {@link #getSimApplicationState(int, int)}
3901      */
3902     @SystemApi
3903     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3904     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
3905     @Deprecated
getSimApplicationState(int physicalSlotIndex)3906     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3907         int activePort = getFirstActivePortIndex(physicalSlotIndex);
3908         int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, activePort));
3909         return getSimApplicationStateFromSimState(simState);
3910     }
3911 
3912     /**
3913      * Returns a constant indicating the state of the card applications on the device SIM card in
3914      * a physical slot.
3915      *
3916      * @param physicalSlotIndex physical slot index
3917      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3918      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3919      *
3920      * @see #SIM_STATE_UNKNOWN
3921      * @see #SIM_STATE_PIN_REQUIRED
3922      * @see #SIM_STATE_PUK_REQUIRED
3923      * @see #SIM_STATE_NETWORK_LOCKED
3924      * @see #SIM_STATE_NOT_READY
3925      * @see #SIM_STATE_PERM_DISABLED
3926      * @see #SIM_STATE_LOADED
3927      *
3928      * @throws UnsupportedOperationException If the device does not have
3929      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3930      * @hide
3931      */
3932     @SystemApi
3933     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3934     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimApplicationState(int physicalSlotIndex, int portIndex)3935     public @SimState int getSimApplicationState(int physicalSlotIndex, int portIndex) {
3936         int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, portIndex));
3937         return getSimApplicationStateFromSimState(simState);
3938     }
3939 
3940     /**
3941      * Converts SIM state to SIM application state.
3942      * @param simState
3943      * @return SIM application state
3944      */
getSimApplicationStateFromSimState(int simState)3945     private @SimState int getSimApplicationStateFromSimState(int simState) {
3946         switch (simState) {
3947             case SIM_STATE_UNKNOWN:
3948             case SIM_STATE_ABSENT:
3949             case SIM_STATE_CARD_IO_ERROR:
3950             case SIM_STATE_CARD_RESTRICTED:
3951                 return SIM_STATE_UNKNOWN;
3952             case SIM_STATE_READY:
3953                 // Ready is not a valid state anymore. The state that is broadcast goes from
3954                 // NOT_READY to either LOCKED or LOADED.
3955                 return SIM_STATE_NOT_READY;
3956             default:
3957                 return simState;
3958         }
3959     }
3960 
3961 
3962     /**
3963      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
3964      * on the UICC card.
3965      *
3966      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
3967      *
3968      * @param appType the uicc app type like {@link APPTYPE_CSIM}
3969      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
3970      *
3971      * @throws UnsupportedOperationException If the device does not have
3972      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3973      * @hide
3974      */
3975     @SystemApi
3976     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3977     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
isApplicationOnUicc(@iccAppType int appType)3978     public boolean isApplicationOnUicc(@UiccAppType int appType) {
3979         try {
3980             ITelephony service = getITelephony();
3981             if (service != null) {
3982                 return service.isApplicationOnUicc(getSubId(), appType);
3983             }
3984         } catch (RemoteException e) {
3985             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
3986         }
3987         return false;
3988     }
3989 
3990     /**
3991      * Returns a constant indicating the state of the device SIM card in a logical slot.
3992      *
3993      * @param slotIndex logical slot index
3994      *
3995      * @see #SIM_STATE_UNKNOWN
3996      * @see #SIM_STATE_ABSENT
3997      * @see #SIM_STATE_PIN_REQUIRED
3998      * @see #SIM_STATE_PUK_REQUIRED
3999      * @see #SIM_STATE_NETWORK_LOCKED
4000      * @see #SIM_STATE_READY
4001      * @see #SIM_STATE_NOT_READY
4002      * @see #SIM_STATE_PERM_DISABLED
4003      * @see #SIM_STATE_CARD_IO_ERROR
4004      * @see #SIM_STATE_CARD_RESTRICTED
4005      *
4006      * @throws UnsupportedOperationException If the device does not have
4007      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4008      */
4009     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimState(int slotIndex)4010     public @SimState int getSimState(int slotIndex) {
4011         int simState = getSimStateForSlotIndex(slotIndex);
4012         if (simState == SIM_STATE_LOADED) {
4013             simState = SIM_STATE_READY;
4014         }
4015         return simState;
4016     }
4017 
4018     /**
4019      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4020      * provider of the SIM. 5 or 6 decimal digits.
4021      * <p>
4022      * Availability: SIM state must be {@link #SIM_STATE_READY}
4023      *
4024      * @see #getSimState
4025      */
4026     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimOperator()4027     public String getSimOperator() {
4028         return getSimOperatorNumeric();
4029     }
4030 
4031     /**
4032      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4033      * provider of the SIM. 5 or 6 decimal digits.
4034      * <p>
4035      * Availability: SIM state must be {@link #SIM_STATE_READY}
4036      *
4037      * @see #getSimState
4038      *
4039      * @param subId for which SimOperator is returned
4040      * @hide
4041      */
4042     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)4043     public String getSimOperator(int subId) {
4044         return getSimOperatorNumeric(subId);
4045     }
4046 
4047     /**
4048      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4049      * provider of the SIM. 5 or 6 decimal digits.
4050      * <p>
4051      * Availability: SIM state must be {@link #SIM_STATE_READY}
4052      *
4053      * @see #getSimState
4054      * @hide
4055      */
4056     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()4057     public String getSimOperatorNumeric() {
4058         int subId = mSubId;
4059         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4060             subId = SubscriptionManager.getDefaultDataSubscriptionId();
4061             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4062                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
4063                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4064                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
4065                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4066                         subId = SubscriptionManager.getDefaultSubscriptionId();
4067                     }
4068                 }
4069             }
4070         }
4071         return getSimOperatorNumeric(subId);
4072     }
4073 
4074     /**
4075      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4076      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
4077      * <p>
4078      * Availability: SIM state must be {@link #SIM_STATE_READY}
4079      *
4080      * @see #getSimState
4081      *
4082      * @param subId for which SimOperator is returned
4083      * @hide
4084      */
4085     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)4086     public String getSimOperatorNumeric(int subId) {
4087         int phoneId = SubscriptionManager.getPhoneId(subId);
4088         return getSimOperatorNumericForPhone(phoneId);
4089     }
4090 
4091     /**
4092      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4093      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
4094      * <p>
4095      *
4096      * @param phoneId for which SimOperator is returned
4097      * @hide
4098      */
4099     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)4100     public String getSimOperatorNumericForPhone(int phoneId) {
4101         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
4102     }
4103 
4104     /**
4105      * Returns the Service Provider Name (SPN).
4106      * <p>
4107      * Availability: SIM state must be {@link #SIM_STATE_READY}
4108      *
4109      * @see #getSimState
4110      */
4111     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimOperatorName()4112     public String getSimOperatorName() {
4113         return getSimOperatorNameForPhone(getPhoneId());
4114     }
4115 
4116     /**
4117      * Returns the Service Provider Name (SPN).
4118      * <p>
4119      * Availability: SIM state must be {@link #SIM_STATE_READY}
4120      *
4121      * @see #getSimState
4122      *
4123      * @param subId for which SimOperatorName is returned
4124      * @hide
4125      */
4126     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)4127     public String getSimOperatorName(int subId) {
4128         int phoneId = SubscriptionManager.getPhoneId(subId);
4129         return getSimOperatorNameForPhone(phoneId);
4130     }
4131 
4132     /**
4133      * Returns the Service Provider Name (SPN).
4134      *
4135      * @hide
4136      */
4137     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)4138     public String getSimOperatorNameForPhone(int phoneId) {
4139         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
4140     }
4141 
4142     /**
4143      * Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
4144      * <p>
4145      * The ISO-3166-1 alpha-2 country code is provided in lowercase 2 character format.
4146      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string is not
4147      * available.
4148      */
4149     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCountryIso()4150     public String getSimCountryIso() {
4151         return getSimCountryIsoForPhone(getPhoneId());
4152     }
4153 
4154     /**
4155      * Returns the ISO country code equivalent for the SIM provider's country code.
4156      *
4157      * @param subId for which SimCountryIso is returned
4158      * @hide
4159      */
4160     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)4161     public static String getSimCountryIso(int subId) {
4162         int phoneId = SubscriptionManager.getPhoneId(subId);
4163         return getSimCountryIsoForPhone(phoneId);
4164     }
4165 
4166     /**
4167      * Returns the ISO country code equivalent for the SIM provider's country code.
4168      *
4169      * @hide
4170      */
4171     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)4172     public static String getSimCountryIsoForPhone(int phoneId) {
4173         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
4174     }
4175 
4176     /**
4177      * Returns the serial number of the SIM, if applicable. Return null if it is
4178      * unavailable.
4179      *
4180      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4181      * restrictions, and apps are recommended to use resettable identifiers (see <a
4182      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4183      * method can be invoked if one of the following requirements is met:
4184      * <ul>
4185      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4186      *     is a privileged permission that can only be granted to apps preloaded on the device.
4187      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4188      *     owner of an organization-owned device, or their delegates (see {@link
4189      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4190      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4191      *     <li>If the calling app is the default SMS role holder (see {@link
4192      *     RoleManager#isRoleHeld(String)}).
4193      * </ul>
4194      *
4195      * <p>If the calling app does not meet one of these requirements then this method will behave
4196      * as follows:
4197      *
4198      * <ul>
4199      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4200      *     READ_PHONE_STATE permission then null is returned.</li>
4201      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4202      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4203      *     higher, then a SecurityException is thrown.</li>
4204      * </ul>
4205      *
4206      * @throws UnsupportedOperationException If the device does not have
4207      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4208      */
4209     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4210     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4211     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSerialNumber()4212     public String getSimSerialNumber() {
4213          return getSimSerialNumber(getSubId());
4214     }
4215 
4216     /**
4217      * Returns the serial number for the given subscription, if applicable. Return null if it is
4218      * unavailable.
4219      *
4220      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4221      * restrictions, and apps are recommended to use resettable identifiers (see <a
4222      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4223      * method can be invoked if one of the following requirements is met:
4224      * <ul>
4225      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4226      *     is a privileged permission that can only be granted to apps preloaded on the device.
4227      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4228      *     owner of an organization-owned device, or their delegates (see {@link
4229      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4230      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4231      *     <li>If the calling app is the default SMS role holder (see {@link
4232      *     RoleManager#isRoleHeld(String)}).
4233      * </ul>
4234      *
4235      * <p>If the calling app does not meet one of these requirements then this method will behave
4236      * as follows:
4237      *
4238      * <ul>
4239      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4240      *     READ_PHONE_STATE permission then null is returned.</li>
4241      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4242      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4243      *     higher, then a SecurityException is thrown.</li>
4244      * </ul>
4245      *
4246      * @param subId for which Sim Serial number is returned
4247      * @hide
4248      */
4249     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4250     @UnsupportedAppUsage
getSimSerialNumber(int subId)4251     public String getSimSerialNumber(int subId) {
4252         try {
4253             IPhoneSubInfo info = getSubscriberInfoService();
4254             if (info == null)
4255                 return null;
4256             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
4257                     mContext.getAttributionTag());
4258         } catch (RemoteException ex) {
4259             return null;
4260         } catch (NullPointerException ex) {
4261             // This could happen before phone restarts due to crashing
4262             return null;
4263         }
4264     }
4265 
4266     /**
4267      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
4268      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
4269      *
4270      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
4271      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
4272      *
4273      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
4274      *         {@code false} if not supported or unknown
4275      *
4276      * @throws UnsupportedOperationException If the device does not have
4277      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
4278      * @hide
4279      */
4280     @SystemApi
4281     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4282     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isLteCdmaEvdoGsmWcdmaEnabled()4283     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
4284         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
4285     }
4286 
4287     /**
4288      * Return if the current radio is LTE on CDMA for Subscription. This
4289      * is a tri-state return value as for a period of time
4290      * the mode may be unknown.
4291      *
4292      * @param subId for which radio is LTE on CDMA is returned
4293      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
4294      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
4295      * @hide
4296      */
4297     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4298     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)4299     public int getLteOnCdmaMode(int subId) {
4300         try {
4301             ITelephony telephony = getITelephony();
4302             if (telephony == null)
4303                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4304             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
4305                     getAttributionTag());
4306         } catch (RemoteException ex) {
4307             // Assume no ICC card if remote exception which shouldn't happen
4308             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4309         } catch (NullPointerException ex) {
4310             // This could happen before phone restarts due to crashing
4311             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4312         }
4313     }
4314 
4315     /**
4316      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
4317      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
4318      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
4319      *
4320      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
4321      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
4322      * through a factory reset.
4323      *
4324      * @return card ID of the default eUICC card, if loaded.
4325      *
4326      * @throws UnsupportedOperationException If the device does not have
4327      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
4328      */
4329     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
getCardIdForDefaultEuicc()4330     public int getCardIdForDefaultEuicc() {
4331         try {
4332             ITelephony telephony = getITelephony();
4333             if (telephony == null) {
4334                 return UNINITIALIZED_CARD_ID;
4335             }
4336             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
4337         } catch (RemoteException e) {
4338             return UNINITIALIZED_CARD_ID;
4339         }
4340     }
4341 
4342     /**
4343      * Gets information about currently inserted UICCs and eUICCs.
4344      * <p>
4345      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4346      * <p>
4347      * If the caller has carrier priviliges on any active subscription, then they have permission to
4348      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
4349      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the physical slot index where the card is
4350      * inserted ({@link UiccCardInfo#getPhysicalSlotIndex()}.
4351      * <p>
4352      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
4353      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
4354      * UICC or eUICC card.
4355      * <p>
4356      * See {@link UiccCardInfo} for more details on the kind of information available.
4357      *
4358      * @return a list of UiccCardInfo objects, representing information on the currently inserted
4359      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
4360      * the caller does not have adequate permissions for that card.
4361      *
4362      * @throws UnsupportedOperationException If the device does not have
4363      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4364      */
4365     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4366     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4367     @NonNull
getUiccCardsInfo()4368     public List<UiccCardInfo> getUiccCardsInfo() {
4369         try {
4370             ITelephony telephony = getITelephony();
4371             if (telephony == null) {
4372                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
4373                 return new ArrayList<UiccCardInfo>();
4374             }
4375             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
4376         } catch (RemoteException e) {
4377             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
4378             return new ArrayList<UiccCardInfo>();
4379         }
4380     }
4381 
4382     /**
4383      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
4384      * available, which is possible between phone process starting and getting slot info from modem.
4385      *
4386      * @return UiccSlotInfo array.
4387      *
4388      * @throws UnsupportedOperationException If the device does not have
4389      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4390      * @hide
4391      */
4392     @SystemApi
4393     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4394     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getUiccSlotsInfo()4395     public UiccSlotInfo[] getUiccSlotsInfo() {
4396         try {
4397             ITelephony telephony = getITelephony();
4398             if (telephony == null) {
4399                 return null;
4400             }
4401             return telephony.getUiccSlotsInfo(mContext.getOpPackageName());
4402         } catch (RemoteException e) {
4403             return null;
4404         }
4405     }
4406 
4407     /**
4408      * Test method to reload the UICC profile.
4409      *
4410      * @hide
4411      */
4412     @TestApi
4413     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()4414     public void refreshUiccProfile() {
4415         try {
4416             ITelephony telephony = getITelephony();
4417             telephony.refreshUiccProfile(mSubId);
4418         } catch (RemoteException ex) {
4419             Rlog.w(TAG, "RemoteException", ex);
4420         }
4421     }
4422 
4423     /**
4424      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
4425      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
4426      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
4427      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
4428      * logical slots.
4429      *
4430      * @param physicalSlots The content of the array represents the physical slot index. The array
4431      *        size should be same as {@link #getUiccSlotsInfo()}.
4432      * @return boolean Return true if the switch succeeds, false if the switch fails.
4433      *
4434      * @throws UnsupportedOperationException If the device does not have
4435      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4436      * @hide
4437      * @deprecated {@link #setSimSlotMapping(Collection, Executor, Consumer)}
4438      */
4439      // TODO: once integrating the HAL changes we can  convert int[] to List<UiccSlotMapping> and
4440      // converge API's in ITelephony.aidl and PhoneInterfaceManager
4441 
4442     @SystemApi
4443     @Deprecated
4444     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4445     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
switchSlots(int[] physicalSlots)4446     public boolean switchSlots(int[] physicalSlots) {
4447         try {
4448             ITelephony telephony = getITelephony();
4449             if (telephony == null) {
4450                 return false;
4451             }
4452             return telephony.switchSlots(physicalSlots);
4453         } catch (RemoteException e) {
4454             return false;
4455         }
4456     }
4457 
4458     /**
4459      * @param slotMapping Logical to physical slot and port mapping.
4460      * @return {@code true} if slotMapping is valid.
4461      * @return {@code false} if slotMapping is invalid.
4462      *
4463      * slotMapping is invalid if there are different entries (physical slot + port) mapping to the
4464      * same logical slot or if there are same {physical slot + port} mapping to the different
4465      * logical slot
4466      * @hide
4467      */
isSlotMappingValid(@onNull Collection<UiccSlotMapping> slotMapping)4468     private static boolean isSlotMappingValid(@NonNull Collection<UiccSlotMapping> slotMapping) {
4469         // Grouping the collection by logicalSlotIndex, finding different entries mapping to the
4470         // same logical slot
4471         Map<Integer, List<UiccSlotMapping>> slotMappingInfo = slotMapping.stream().collect(
4472                 Collectors.groupingBy(UiccSlotMapping::getLogicalSlotIndex));
4473         for (Map.Entry<Integer, List<UiccSlotMapping>> entry : slotMappingInfo.entrySet()) {
4474             List<UiccSlotMapping> logicalSlotMap = entry.getValue();
4475             if (logicalSlotMap.size() > 1) {
4476                 // duplicate logicalSlotIndex found
4477                 return false;
4478             }
4479         }
4480 
4481         // Grouping the collection by physical slot and port, finding same entries mapping to the
4482         // different logical slot
4483         Map<List<Integer>, List<UiccSlotMapping>> slotMapInfos = slotMapping.stream().collect(
4484                 Collectors.groupingBy(
4485                         slot -> Arrays.asList(slot.getPhysicalSlotIndex(), slot.getPortIndex())));
4486         for (Map.Entry<List<Integer>, List<UiccSlotMapping>> entry : slotMapInfos.entrySet()) {
4487             List<UiccSlotMapping> portAndPhysicalSlotList = entry.getValue();
4488             if (portAndPhysicalSlotList.size() > 1) {
4489                 // duplicate pair of portIndex and physicalSlotIndex found
4490                 return false;
4491             }
4492         }
4493         return true;
4494     }
4495     /**
4496      * Maps the logical slots to physical slots and ports. Mapping is specified from
4497      * {@link UiccSlotMapping} which consist of both physical slot index and port index.
4498      * Logical slot is the slot that is seen by modem. Physical slot is the actual physical slot.
4499      * Port index is the index (enumerated value) for the associated port available on the SIM.
4500      * Each physical slot can have multiple ports if
4501      * {@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP} is supported.
4502      *
4503      * Example: no. of logical slots 1 and physical slots 2 do not support MEP, each physical slot
4504      * has one port:
4505      * The only logical slot (index 0) can be mapped to first physical slot (value 0), port(index
4506      * 0) or
4507      * second physical slot(value 1), port (index 0), while the other physical slot remains unmapped
4508      * and inactive.
4509      * slotMapping[0] = UiccSlotMapping{0 //port index, 0 //physical slot, 0 //logical slot} or
4510      * slotMapping[0] = UiccSlotMapping{0 //port index, 1 //physical slot, 0 //logical slot}
4511      *
4512      * Example no. of logical slots 2 and physical slots 2 supports MEP with 2 ports available:
4513      * Each logical slot must be mapped to a port (physical slot and port combination).
4514      * First logical slot (index 0) can be mapped to physical slot 1 and the second logical slot
4515      * can be mapped to either port from physical slot 2.
4516      *
4517      * slotMapping[0] = UiccSlotMapping{0, 0, 0} and slotMapping[1] = UiccSlotMapping{0, 1, 1} or
4518      * slotMapping[0] = UiccSlotMapping{0, 0, 0} and slotMapping[1] = UiccSlotMapping{1, 1, 1}
4519      *
4520      * or the other way around, the second logical slot(index 1) can be mapped to physical slot 1
4521      * and the first logical slot can be mapped to either port from physical slot 2.
4522      *
4523      * slotMapping[1] = UiccSlotMapping{0, 0, 0} and slotMapping[0] = UiccSlotMapping{0, 1, 1} or
4524      * slotMapping[1] = UiccSlotMapping{0, 0, 0} and slotMapping[0] = UiccSlotMapping{1, 1, 1}
4525      *
4526      * another possible mapping is each logical slot maps to each port of physical slot 2 and there
4527      * is no active logical modem mapped to physical slot 1.
4528      *
4529      * slotMapping[0] = UiccSlotMapping{0, 1, 0} and slotMapping[1] = UiccSlotMapping{1, 1, 1} or
4530      * slotMapping[0] = UiccSlotMapping{1, 1, 0} and slotMapping[1] = UiccSlotMapping{0, 1, 1}
4531      *
4532      * @param slotMapping Logical to physical slot and port mapping.
4533      * @throws IllegalStateException if telephony service is null or slot mapping was sent when the
4534      *         radio in middle of a silent restart or other invalid states to handle the command
4535      * @throws IllegalArgumentException if the caller passes in an invalid collection of
4536      *         UiccSlotMapping like duplicate data, etc
4537      *
4538      * @throws UnsupportedOperationException If the device does not have
4539      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4540      * @hide
4541      */
4542     @SystemApi
4543     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4544     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimSlotMapping(@onNull Collection<UiccSlotMapping> slotMapping)4545     public void setSimSlotMapping(@NonNull Collection<UiccSlotMapping> slotMapping) {
4546         try {
4547             ITelephony telephony = getITelephony();
4548             if (telephony != null) {
4549                 if (isSlotMappingValid(slotMapping)) {
4550                     boolean result = telephony.setSimSlotMapping(new ArrayList(slotMapping));
4551                     if (!result) {
4552                         throw new IllegalStateException("setSimSlotMapping has failed");
4553                     }
4554                 } else {
4555                     throw new IllegalArgumentException("Duplicate UiccSlotMapping data found");
4556                 }
4557             } else {
4558                 throw new IllegalStateException("telephony service is null.");
4559             }
4560         } catch (RemoteException e) {
4561             throw e.rethrowAsRuntimeException();
4562         }
4563     }
4564 
4565     /**
4566      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
4567      * id and the value is the physical slots id mapped to this logical slot id.
4568      *
4569      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
4570      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
4571      *
4572      * @throws UnsupportedOperationException If the device does not have
4573      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4574      * @hide
4575      * @deprecated use {@link #getSimSlotMapping()} instead.
4576      */
4577     @SystemApi
4578     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4579     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4580     @NonNull
4581     @Deprecated
getLogicalToPhysicalSlotMapping()4582     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
4583         Map<Integer, Integer> slotMapping = new HashMap<>();
4584         try {
4585             ITelephony telephony = getITelephony();
4586             if (telephony != null) {
4587                 List<UiccSlotMapping> simSlotsMapping = telephony.getSlotsMapping(
4588                         mContext.getOpPackageName());
4589                 for (UiccSlotMapping slotMap : simSlotsMapping) {
4590                     slotMapping.put(slotMap.getLogicalSlotIndex(), slotMap.getPhysicalSlotIndex());
4591                 }
4592             }
4593         } catch (RemoteException e) {
4594             Log.e(TAG, "getSlotsMapping RemoteException", e);
4595         }
4596         return slotMapping;
4597     }
4598 
4599     /**
4600      * Get the mapping from logical slots to physical sim slots and port indexes. Initially the
4601      * logical slot index was mapped to physical slot index, but with support for multi-enabled
4602      * profile(MEP){@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP},logical slot is now mapped to
4603      * port index.
4604      *
4605      * @return a collection of {@link UiccSlotMapping} which indicates the mapping from logical
4606      *         slots to ports and physical slots.
4607      *
4608      * @throws UnsupportedOperationException If the device does not have
4609      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4610      * @hide
4611      */
4612     @SystemApi
4613     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4614     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4615     @NonNull
getSimSlotMapping()4616     public Collection<UiccSlotMapping> getSimSlotMapping() {
4617         List<UiccSlotMapping> slotMap;
4618         try {
4619             ITelephony telephony = getITelephony();
4620             if (telephony != null) {
4621                 slotMap = telephony.getSlotsMapping(mContext.getOpPackageName());
4622             } else {
4623                 throw new IllegalStateException("telephony service is null.");
4624             }
4625         } catch (RemoteException e) {
4626             throw e.rethrowAsRuntimeException();
4627         }
4628         return slotMap;
4629     }
4630     //
4631     //
4632     // Subscriber Info
4633     //
4634     //
4635 
4636     /**
4637      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
4638      * Return null if it is unavailable.
4639      *
4640      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4641      * restrictions, and apps are recommended to use resettable identifiers (see <a
4642      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4643      * method can be invoked if one of the following requirements is met:
4644      * <ul>
4645      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4646      *     is a privileged permission that can only be granted to apps preloaded on the device.
4647      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4648      *     owner of an organization-owned device, or their delegates (see {@link
4649      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4650      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4651      *     <li>If the calling app is the default SMS role holder (see {@link
4652      *     RoleManager#isRoleHeld(String)}).
4653      *     <li>If the calling app has been granted the
4654      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
4655      * </ul>
4656      *
4657      * <p>If the calling app does not meet one of these requirements then this method will behave
4658      * as follows:
4659      *
4660      * <ul>
4661      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4662      *     READ_PHONE_STATE permission then null is returned.</li>
4663      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4664      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4665      *     higher, then a SecurityException is thrown.</li>
4666      * </ul>
4667      *
4668      * @throws UnsupportedOperationException If the device does not have
4669      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4670      */
4671     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4672     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4673     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriberId()4674     public String getSubscriberId() {
4675         return getSubscriberId(getSubId());
4676     }
4677 
4678     /**
4679      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
4680      * for a subscription.
4681      * Return null if it is unavailable.
4682      *
4683      * See {@link #getSubscriberId()} for details on the required permissions and behavior
4684      * when the caller does not hold sufficient permissions.
4685      *
4686      * @param subId whose subscriber id is returned
4687      * @hide
4688      */
4689     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4690     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)4691     public String getSubscriberId(int subId) {
4692         try {
4693             IPhoneSubInfo info = getSubscriberInfoService();
4694             if (info == null)
4695                 return null;
4696             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
4697                     mContext.getAttributionTag());
4698         } catch (RemoteException ex) {
4699             return null;
4700         } catch (NullPointerException ex) {
4701             // This could happen before phone restarts due to crashing
4702             return null;
4703         }
4704     }
4705 
4706     /**
4707      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
4708      * including the public key and the key identifier; or {@code null} if not available.
4709      * <p>
4710      * For a multi-sim device, the dafault data sim is used if not specified.
4711      * <p>
4712      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
4713      *
4714      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
4715      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
4716      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
4717      *         IMSI and IMPI. This includes the public key and the key identifier. This information
4718      *         will be stored in the device keystore. {@code null} will be returned when no key is
4719      *         found, and the carrier does not require a key.
4720      * @throws IllegalArgumentException when an invalid key is found or when key is required but
4721      *         not found.
4722      * @throws UnsupportedOperationException If the device does not have
4723      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4724      * @hide
4725      */
4726     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4727     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4728     @SystemApi
4729     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)4730     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
4731         try {
4732             IPhoneSubInfo info = getSubscriberInfoService();
4733             if (info == null) {
4734                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
4735                 return null;
4736             }
4737             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4738             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
4739                 throw new IllegalArgumentException("IMSI error: Invalid key type");
4740             }
4741             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
4742                     subId, keyType, mContext.getOpPackageName());
4743             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
4744                 Rlog.e(TAG, "IMSI error: key is required but not found");
4745                 throw new IllegalArgumentException("IMSI error: key is required but not found");
4746             }
4747             return imsiEncryptionInfo;
4748         } catch (RemoteException ex) {
4749             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4750         } catch (NullPointerException ex) {
4751             // This could happen before phone restarts due to crashing
4752             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
4753         }
4754         return null;
4755     }
4756 
4757     /**
4758      * Resets the carrier keys used to encrypt the IMSI and IMPI.
4759      * <p>
4760      * This involves 2 steps:
4761      *  1. Delete the keys from the database.
4762      *  2. Send an intent to download new Certificates.
4763      * <p>
4764      * For a multi-sim device, the dafault data sim is used if not specified.
4765      * <p>
4766      * Requires Permission: MODIFY_PHONE_STATE.
4767      *
4768      * @see #getCarrierInfoForImsiEncryption
4769      *
4770      * @throws UnsupportedOperationException If the device does not have
4771      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4772      * @hide
4773      */
4774     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4775     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4776     @SystemApi
resetCarrierKeysForImsiEncryption()4777     public void resetCarrierKeysForImsiEncryption() {
4778         try {
4779             IPhoneSubInfo info = getSubscriberInfoService();
4780             if (info == null) {
4781                 throw new RuntimeException("IMSI error: Subscriber Info is null");
4782             }
4783             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4784             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
4785         } catch (RemoteException ex) {
4786             Rlog.e(TAG, "Telephony#getCarrierInfoForImsiEncryption RemoteException" + ex);
4787         }
4788     }
4789 
4790     /**
4791      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
4792      * @param keyType the key type which is being checked. (WLAN, EPDG)
4793      * @return true if the digit at position keyType is 1, else false.
4794      * @hide
4795      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)4796     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
4797         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
4798         return (returnValue == 1) ? true : false;
4799     }
4800 
4801     /**
4802      * If Carrier requires Imsi to be encrypted.
4803      * @hide
4804      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4805     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4806         CarrierConfigManager configManager =
4807                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4808         if (configManager == null) {
4809             return false;
4810         }
4811         PersistableBundle pb = configManager.getConfigForSubId(subId);
4812         if (pb == null) {
4813             return false;
4814         }
4815         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4816         return isKeyEnabled(keyAvailability, keyType);
4817     }
4818 
4819     /**
4820      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4821      * This includes the public key and the key identifier. This information will be stored in the
4822      * device keystore.
4823      * <p>
4824      * Requires Permission:
4825      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4826      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4827      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4828      *        The keyIdentifier Attribute value pair that helps a server locate
4829      *        the private key to decrypt the permanent identity. This field is
4830      *        optional and if it is present then it’s always separated from encrypted
4831      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4832      *        with “name=value” format.
4833      * @hide
4834      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4835     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4836         try {
4837             IPhoneSubInfo info = getSubscriberInfoService();
4838             if (info == null) return;
4839             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4840                     imsiEncryptionInfo);
4841         } catch (NullPointerException ex) {
4842             // This could happen before phone restarts due to crashing
4843             return;
4844         } catch (RemoteException ex) {
4845             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4846             return;
4847         }
4848     }
4849 
4850     /**
4851      * Exception that may be supplied to the callback in {@link #uploadCallComposerPicture} if
4852      * something goes awry.
4853      */
4854     public static class CallComposerException extends Exception {
4855         /**
4856          * Used internally only, signals success of the upload to the carrier.
4857          * @hide
4858          */
4859         public static final int SUCCESS = -1;
4860         /**
4861          * Indicates that an unknown error was encountered when uploading the call composer picture.
4862          *
4863          * Clients that encounter this error should retry the upload.
4864          */
4865         public static final int ERROR_UNKNOWN = 0;
4866 
4867         /**
4868          * Indicates that the phone process died or otherwise became unavailable while uploading the
4869          * call composer picture.
4870          *
4871          * Clients that encounter this error should retry the upload.
4872          */
4873         public static final int ERROR_REMOTE_END_CLOSED = 1;
4874 
4875         /**
4876          * Indicates that the file or stream supplied exceeds the size limit defined in
4877          * {@link #getMaximumCallComposerPictureSize()}.
4878          *
4879          * Clients that encounter this error should retry the upload after reducing the size of the
4880          * picture.
4881          */
4882         public static final int ERROR_FILE_TOO_LARGE = 2;
4883 
4884         /**
4885          * Indicates that the device failed to authenticate with the carrier when uploading the
4886          * picture.
4887          *
4888          * Clients that encounter this error should not retry the upload unless a reboot or radio
4889          * reset has been performed in the interim.
4890          */
4891         public static final int ERROR_AUTHENTICATION_FAILED = 3;
4892 
4893         /**
4894          * Indicates that the {@link InputStream} passed to {@link #uploadCallComposerPicture}
4895          * was closed.
4896          *
4897          * The caller should retry if this error is encountered, and be sure to not close the stream
4898          * before the callback is called this time.
4899          */
4900         public static final int ERROR_INPUT_CLOSED = 4;
4901 
4902         /**
4903          * Indicates that an {@link IOException} was encountered while reading the picture.
4904          *
4905          * The offending {@link IOException} will be available via {@link #getIOException()}.
4906          * Clients should use the contents of the exception to determine whether a retry is
4907          * warranted.
4908          */
4909         public static final int ERROR_IO_EXCEPTION = 5;
4910 
4911         /**
4912          * Indicates that the device is currently not connected to a network that's capable of
4913          * reaching a carrier's RCS servers.
4914          *
4915          * Clients should prompt the user to remedy the issue by moving to an area with better
4916          * signal, by connecting to a different network, or to retry at another time.
4917          */
4918         public static final int ERROR_NETWORK_UNAVAILABLE = 6;
4919 
4920         /** @hide */
4921         @IntDef(prefix = {"ERROR_"}, value = {
4922                 ERROR_UNKNOWN,
4923                 ERROR_REMOTE_END_CLOSED,
4924                 ERROR_FILE_TOO_LARGE,
4925                 ERROR_AUTHENTICATION_FAILED,
4926                 ERROR_INPUT_CLOSED,
4927                 ERROR_IO_EXCEPTION,
4928                 ERROR_NETWORK_UNAVAILABLE,
4929         })
4930 
4931         @Retention(RetentionPolicy.SOURCE)
4932         public @interface CallComposerError {}
4933 
4934         private final int mErrorCode;
4935         private final IOException mIOException;
4936 
CallComposerException(@allComposerError int errorCode, @Nullable IOException ioException)4937         public CallComposerException(@CallComposerError int errorCode,
4938                 @Nullable IOException ioException) {
4939             mErrorCode = errorCode;
4940             mIOException = ioException;
4941         }
4942 
4943         /**
4944          * Fetches the error code associated with this exception.
4945          * @return An error code.
4946          */
getErrorCode()4947         public @CallComposerError int getErrorCode() {
4948             return mErrorCode;
4949         }
4950 
4951         /**
4952          * Fetches the {@link IOException} that caused the error.
4953          */
4954         // Follows the naming of IOException
4955         @SuppressLint("AcronymName")
getIOException()4956         public @Nullable IOException getIOException() {
4957             return mIOException;
4958         }
4959     }
4960 
4961     /** @hide */
4962     public static final String KEY_CALL_COMPOSER_PICTURE_HANDLE = "call_composer_picture_handle";
4963 
4964     /**
4965      * Uploads a picture to the carrier network for use with call composer.
4966      *
4967      * @see #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)
4968      * @param pictureToUpload Path to a local file containing the picture to upload.
4969      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg)
4970      * @param executor The {@link Executor} on which the {@code pictureToUpload} file will be read
4971      *                 from disk, as well as on which {@code callback} will be called.
4972      * @param callback A callback called when the upload operation terminates, either in success
4973      *                 or in error.
4974      *
4975      * @throws UnsupportedOperationException If the device does not have
4976      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
4977      */
4978     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
uploadCallComposerPicture(@onNull Path pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)4979     public void uploadCallComposerPicture(@NonNull Path pictureToUpload,
4980             @NonNull String contentType,
4981             @CallbackExecutor @NonNull Executor executor,
4982             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
4983         Objects.requireNonNull(pictureToUpload);
4984         Objects.requireNonNull(executor);
4985         Objects.requireNonNull(callback);
4986 
4987         // Do the role check now so that we can quit early if needed -- there's an additional
4988         // permission check on the other side of the binder call as well.
4989         RoleManager rm = mContext.getSystemService(RoleManager.class);
4990         if (!rm.isRoleHeld(RoleManager.ROLE_DIALER)) {
4991             throw new SecurityException("You must hold RoleManager.ROLE_DIALER to do this");
4992         }
4993 
4994         executor.execute(() -> {
4995             try {
4996                 if (Looper.getMainLooper().isCurrentThread()) {
4997                     Log.w(TAG, "Uploading call composer picture on main thread!"
4998                             + " hic sunt dracones!");
4999                 }
5000                 long size = Files.size(pictureToUpload);
5001                 if (size > getMaximumCallComposerPictureSize()) {
5002                     callback.onError(new CallComposerException(
5003                             CallComposerException.ERROR_FILE_TOO_LARGE, null));
5004                     return;
5005                 }
5006                 InputStream fileStream = Files.newInputStream(pictureToUpload);
5007                 try {
5008                     uploadCallComposerPicture(fileStream, contentType, executor,
5009                             new OutcomeReceiver<ParcelUuid, CallComposerException>() {
5010                                 @Override
5011                                 public void onResult(ParcelUuid result) {
5012                                     try {
5013                                         fileStream.close();
5014                                     } catch (IOException e) {
5015                                         // ignore
5016                                         Log.e(TAG, "Error closing file input stream when"
5017                                                 + " uploading call composer pic");
5018                                     }
5019                                     callback.onResult(result);
5020                                 }
5021 
5022                                 @Override
5023                                 public void onError(CallComposerException error) {
5024                                     try {
5025                                         fileStream.close();
5026                                     } catch (IOException e) {
5027                                         // ignore
5028                                         Log.e(TAG, "Error closing file input stream when"
5029                                                 + " uploading call composer pic");
5030                                     }
5031                                     callback.onError(error);
5032                                 }
5033                             });
5034                 } catch (Exception e) {
5035                     Log.e(TAG, "Got exception calling into stream-version of"
5036                             + " uploadCallComposerPicture: " + e);
5037                     try {
5038                         fileStream.close();
5039                     } catch (IOException e1) {
5040                         // ignore
5041                         Log.e(TAG, "Error closing file input stream when uploading"
5042                                 + " call composer pic");
5043                     }
5044                 }
5045             } catch (IOException e) {
5046                 Log.e(TAG, "IOException when uploading call composer pic:" + e);
5047                 callback.onError(
5048                         new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e));
5049             }
5050         });
5051 
5052     }
5053 
5054     /**
5055      * Uploads a picture to the carrier network for use with call composer.
5056      *
5057      * This method allows a dialer app to upload a picture to the carrier network that can then
5058      * later be attached to an outgoing call. In order to attach the picture to a call, use the
5059      * {@link ParcelUuid} returned from {@code callback} upon successful upload as the value to
5060      * {@link TelecomManager#EXTRA_OUTGOING_PICTURE}.
5061      *
5062      * This functionality is only available to the app filling the {@link RoleManager#ROLE_DIALER}
5063      * role on the device.
5064      *
5065      * This functionality is only available when
5066      * {@link CarrierConfigManager#KEY_SUPPORTS_CALL_COMPOSER_BOOL} is set to {@code true} in the
5067      * bundle returned from {@link #getCarrierConfig()}.
5068      *
5069      * @param pictureToUpload An {@link InputStream} that supplies the bytes representing the
5070      *                        picture to upload. The client bears responsibility for closing this
5071      *                        stream after {@code callback} is called with success or failure.
5072      *
5073      *                        Additionally, if the stream supplies more bytes than the return value
5074      *                        of {@link #getMaximumCallComposerPictureSize()}, the upload will be
5075      *                        aborted and the callback will be called with an exception containing
5076      *                        {@link CallComposerException#ERROR_FILE_TOO_LARGE}.
5077      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg). The list
5078      *                    of acceptable content types can be found at 3GPP TS 26.141 sections
5079      *                    4.2 and 4.3.
5080      * @param executor The {@link Executor} on which the {@code pictureToUpload} stream will be
5081      *                 read, as well as on which the callback will be called.
5082      * @param callback A callback called when the upload operation terminates, either in success
5083      *                 or in error.
5084      *
5085      * @throws UnsupportedOperationException If the device does not have
5086      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5087      */
5088     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
uploadCallComposerPicture(@onNull InputStream pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)5089     public void uploadCallComposerPicture(@NonNull InputStream pictureToUpload,
5090             @NonNull String contentType,
5091             @CallbackExecutor @NonNull Executor executor,
5092             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
5093         Objects.requireNonNull(pictureToUpload);
5094         Objects.requireNonNull(executor);
5095         Objects.requireNonNull(callback);
5096 
5097         ITelephony telephony = getITelephony();
5098         if (telephony == null) {
5099             throw new IllegalStateException("Telephony service not available.");
5100         }
5101 
5102         ParcelFileDescriptor writeFd;
5103         ParcelFileDescriptor readFd;
5104         try {
5105             ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
5106             writeFd = pipe[1];
5107             readFd = pipe[0];
5108         } catch (IOException e) {
5109             executor.execute(() -> callback.onError(
5110                     new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e)));
5111             return;
5112         }
5113 
5114         OutputStream output = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
5115 
5116         try {
5117             telephony.uploadCallComposerPicture(getSubId(), mContext.getOpPackageName(),
5118                     contentType, readFd, new ResultReceiver(null) {
5119                         @Override
5120                         protected void onReceiveResult(int resultCode, Bundle result) {
5121                             if (resultCode != CallComposerException.SUCCESS) {
5122                                 executor.execute(() -> callback.onError(
5123                                         new CallComposerException(resultCode, null)));
5124                                 return;
5125                             }
5126                             ParcelUuid resultUuid =
5127                                     result.getParcelable(KEY_CALL_COMPOSER_PICTURE_HANDLE, android.os.ParcelUuid.class);
5128                             if (resultUuid == null) {
5129                                 Log.e(TAG, "Got null uuid without an error"
5130                                         + " while uploading call composer pic");
5131                                 executor.execute(() -> callback.onError(
5132                                         new CallComposerException(
5133                                                 CallComposerException.ERROR_UNKNOWN, null)));
5134                                 return;
5135                             }
5136                             executor.execute(() -> callback.onResult(resultUuid));
5137                         }
5138                     });
5139         } catch (RemoteException e) {
5140             Log.e(TAG, "Remote exception uploading call composer pic:" + e);
5141             e.rethrowAsRuntimeException();
5142         }
5143 
5144         executor.execute(() -> {
5145             if (Looper.getMainLooper().isCurrentThread()) {
5146                 Log.w(TAG, "Uploading call composer picture on main thread!"
5147                         + " hic sunt dracones!");
5148             }
5149 
5150             int totalBytesRead = 0;
5151             byte[] buffer = new byte[16 * 1024];
5152             try {
5153                 while (true) {
5154                     int numRead;
5155                     try {
5156                         numRead = pictureToUpload.read(buffer);
5157                     } catch (IOException e) {
5158                         Log.e(TAG, "IOException reading from input while uploading pic: " + e);
5159                         // Most likely, this was because the stream was closed. We have no way to
5160                         // tell though.
5161                         callback.onError(new CallComposerException(
5162                                 CallComposerException.ERROR_INPUT_CLOSED, e));
5163                         try {
5164                             writeFd.closeWithError("input closed");
5165                         } catch (IOException e1) {
5166                             // log and ignore
5167                             Log.e(TAG, "Error closing fd pipe: " + e1);
5168                         }
5169                         break;
5170                     }
5171 
5172                     if (numRead < 0) {
5173                         break;
5174                     }
5175 
5176                     totalBytesRead += numRead;
5177                     if (totalBytesRead > getMaximumCallComposerPictureSize()) {
5178                         Log.e(TAG, "Read too many bytes from call composer pic stream: "
5179                                 + totalBytesRead);
5180                         try {
5181                             callback.onError(new CallComposerException(
5182                                     CallComposerException.ERROR_FILE_TOO_LARGE, null));
5183                             writeFd.closeWithError("too large");
5184                         } catch (IOException e1) {
5185                             // log and ignore
5186                             Log.e(TAG, "Error closing fd pipe: " + e1);
5187                         }
5188                         break;
5189                     }
5190 
5191                     try {
5192                         output.write(buffer, 0, numRead);
5193                     } catch (IOException e) {
5194                         callback.onError(new CallComposerException(
5195                                 CallComposerException.ERROR_REMOTE_END_CLOSED, e));
5196                         try {
5197                             writeFd.closeWithError("remote end closed");
5198                         } catch (IOException e1) {
5199                             // log and ignore
5200                             Log.e(TAG, "Error closing fd pipe: " + e1);
5201                         }
5202                         break;
5203                     }
5204                 }
5205             } finally {
5206                 try {
5207                     output.close();
5208                 } catch (IOException e) {
5209                     // Ignore -- we might've already closed it.
5210                 }
5211             }
5212         });
5213     }
5214 
5215     /**
5216      * Returns the Group Identifier Level1 for a GSM phone.
5217      * Return null if it is unavailable.
5218      *
5219      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5220      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5221      *
5222      * @throws UnsupportedOperationException If the device does not have
5223      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5224      */
5225     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5226     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5227     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getGroupIdLevel1()5228     public String getGroupIdLevel1() {
5229         try {
5230             IPhoneSubInfo info = getSubscriberInfoService();
5231             if (info == null)
5232                 return null;
5233             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
5234                     mContext.getAttributionTag());
5235         } catch (RemoteException ex) {
5236             return null;
5237         } catch (NullPointerException ex) {
5238             // This could happen before phone restarts due to crashing
5239             return null;
5240         }
5241     }
5242 
5243     /**
5244      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
5245      * Return null if it is unavailable.
5246      *
5247      * @param subId whose subscriber id is returned
5248      * @hide
5249      */
5250     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5251     @UnsupportedAppUsage
getGroupIdLevel1(int subId)5252     public String getGroupIdLevel1(int subId) {
5253         try {
5254             IPhoneSubInfo info = getSubscriberInfoService();
5255             if (info == null)
5256                 return null;
5257             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
5258                     mContext.getAttributionTag());
5259         } catch (RemoteException ex) {
5260             return null;
5261         } catch (NullPointerException ex) {
5262             // This could happen before phone restarts due to crashing
5263             return null;
5264         }
5265     }
5266 
5267     /**
5268      * Returns the phone number string for line 1, for example, the MSISDN
5269      * for a GSM phone for a particular subscription. Return null if it is unavailable.
5270      * <p>
5271      * The default SMS app can also use this.
5272      *
5273      * <p>Requires Permission:
5274      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5275      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5276      *     that the caller is the default SMS app,
5277      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5278      *     for any API level.
5279      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5280      *     for apps targeting SDK API level 29 and below.
5281      *
5282      * @throws UnsupportedOperationException If the device does not have
5283      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5284      * @deprecated use {@link SubscriptionManager#getPhoneNumber(int)} instead.
5285      */
5286     @Deprecated
5287     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
5288     @RequiresPermission(anyOf = {
5289             android.Manifest.permission.READ_PHONE_STATE,
5290             android.Manifest.permission.READ_SMS,
5291             android.Manifest.permission.READ_PHONE_NUMBERS
5292     })
5293     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getLine1Number()5294     public String getLine1Number() {
5295         return getLine1Number(getSubId());
5296     }
5297 
5298     /**
5299      * Returns the phone number string for line 1, for example, the MSISDN
5300      * for a GSM phone for a particular subscription. Return null if it is unavailable.
5301      * <p>
5302      * The default SMS app can also use this.
5303      *
5304      * <p>Requires Permission:
5305      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5306      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5307      *     that the caller is the default SMS app,
5308      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5309      *     for any API level.
5310      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5311      *     for apps targeting SDK API level 29 and below.
5312      *
5313      * @param subId whose phone number for line 1 is returned
5314      * @hide
5315      */
5316     @RequiresPermission(anyOf = {
5317             android.Manifest.permission.READ_PHONE_STATE,
5318             android.Manifest.permission.READ_SMS,
5319             android.Manifest.permission.READ_PHONE_NUMBERS
5320     })
5321     @UnsupportedAppUsage
getLine1Number(int subId)5322     public String getLine1Number(int subId) {
5323         String number = null;
5324         try {
5325             ITelephony telephony = getITelephony();
5326             if (telephony != null)
5327                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
5328                          mContext.getAttributionTag());
5329         } catch (RemoteException ex) {
5330         } catch (NullPointerException ex) {
5331         }
5332         if (number != null) {
5333             return number;
5334         }
5335         try {
5336             IPhoneSubInfo info = getSubscriberInfoService();
5337             if (info == null)
5338                 return null;
5339             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
5340                     mContext.getAttributionTag());
5341         } catch (RemoteException ex) {
5342             return null;
5343         } catch (NullPointerException ex) {
5344             // This could happen before phone restarts due to crashing
5345             return null;
5346         }
5347     }
5348 
5349     /**
5350      * Set the line 1 phone number string and its alphatag for the current ICCID
5351      * for display purpose only, for example, displayed in Phone Status. It won't
5352      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
5353      * value.
5354      *
5355      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5356      *
5357      * @param alphaTag alpha-tagging of the dailing nubmer
5358      * @param number The dialing number
5359      * @return true if the operation was executed correctly.
5360      *
5361      * @throws UnsupportedOperationException If the device does not have
5362      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5363      * @deprecated use {@link SubscriptionManager#setCarrierPhoneNumber(int, String)} instead.
5364      */
5365     @Deprecated
5366     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setLine1NumberForDisplay(String alphaTag, String number)5367     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
5368         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
5369     }
5370 
5371     /**
5372      * Set the line 1 phone number string and its alphatag for the current ICCID
5373      * for display purpose only, for example, displayed in Phone Status. It won't
5374      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
5375      * value.
5376      *
5377      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5378      *
5379      * @param subId the subscriber that the alphatag and dialing number belongs to.
5380      * @param alphaTag alpha-tagging of the dailing nubmer
5381      * @param number The dialing number
5382      * @return true if the operation was executed correctly.
5383      * @hide
5384      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)5385     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
5386         try {
5387             // This API is deprecated; call the new API to allow smooth migartion.
5388             // The new API doesn't accept null so convert null to empty string.
5389             mSubscriptionManager.setCarrierPhoneNumber(subId, (number == null ? "" : number));
5390 
5391             ITelephony telephony = getITelephony();
5392             if (telephony != null)
5393                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
5394         } catch (RemoteException ex) {
5395         } catch (NullPointerException ex) {
5396         }
5397         return false;
5398     }
5399 
5400     /**
5401      * Returns the alphabetic identifier associated with the line 1 number.
5402      * Return null if it is unavailable.
5403      * @hide
5404      * nobody seems to call this.
5405      */
5406     @UnsupportedAppUsage
5407     @TestApi
5408     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()5409     public String getLine1AlphaTag() {
5410         return getLine1AlphaTag(getSubId());
5411     }
5412 
5413     /**
5414      * Returns the alphabetic identifier associated with the line 1 number
5415      * for a subscription.
5416      * Return null if it is unavailable.
5417      * @param subId whose alphabetic identifier associated with line 1 is returned
5418      * nobody seems to call this.
5419      * @hide
5420      */
5421     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5422     @UnsupportedAppUsage
getLine1AlphaTag(int subId)5423     public String getLine1AlphaTag(int subId) {
5424         String alphaTag = null;
5425         try {
5426             ITelephony telephony = getITelephony();
5427             if (telephony != null)
5428                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
5429                         getOpPackageName(), getAttributionTag());
5430         } catch (RemoteException ex) {
5431         } catch (NullPointerException ex) {
5432         }
5433         if (alphaTag != null) {
5434             return alphaTag;
5435         }
5436         try {
5437             IPhoneSubInfo info = getSubscriberInfoService();
5438             if (info == null)
5439                 return null;
5440             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
5441                     getAttributionTag());
5442         } catch (RemoteException ex) {
5443             return null;
5444         } catch (NullPointerException ex) {
5445             // This could happen before phone restarts due to crashing
5446             return null;
5447         }
5448     }
5449 
5450     /**
5451      * Return the set of subscriber IDs that should be considered "merged together" for data usage
5452      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
5453      * subscribers are sorted in a deterministic order.
5454      * <p>
5455      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
5456      * TelephonyManager's subId.
5457      *
5458      * This is deprecated and {@link #getMergedImsisFromGroup()} should be used for data
5459      * usage merging purpose.
5460      * TODO: remove this API.
5461      *
5462      * @hide
5463      */
5464     @UnsupportedAppUsage
5465     @Deprecated
getMergedSubscriberIds()5466     public @Nullable String[] getMergedSubscriberIds() {
5467         try {
5468             ITelephony telephony = getITelephony();
5469             if (telephony != null)
5470                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
5471                         getAttributionTag());
5472         } catch (RemoteException ex) {
5473         } catch (NullPointerException ex) {
5474         }
5475         return null;
5476     }
5477 
5478     /**
5479      * Return the set of IMSIs that should be considered "merged together" for data usage
5480      * purposes. This API merges IMSIs based on subscription grouping: IMSI of those in the same
5481      * group will all be returned.
5482      * Return the current IMSI if there is no subscription group, see
5483      * {@link SubscriptionManager#createSubscriptionGroup(List)} for the definition of a group,
5484      * otherwise return an empty array if there is a failure.
5485      *
5486      * @throws UnsupportedOperationException If the device does not have
5487      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5488      * @hide
5489      */
5490     @SystemApi
5491     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5492     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getMergedImsisFromGroup()5493     public @NonNull String[] getMergedImsisFromGroup() {
5494         try {
5495             ITelephony telephony = getITelephony();
5496             if (telephony != null) {
5497                 String[] mergedImsisFromGroup =
5498                         telephony.getMergedImsisFromGroup(getSubId(), getOpPackageName());
5499                 if (mergedImsisFromGroup != null) {
5500                     return mergedImsisFromGroup;
5501                 }
5502             }
5503         } catch (RemoteException ex) {
5504         }
5505         return new String[0];
5506     }
5507 
5508     /**
5509      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
5510      *
5511      * <p>Requires Permission:
5512      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5513      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5514      *     that the caller is the default SMS app,
5515      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5516      *     for any API level.
5517      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5518      *     for apps targeting SDK API level 29 and below.
5519      *
5520      * @hide
5521      */
5522     @RequiresPermission(anyOf = {
5523             android.Manifest.permission.READ_PHONE_STATE,
5524             android.Manifest.permission.READ_SMS,
5525             android.Manifest.permission.READ_PHONE_NUMBERS
5526     })
5527     @UnsupportedAppUsage
getMsisdn()5528     public String getMsisdn() {
5529         return getMsisdn(getSubId());
5530     }
5531 
5532     /**
5533      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
5534      *
5535      * @param subId for which msisdn is returned
5536      *
5537      * <p>Requires Permission:
5538      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5539      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5540      *     that the caller is the default SMS app,
5541      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5542      *     for any API level.
5543      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5544      *     for apps targeting SDK API level 29 and below.
5545      *
5546      * @hide
5547      */
5548     @RequiresPermission(anyOf = {
5549             android.Manifest.permission.READ_PHONE_STATE,
5550             android.Manifest.permission.READ_SMS,
5551             android.Manifest.permission.READ_PHONE_NUMBERS
5552     })
5553     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)5554     public String getMsisdn(int subId) {
5555         try {
5556             IPhoneSubInfo info = getSubscriberInfoService();
5557             if (info == null)
5558                 return null;
5559             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
5560         } catch (RemoteException ex) {
5561             return null;
5562         } catch (NullPointerException ex) {
5563             // This could happen before phone restarts due to crashing
5564             return null;
5565         }
5566     }
5567 
5568     /**
5569      * Returns the voice mail number. Return null if it is unavailable.
5570      *
5571      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5572      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5573      *
5574      * @throws UnsupportedOperationException If the device does not have
5575      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5576      */
5577     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5578     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5579     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceMailNumber()5580     public String getVoiceMailNumber() {
5581         return getVoiceMailNumber(getSubId());
5582     }
5583 
5584     /**
5585      * Returns the voice mail number for a subscription.
5586      * Return null if it is unavailable.
5587      * @param subId whose voice mail number is returned
5588      * @hide
5589      */
5590     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5591     @UnsupportedAppUsage
getVoiceMailNumber(int subId)5592     public String getVoiceMailNumber(int subId) {
5593         try {
5594             IPhoneSubInfo info = getSubscriberInfoService();
5595             if (info == null)
5596                 return null;
5597             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
5598                     getAttributionTag());
5599         } catch (RemoteException ex) {
5600             return null;
5601         } catch (NullPointerException ex) {
5602             // This could happen before phone restarts due to crashing
5603             return null;
5604         }
5605     }
5606 
5607     /**
5608      * Sets the voice mail number.
5609      *
5610      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5611      *
5612      * @param alphaTag The alpha tag to display.
5613      * @param number The voicemail number.
5614      *
5615      * @throws UnsupportedOperationException If the device does not have
5616      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5617      */
5618     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoiceMailNumber(String alphaTag, String number)5619     public boolean setVoiceMailNumber(String alphaTag, String number) {
5620         return setVoiceMailNumber(getSubId(), alphaTag, number);
5621     }
5622 
5623     /**
5624      * Sets the voicemail number for the given subscriber.
5625      *
5626      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5627      *
5628      * @param subId The subscription id.
5629      * @param alphaTag The alpha tag to display.
5630      * @param number The voicemail number.
5631      * @hide
5632      */
setVoiceMailNumber(int subId, String alphaTag, String number)5633     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
5634         try {
5635             ITelephony telephony = getITelephony();
5636             if (telephony != null)
5637                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
5638         } catch (RemoteException ex) {
5639         } catch (NullPointerException ex) {
5640         }
5641         return false;
5642     }
5643 
5644     /**
5645      * Enables or disables the visual voicemail client for a phone account.
5646      *
5647      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
5648      * {@link #hasCarrierPrivileges}), or has permission
5649      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
5650      *
5651      * @param phoneAccountHandle the phone account to change the client state
5652      * @param enabled the new state of the client
5653      * @hide
5654      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5655      * be implemented instead.
5656      */
5657     @SystemApi
5658     @Deprecated
5659     @SuppressLint("RequiresPermission")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)5660     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
5661     }
5662 
5663     /**
5664      * Returns whether the visual voicemail client is enabled.
5665      *
5666      * @param phoneAccountHandle the phone account to check for.
5667      * @return {@code true} when the visual voicemail client is enabled for this client
5668      * @hide
5669      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5670      * be implemented instead.
5671      */
5672     @SystemApi
5673     @Deprecated
5674     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5675     @SuppressLint("RequiresPermission")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)5676     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
5677         return false;
5678     }
5679 
5680     /**
5681      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
5682      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
5683      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
5684      * voicemail client in telephony.
5685      *
5686      * <p>Requires the caller to be the system dialer.
5687      *
5688      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
5689      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
5690      *
5691      * @throws UnsupportedOperationException If the device does not have
5692      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5693      * @hide
5694      */
5695     @SystemApi
5696     @SuppressLint("RequiresPermission")
5697     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
5698     @Nullable
getVisualVoicemailSettings()5699     public Bundle getVisualVoicemailSettings(){
5700         try {
5701             ITelephony telephony = getITelephony();
5702             if (telephony != null) {
5703                 return telephony
5704                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
5705             }
5706         } catch (RemoteException ex) {
5707         } catch (NullPointerException ex) {
5708         }
5709         return null;
5710     }
5711 
5712     /**
5713      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
5714      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
5715      * processing visual voicemail for the subscription.
5716      *
5717      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5718      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5719      *
5720      * @see #createForSubscriptionId(int)
5721      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
5722      * @see VisualVoicemailService
5723      *
5724      * @throws UnsupportedOperationException If the device does not have
5725      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5726      */
5727     @Nullable
5728     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5729     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5730     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVisualVoicemailPackageName()5731     public String getVisualVoicemailPackageName() {
5732         try {
5733             ITelephony telephony = getITelephony();
5734             if (telephony != null) {
5735                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
5736                         getAttributionTag(), getSubId());
5737             }
5738         } catch (RemoteException ex) {
5739         } catch (NullPointerException ex) {
5740         }
5741         return null;
5742     }
5743 
5744     /**
5745      * Set the visual voicemail SMS filter settings for the subscription ID pinned
5746      * to the TelephonyManager.
5747      * When the filter is enabled, {@link
5748      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
5749      * called when a SMS matching the settings is received. Caller must be the default dialer,
5750      * system dialer, or carrier visual voicemail app.
5751      *
5752      * @param settings The settings for the filter, or {@code null} to disable the filter.
5753      *
5754      * @see TelecomManager#getDefaultDialerPackage()
5755      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
5756      *
5757      * @throws UnsupportedOperationException If the device does not have
5758      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5759      */
5760     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)5761     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
5762         if (settings == null) {
5763             disableVisualVoicemailSmsFilter(mSubId);
5764         } else {
5765             enableVisualVoicemailSmsFilter(mSubId, settings);
5766         }
5767     }
5768 
5769     /**
5770      * Send a visual voicemail SMS. The caller must be the current default dialer.
5771      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
5772      * visual voicemail server.  Some examples for carriers using the OMTP standard include
5773      * activating and deactivating visual voicemail, or requesting the current visual voicemail
5774      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
5775      * format of these SMS messages.
5776      *
5777      * <p>Requires Permission:
5778      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
5779      *
5780      * @param number The destination number.
5781      * @param port The destination port for data SMS, or 0 for text SMS.
5782      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5783      * @param sentIntent The sent intent passed to the {@link SmsManager}
5784      *
5785      * @throws SecurityException if the caller is not the current default dialer
5786      *
5787      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5788      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5789      *
5790      * @throws UnsupportedOperationException If the device does not have
5791      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5792      */
5793     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)5794     public void sendVisualVoicemailSms(String number, int port, String text,
5795             PendingIntent sentIntent) {
5796         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
5797     }
5798 
5799     /**
5800      * Enables the visual voicemail SMS filter for a phone account. When the filter is
5801      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
5802      * visual voicemail client with
5803      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
5804      *
5805      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5806      * settings persist through default dialer changes, but the filter will only honor the setting
5807      * set by the current default dialer.
5808      *
5809      *
5810      * @param subId The subscription id of the phone account.
5811      * @param settings The settings for the filter.
5812      */
5813     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)5814     public void enableVisualVoicemailSmsFilter(int subId,
5815             VisualVoicemailSmsFilterSettings settings) {
5816         if(settings == null){
5817             throw new IllegalArgumentException("Settings cannot be null");
5818         }
5819         try {
5820             ITelephony telephony = getITelephony();
5821             if (telephony != null) {
5822                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
5823                         settings);
5824             }
5825         } catch (RemoteException ex) {
5826         } catch (NullPointerException ex) {
5827         }
5828     }
5829 
5830     /**
5831      * Disables the visual voicemail SMS filter for a phone account.
5832      *
5833      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5834      * settings persist through default dialer changes, but the filter will only honor the setting
5835      * set by the current default dialer.
5836      */
5837     /** @hide */
disableVisualVoicemailSmsFilter(int subId)5838     public void disableVisualVoicemailSmsFilter(int subId) {
5839         try {
5840             ITelephony telephony = getITelephony();
5841             if (telephony != null) {
5842                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
5843             }
5844         } catch (RemoteException ex) {
5845         } catch (NullPointerException ex) {
5846         }
5847     }
5848 
5849     /**
5850      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
5851      * if the filter is disabled.
5852      *
5853      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5854      * settings persist through default dialer changes, but the filter will only honor the setting
5855      * set by the current default dialer.
5856      */
5857     /** @hide */
5858     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)5859     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
5860         try {
5861             ITelephony telephony = getITelephony();
5862             if (telephony != null) {
5863                 return telephony
5864                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
5865             }
5866         } catch (RemoteException ex) {
5867         } catch (NullPointerException ex) {
5868         }
5869 
5870         return null;
5871     }
5872 
5873     /**
5874      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
5875      * current active visual voicemail client, or {@code null} if the filter is disabled.
5876      *
5877      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
5878      */
5879     /** @hide */
5880     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)5881     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
5882         try {
5883             ITelephony telephony = getITelephony();
5884             if (telephony != null) {
5885                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
5886             }
5887         } catch (RemoteException ex) {
5888         } catch (NullPointerException ex) {
5889         }
5890 
5891         return null;
5892     }
5893 
5894     /**
5895      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
5896      *
5897      * @param phoneAccountHandle The account to send the SMS with.
5898      * @param number The destination number.
5899      * @param port The destination port for data SMS, or 0 for text SMS.
5900      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5901      * @param sentIntent The sent intent passed to the {@link SmsManager}
5902      *
5903      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5904      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5905      *
5906      * @hide
5907      */
5908     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)5909     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
5910             String text, PendingIntent sentIntent) {
5911         try {
5912             ITelephony telephony = getITelephony();
5913             if (telephony != null) {
5914                 telephony.sendVisualVoicemailSmsForSubscriber(
5915                         mContext.getOpPackageName(), mContext.getAttributionTag(), subId, number,
5916                         port, text, sentIntent);
5917             }
5918         } catch (RemoteException ex) {
5919         }
5920     }
5921 
5922     /**
5923      * Initial SIM activation state, unknown. Not set by any carrier apps.
5924      * @hide
5925      */
5926     @SystemApi
5927     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
5928 
5929     /**
5930      * indicate SIM is under activation procedure now.
5931      * intermediate state followed by another state update with activation procedure result:
5932      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5933      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5934      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5935      * @hide
5936      */
5937     @SystemApi
5938     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
5939 
5940     /**
5941      * Indicate SIM has been successfully activated with full service
5942      * @hide
5943      */
5944     @SystemApi
5945     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
5946 
5947     /**
5948      * Indicate SIM has been deactivated by the carrier so that service is not available
5949      * and requires activation service to enable services.
5950      * Carrier apps could be signalled to set activation state to deactivated if detected
5951      * deactivated sim state and set it back to activated after successfully run activation service.
5952      * @hide
5953      */
5954     @SystemApi
5955     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
5956 
5957     /**
5958      * Restricted state indicate SIM has been activated but service are restricted.
5959      * note this is currently available for data activation state. For example out of byte sim.
5960      * @hide
5961      */
5962     @SystemApi
5963     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
5964 
5965      /**
5966       * Sets the voice activation state
5967       *
5968       * <p>Requires Permission:
5969       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5970       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5971       *
5972       * @param activationState The voice activation state
5973       * @see #SIM_ACTIVATION_STATE_UNKNOWN
5974       * @see #SIM_ACTIVATION_STATE_ACTIVATING
5975       * @see #SIM_ACTIVATION_STATE_ACTIVATED
5976       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5977       *
5978       * @throws UnsupportedOperationException If the device does not have
5979       *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}
5980       * @hide
5981       */
5982     @SystemApi
5983     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
5984     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoiceActivationState(@imActivationState int activationState)5985     public void setVoiceActivationState(@SimActivationState int activationState) {
5986         setVoiceActivationState(getSubId(), activationState);
5987     }
5988 
5989     /**
5990      * Sets the voice activation state for the given subscriber.
5991      *
5992      * <p>Requires Permission:
5993      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5994      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5995      *
5996      * @param subId The subscription id.
5997      * @param activationState The voice activation state of the given subscriber.
5998      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5999      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6000      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6001      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6002      * @hide
6003      */
6004     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)6005     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
6006         try {
6007            ITelephony telephony = getITelephony();
6008            if (telephony != null)
6009                telephony.setVoiceActivationState(subId, activationState);
6010        } catch (RemoteException ex) {
6011        } catch (NullPointerException ex) {
6012        }
6013     }
6014 
6015     /**
6016      * Sets the data activation state
6017      *
6018      * <p>Requires Permission:
6019      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
6020      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6021      *
6022      * @param activationState The data activation state
6023      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6024      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6025      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6026      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6027      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6028      *
6029      * @throws UnsupportedOperationException If the device does not have
6030      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6031      * @hide
6032      */
6033     @SystemApi
6034     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
6035     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataActivationState(@imActivationState int activationState)6036     public void setDataActivationState(@SimActivationState int activationState) {
6037         setDataActivationState(getSubId(), activationState);
6038     }
6039 
6040     /**
6041      * Sets the data activation state for the given subscriber.
6042      *
6043      * <p>Requires Permission:
6044      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
6045      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6046      *
6047      * @param subId The subscription id.
6048      * @param activationState The data activation state of the given subscriber.
6049      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6050      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6051      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6052      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6053      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6054      * @hide
6055      */
6056     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)6057     public void setDataActivationState(int subId, @SimActivationState int activationState) {
6058         try {
6059             ITelephony telephony = getITelephony();
6060             if (telephony != null)
6061                 telephony.setDataActivationState(subId, activationState);
6062         } catch (RemoteException ex) {
6063         } catch (NullPointerException ex) {
6064         }
6065     }
6066 
6067     /**
6068      * Returns the voice activation state
6069      *
6070      * <p>Requires Permission:
6071      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6072      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6073      *
6074      * @return voiceActivationState
6075      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6076      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6077      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6078      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6079      *
6080      * @throws UnsupportedOperationException If the device does not have
6081      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6082      * @hide
6083      */
6084     @SystemApi
6085     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6086     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceActivationState()6087     public @SimActivationState int getVoiceActivationState() {
6088         return getVoiceActivationState(getSubId());
6089     }
6090 
6091     /**
6092      * Returns the voice activation state for the given subscriber.
6093      *
6094      * <p>Requires Permission:
6095      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6096      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6097      *
6098      * @param subId The subscription id.
6099      *
6100      * @return voiceActivationState for the given subscriber
6101      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6102      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6103      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6104      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6105      * @hide
6106      */
6107     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)6108     public @SimActivationState int getVoiceActivationState(int subId) {
6109         try {
6110             ITelephony telephony = getITelephony();
6111             if (telephony != null)
6112                 return telephony.getVoiceActivationState(subId, getOpPackageName());
6113         } catch (RemoteException ex) {
6114         } catch (NullPointerException ex) {
6115         }
6116         return SIM_ACTIVATION_STATE_UNKNOWN;
6117     }
6118 
6119     /**
6120      * Returns the data activation state
6121      *
6122      * <p>Requires Permission:
6123      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6124      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6125      *
6126      * @return dataActivationState for the given subscriber
6127      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6128      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6129      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6130      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6131      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6132      *
6133      * @throws UnsupportedOperationException If the device does not have
6134      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6135      * @hide
6136      */
6137     @SystemApi
6138     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6139     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataActivationState()6140     public @SimActivationState int getDataActivationState() {
6141         return getDataActivationState(getSubId());
6142     }
6143 
6144     /**
6145      * Returns the data activation state for the given subscriber.
6146      *
6147      * <p>Requires Permission:
6148      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6149      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6150      *
6151      * @param subId The subscription id.
6152      *
6153      * @return dataActivationState for the given subscriber
6154      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6155      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6156      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6157      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6158      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6159      * @hide
6160      */
6161     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)6162     public @SimActivationState int getDataActivationState(int subId) {
6163         try {
6164             ITelephony telephony = getITelephony();
6165             if (telephony != null)
6166                 return telephony.getDataActivationState(subId, getOpPackageName());
6167         } catch (RemoteException ex) {
6168         } catch (NullPointerException ex) {
6169         }
6170         return SIM_ACTIVATION_STATE_UNKNOWN;
6171     }
6172 
6173     /**
6174      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
6175      * but the count is unknown.
6176      * @hide
6177      */
6178     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6179     @UnsupportedAppUsage
getVoiceMessageCount()6180     public int getVoiceMessageCount() {
6181         return getVoiceMessageCount(getSubId());
6182     }
6183 
6184     /**
6185      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
6186      * not have the READ_PHONE_STATE permission.
6187      * @param subId whose voice message count is returned
6188      * @hide
6189      */
6190     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6191     @UnsupportedAppUsage
getVoiceMessageCount(int subId)6192     public int getVoiceMessageCount(int subId) {
6193         try {
6194             ITelephony telephony = getITelephony();
6195             if (telephony == null)
6196                 return 0;
6197             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
6198                     getAttributionTag());
6199         } catch (RemoteException ex) {
6200             return 0;
6201         } catch (NullPointerException ex) {
6202             // This could happen before phone restarts due to crashing
6203             return 0;
6204         }
6205     }
6206 
6207     /**
6208      * Retrieves the alphabetic identifier associated with the voice
6209      * mail number.
6210      *
6211      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
6212      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6213      *
6214      * @throws UnsupportedOperationException If the device does not have
6215      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6216      */
6217     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
6218     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6219     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceMailAlphaTag()6220     public String getVoiceMailAlphaTag() {
6221         return getVoiceMailAlphaTag(getSubId());
6222     }
6223 
6224     /**
6225      * Retrieves the alphabetic identifier associated with the voice
6226      * mail number for a subscription.
6227      * @param subId whose alphabetic identifier associated with the
6228      * voice mail number is returned
6229      * @hide
6230      */
6231     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6232     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)6233     public String getVoiceMailAlphaTag(int subId) {
6234         try {
6235             IPhoneSubInfo info = getSubscriberInfoService();
6236             if (info == null)
6237                 return null;
6238             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
6239                     getAttributionTag());
6240         } catch (RemoteException ex) {
6241             return null;
6242         } catch (NullPointerException ex) {
6243             // This could happen before phone restarts due to crashing
6244             return null;
6245         }
6246     }
6247 
6248     /**
6249      * Send the special dialer code. The IPC caller must be the current default dialer or have
6250      * carrier privileges (see {@link #hasCarrierPrivileges}).
6251      *
6252      * @param inputCode The special dialer code to send
6253      *
6254      * @throws SecurityException if the caller does not have carrier privileges or is not the
6255      *         current default dialer
6256      * @throws UnsupportedOperationException If the device does not have
6257      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6258      */
6259     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
sendDialerSpecialCode(String inputCode)6260     public void sendDialerSpecialCode(String inputCode) {
6261         try {
6262             final ITelephony telephony = getITelephony();
6263             if (telephony == null) {
6264                 return;
6265             }
6266             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
6267         } catch (RemoteException ex) {
6268             Rlog.e(TAG, "Telephony#sendDialerSpecialCode RemoteException" + ex);
6269         }
6270     }
6271 
6272     /**
6273      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
6274      * @return the IMPI, or null if not present or not loaded
6275      * @hide
6276      * @deprecated use {@link #getImsPrivateUserIdentity()}
6277      */
6278     @UnsupportedAppUsage
getIsimImpi()6279     public String getIsimImpi() {
6280         try {
6281             IPhoneSubInfo info = getSubscriberInfoService();
6282             if (info == null)
6283                 return null;
6284             //get the Isim Impi based on subId
6285             return info.getIsimImpi(getSubId());
6286         } catch (RemoteException ex) {
6287             return null;
6288         } catch (NullPointerException ex) {
6289             // This could happen before phone restarts due to crashing
6290             return null;
6291         }
6292     }
6293 
6294     /**
6295      * Returns the IMS private user identity (IMPI) of the subscription that was loaded from the
6296      * ISIM records {@link #APPTYPE_ISIM}. This value is fetched from the Elementary file EF_IMPI.
6297      * The contents of the file is a <b>Ip Multimedia Service Private User Identity</b> of the user
6298      * as defined in the section 4.2.2 of 3GPP TS 131 103.
6299      *
6300      * @return IMPI (IMS private user identity) of type string.
6301      * @throws IllegalStateException in case the ISIM has’t been loaded
6302      * @throws SecurityException if the caller does not have the required permission/privileges
6303      * @hide
6304      */
6305     @NonNull
6306     @RequiresPermission(android.Manifest.permission.USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER)
6307     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getImsPrivateUserIdentity()6308     public String getImsPrivateUserIdentity() {
6309         try {
6310             IPhoneSubInfo info = getSubscriberInfoService();
6311             if (info == null) {
6312                 Rlog.e(TAG, "getImsPrivateUserIdentity(): IPhoneSubInfo instance is NULL");
6313                 throw new RuntimeException("IMPI error: Subscriber Info is null");
6314             }
6315             return info.getImsPrivateUserIdentity(getSubId(), getOpPackageName(),
6316                     getAttributionTag());
6317         } catch (RemoteException | NullPointerException | IllegalArgumentException ex) {
6318             Rlog.e(TAG, "getImsPrivateUserIdentity() Exception = " + ex);
6319             throw new RuntimeException(ex.getMessage());
6320         }
6321     }
6322 
6323     /**
6324      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
6325      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
6326      * hasn't been loaded or isn't present on the ISIM.
6327      *
6328      * <p>Requires Permission:
6329      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6330      *
6331      * @throws UnsupportedOperationException If the device does not have
6332      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
6333      * @hide
6334      */
6335     @Nullable
6336     @SystemApi
6337     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6338     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIsimDomain()6339     public String getIsimDomain() {
6340         try {
6341             IPhoneSubInfo info = getSubscriberInfoService();
6342             if (info == null)
6343                 return null;
6344             //get the Isim Domain based on subId
6345             return info.getIsimDomain(getSubId());
6346         } catch (RemoteException ex) {
6347             return null;
6348         } catch (NullPointerException ex) {
6349             // This could happen before phone restarts due to crashing
6350             return null;
6351         }
6352     }
6353 
6354     /**
6355      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
6356      * @return an array of IMPU strings, with one IMPU per string, or null if
6357      *      not present or not loaded
6358      *
6359      * @throws UnsupportedOperationException If the device does not have
6360      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
6361      * @hide
6362      * @deprecated use {@link #getImsPublicUserIdentities()}
6363      */
6364     @UnsupportedAppUsage
6365     @Nullable
6366     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()6367     public String[] getIsimImpu() {
6368         try {
6369             IPhoneSubInfo info = getSubscriberInfoService();
6370             if (info == null)
6371                 return null;
6372             //get the Isim Impu based on subId
6373             return info.getIsimImpu(getSubId());
6374         } catch (RemoteException ex) {
6375             return null;
6376         } catch (NullPointerException ex) {
6377             // This could happen before phone restarts due to crashing
6378             return null;
6379         }
6380     }
6381 
6382     /**
6383      * Returns the IMS public user identities (IMPU) of the subscription that was loaded from the
6384      * ISIM records {@link #APPTYPE_ISIM}. This value is fetched from the Elementary file EF_IMPU.
6385      * The contents of the file are <b>Ip Multimedia Service Public User Identities</b> of the user
6386      * as defined in the section 4.2.4 of 3GPP TS 131 103. It contains one or more records.
6387      *
6388      * @return List of public user identities of type android.net.Uri or empty list  if
6389      *         EF_IMPU is not available.
6390      * @throws IllegalStateException in case the ISIM hasn’t been loaded
6391      * @throws SecurityException if the caller does not have the required permission/privilege
6392      * @throws UnsupportedOperationException If the device does not have
6393      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
6394      * @hide
6395      */
6396     @NonNull
6397     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PHONE_NUMBERS,
6398             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
6399     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getImsPublicUserIdentities()6400     public List<Uri> getImsPublicUserIdentities() {
6401         try {
6402             IPhoneSubInfo info = getSubscriberInfoService();
6403             if (info == null) {
6404                 throw new RuntimeException("IMPU error: Subscriber Info is null");
6405             }
6406             return info.getImsPublicUserIdentities(getSubId(), getOpPackageName(),
6407                     getAttributionTag());
6408         } catch (IllegalArgumentException | NullPointerException ex) {
6409             Rlog.e(TAG, "getImsPublicUserIdentities Exception = " + ex);
6410         } catch (RemoteException ex) {
6411             Rlog.e(TAG, "getImsPublicUserIdentities Exception = " + ex);
6412             ex.rethrowAsRuntimeException();
6413         }
6414         return Collections.EMPTY_LIST;
6415     }
6416 
6417     /**
6418      * Device call state: No activity.
6419      */
6420     public static final int CALL_STATE_IDLE = 0;
6421     /**
6422      * Device call state: Ringing. A new call arrived and is
6423      *  ringing or waiting. In the latter case, another call is
6424      *  already active.
6425      */
6426     public static final int CALL_STATE_RINGING = 1;
6427     /**
6428      * Device call state: Off-hook. At least one call exists
6429      * that is dialing, active, or on hold, and no calls are ringing
6430      * or waiting.
6431      */
6432     public static final int CALL_STATE_OFFHOOK = 2;
6433 
6434     /**
6435      * Returns the state of all calls on the device.
6436      * <p>
6437      * This method considers not only calls in the Telephony stack, but also calls via other
6438      * {@link android.telecom.ConnectionService} implementations.
6439      * <p>
6440      * Note: The call state returned via this method may differ from what is reported by {@link
6441      * TelephonyCallback.CallStateListener#onCallStateChanged(int)}, as that callback only considers
6442      * Telephony (mobile) calls.
6443      * <p>
6444      * Requires Permission:
6445      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
6446      * targeting API level 31+.
6447      *
6448      * @return the current call state.
6449      * @deprecated Use {@link #getCallStateForSubscription} to retrieve the call state for a
6450      * specific telephony subscription (which allows carrier privileged apps),
6451      * {@link TelephonyCallback.CallStateListener} for real-time call state updates, or
6452      * {@link TelecomManager#isInCall()}, which supplies an aggregate "in call" state for the entire
6453      * device.
6454      */
6455     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
6456     @Deprecated
getCallState()6457     public @CallState int getCallState() {
6458         if (mContext != null) {
6459             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
6460             if (telecomManager != null) {
6461                 return telecomManager.getCallState();
6462             }
6463         }
6464         return CALL_STATE_IDLE;
6465     }
6466 
6467     /**
6468      * Retrieve the call state for a specific subscription that was specified when this
6469      * TelephonyManager instance was created.
6470      * <p>Requires Permission:
6471      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the calling
6472      * application has carrier privileges (see {@link #hasCarrierPrivileges}).
6473      * @see TelephonyManager#createForSubscriptionId(int)
6474      * @see TelephonyManager#createForPhoneAccountHandle(PhoneAccountHandle)
6475      * @return The call state of the subscription associated with this TelephonyManager instance.
6476      *
6477      * @throws UnsupportedOperationException If the device does not have
6478      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6479      */
6480     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6481     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallStateForSubscription()6482     public @CallState int getCallStateForSubscription() {
6483         return getCallState(getSubId());
6484     }
6485 
6486     /**
6487      * Returns the Telephony call state for calls on a specific subscription.
6488      * <p>
6489      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
6490      * considers the state of calls from other {@link android.telecom.ConnectionService}
6491      * implementations.
6492      * <p>
6493      * Requires Permission:
6494      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
6495      * targeting API level 31+ or that the calling application has carrier privileges
6496      * (see {@link #hasCarrierPrivileges()}).
6497      *
6498      * @param subId the subscription to check call state for.
6499      * @hide
6500      */
6501     @UnsupportedAppUsage
6502     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
getCallState(int subId)6503     public @CallState int getCallState(int subId) {
6504         ITelephony telephony = getITelephony();
6505         if (telephony == null) {
6506             return CALL_STATE_IDLE;
6507         }
6508         try {
6509             return telephony.getCallStateForSubscription(subId, mContext.getPackageName(),
6510                     mContext.getAttributionTag());
6511         } catch (RemoteException e) {
6512             return CALL_STATE_IDLE;
6513         }
6514     }
6515 
6516     /** Data connection activity: No traffic. */
6517     public static final int DATA_ACTIVITY_NONE = 0x00000000;
6518     /** Data connection activity: Currently receiving IP PPP traffic. */
6519     public static final int DATA_ACTIVITY_IN = 0x00000001;
6520     /** Data connection activity: Currently sending IP PPP traffic. */
6521     public static final int DATA_ACTIVITY_OUT = 0x00000002;
6522     /** Data connection activity: Currently both sending and receiving
6523      *  IP PPP traffic. */
6524     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
6525     /**
6526      * Data connection is active, but physical link is down
6527      */
6528     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
6529 
6530     /**
6531      * Returns a constant indicating the type of activity on a data connection
6532      * (cellular).
6533      *
6534      * @see #DATA_ACTIVITY_NONE
6535      * @see #DATA_ACTIVITY_IN
6536      * @see #DATA_ACTIVITY_OUT
6537      * @see #DATA_ACTIVITY_INOUT
6538      * @see #DATA_ACTIVITY_DORMANT
6539      *
6540      * @throws UnsupportedOperationException If the device does not have
6541      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6542      */
6543     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataActivity()6544     public int getDataActivity() {
6545         try {
6546             ITelephony telephony = getITelephony();
6547             if (telephony == null)
6548                 return DATA_ACTIVITY_NONE;
6549             return telephony.getDataActivityForSubId(
6550                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
6551         } catch (RemoteException ex) {
6552             // the phone process is restarting.
6553             return DATA_ACTIVITY_NONE;
6554         } catch (NullPointerException ex) {
6555           // the phone process is restarting.
6556           return DATA_ACTIVITY_NONE;
6557       }
6558     }
6559 
6560     /** @hide */
6561     @IntDef(prefix = {"DATA_"}, value = {
6562             DATA_UNKNOWN,
6563             DATA_DISCONNECTED,
6564             DATA_CONNECTING,
6565             DATA_CONNECTED,
6566             DATA_SUSPENDED,
6567             DATA_DISCONNECTING,
6568             DATA_HANDOVER_IN_PROGRESS,
6569     })
6570     @Retention(RetentionPolicy.SOURCE)
6571     public @interface DataState{}
6572 
6573     /** Data connection state: Unknown.  Used before we know the state. */
6574     public static final int DATA_UNKNOWN        = -1;
6575     /** Data connection state: Disconnected. IP traffic not available. */
6576     public static final int DATA_DISCONNECTED   = 0;
6577     /** Data connection state: Currently setting up a data connection. */
6578     public static final int DATA_CONNECTING     = 1;
6579     /** Data connection state: Connected. IP traffic should be available. */
6580     public static final int DATA_CONNECTED      = 2;
6581     /** Data connection state: Suspended. The connection is up, but IP
6582      * traffic is temporarily unavailable. For example, in a 2G network,
6583      * data activity may be suspended when a voice call arrives. */
6584     public static final int DATA_SUSPENDED      = 3;
6585     /**
6586      * Data connection state: Disconnecting.
6587      *
6588      * IP traffic may be available but will cease working imminently.
6589      */
6590     public static final int DATA_DISCONNECTING = 4;
6591 
6592     /**
6593      * Data connection state: Handover in progress. The connection is being transited from cellular
6594      * network to IWLAN, or from IWLAN to cellular network.
6595      */
6596     public static final int DATA_HANDOVER_IN_PROGRESS = 5;
6597 
6598     /**
6599      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
6600      */
6601     @ChangeId
6602     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
6603     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
6604 
6605     /**
6606      * Returns a constant indicating the current data connection state
6607      * (cellular).
6608      *
6609      * @see #DATA_DISCONNECTED
6610      * @see #DATA_CONNECTING
6611      * @see #DATA_CONNECTED
6612      * @see #DATA_SUSPENDED
6613      * @see #DATA_DISCONNECTING
6614      * @see #DATA_HANDOVER_IN_PROGRESS
6615      *
6616      * @throws UnsupportedOperationException If the device does not have
6617      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6618      */
6619     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataState()6620     public int getDataState() {
6621         try {
6622             ITelephony telephony = getITelephony();
6623             if (telephony == null)
6624                 return DATA_DISCONNECTED;
6625             int state = telephony.getDataStateForSubId(
6626                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
6627             if (state == TelephonyManager.DATA_DISCONNECTING
6628                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
6629                 return TelephonyManager.DATA_CONNECTED;
6630             }
6631 
6632             return state;
6633         } catch (RemoteException ex) {
6634             // the phone process is restarting.
6635             return DATA_DISCONNECTED;
6636         } catch (NullPointerException ex) {
6637             return DATA_DISCONNECTED;
6638         }
6639     }
6640 
getITelephony()6641     private static ITelephony getITelephony() {
6642         // Keeps cache disabled until test fixes are checked into AOSP.
6643         if (!sServiceHandleCacheEnabled) {
6644             return ITelephony.Stub.asInterface(
6645                     TelephonyFrameworkInitializer
6646                             .getTelephonyServiceManager()
6647                             .getTelephonyServiceRegisterer()
6648                             .get());
6649         }
6650 
6651         if (sITelephony == null) {
6652             ITelephony temp = ITelephony.Stub.asInterface(
6653                     TelephonyFrameworkInitializer
6654                             .getTelephonyServiceManager()
6655                             .getTelephonyServiceRegisterer()
6656                             .get());
6657             synchronized (sCacheLock) {
6658                 if (sITelephony == null && temp != null) {
6659                     try {
6660                         sITelephony = temp;
6661                         sITelephony.asBinder().linkToDeath(sServiceDeath, 0);
6662                     } catch (Exception e) {
6663                         // something has gone horribly wrong
6664                         sITelephony = null;
6665                     }
6666                 }
6667             }
6668         }
6669         return sITelephony;
6670     }
6671 
getIOns()6672     private IOns getIOns() {
6673         return IOns.Stub.asInterface(
6674                 TelephonyFrameworkInitializer
6675                         .getTelephonyServiceManager()
6676                         .getOpportunisticNetworkServiceRegisterer()
6677                         .get());
6678     }
6679 
6680     //
6681     //
6682     // PhoneStateListener
6683     //
6684     //
6685 
6686     /**
6687      * Registers a listener object to receive notification of changes
6688      * in specified telephony states.
6689      * <p>
6690      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
6691      * state of interest in the events argument.
6692      *
6693      * At registration, and when a specified telephony state changes, the telephony manager invokes
6694      * the appropriate callback method on the listener object and passes the current (updated)
6695      * values.
6696      * <p>
6697      * To un-register a listener, pass the listener object and set the events argument to
6698      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
6699      *
6700      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
6701      * applies to the given subId. Otherwise, applies to
6702      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
6703      * pass a separate listener object to each TelephonyManager object created with
6704      * {@link #createForSubscriptionId}.
6705      *
6706      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
6707      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
6708      * {@link SecurityException} will be thrown otherwise.
6709      *
6710      * This API should be used sparingly -- large numbers of listeners will cause system
6711      * instability. If a process has registered too many listeners without unregistering them, it
6712      * may encounter an {@link IllegalStateException} when trying to register more listeners.
6713      *
6714      * @param listener The {@link PhoneStateListener} object to register
6715      *                 (or unregister)
6716      * @param events The telephony state(s) of interest to the listener,
6717      *               as a bitwise-OR combination of {@link PhoneStateListener}
6718      *               LISTEN_ flags.
6719      * @deprecated Use {@link #registerTelephonyCallback(Executor, TelephonyCallback)}.
6720      */
6721     @Deprecated
listen(PhoneStateListener listener, int events)6722     public void listen(PhoneStateListener listener, int events) {
6723         if (mContext == null) return;
6724         boolean notifyNow = (getITelephony() != null);
6725         TelephonyRegistryManager telephonyRegistry =
6726                 (TelephonyRegistryManager)
6727                         mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
6728         if (telephonyRegistry != null) {
6729             Set<String> renouncedPermissions = getRenouncedPermissions();
6730             boolean renounceFineLocationAccess = renouncedPermissions
6731                     .contains(Manifest.permission.ACCESS_FINE_LOCATION);
6732             boolean renounceCoarseLocationAccess = renouncedPermissions
6733                     .contains(Manifest.permission.ACCESS_COARSE_LOCATION);
6734             telephonyRegistry.listenFromListener(mSubId, renounceFineLocationAccess,
6735                     renounceCoarseLocationAccess, getOpPackageName(), getAttributionTag(),
6736                     listener, events, notifyNow);
6737         } else {
6738             Rlog.w(TAG, "telephony registry not ready.");
6739         }
6740     }
6741 
6742     /** @hide */
6743     @Retention(RetentionPolicy.SOURCE)
6744     @IntDef(prefix = {"ERI_"}, value = {
6745             ERI_ON,
6746             ERI_OFF,
6747             ERI_FLASH
6748     })
6749     public @interface EriIconIndex {}
6750 
6751     /**
6752      * ERI (Enhanced Roaming Indicator) is ON i.e value 0 defined by
6753      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6754      */
6755     public static final int ERI_ON = 0;
6756 
6757     /**
6758      * ERI (Enhanced Roaming Indicator) is OFF i.e value 1 defined by
6759      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6760      */
6761     public static final int ERI_OFF = 1;
6762 
6763     /**
6764      * ERI (Enhanced Roaming Indicator) is FLASH i.e value 2 defined by
6765      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6766      */
6767     public static final int ERI_FLASH = 2;
6768 
6769     /** @hide */
6770     @Retention(RetentionPolicy.SOURCE)
6771     @IntDef(prefix = {"ERI_ICON_MODE_"}, value = {
6772             ERI_ICON_MODE_NORMAL,
6773             ERI_ICON_MODE_FLASH
6774     })
6775     public @interface EriIconMode {}
6776 
6777     /**
6778      * ERI (Enhanced Roaming Indicator) icon mode is normal. This constant represents that
6779      * the ERI icon should be displayed normally.
6780      *
6781      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6782      * @hide
6783      */
6784     public static final int ERI_ICON_MODE_NORMAL = 0;
6785 
6786     /**
6787      * ERI (Enhanced Roaming Indicator) icon mode flash. This constant represents that
6788      * the ERI icon should be flashing.
6789      *
6790      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6791      * @hide
6792      */
6793     public static final int ERI_ICON_MODE_FLASH = 1;
6794 
6795     /**
6796      * Returns the CDMA ERI icon display number. The number is assigned by
6797      * 3GPP2 C.R1001-H v1.0 Table 8.1-1. Additionally carriers define their own ERI display numbers.
6798      * Defined values are {@link #ERI_ON}, {@link #ERI_OFF}, and {@link #ERI_FLASH}.
6799      *
6800      * @throws UnsupportedOperationException If the device does not have
6801      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
6802      * @hide
6803      */
6804     @SystemApi
6805     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6806     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaEnhancedRoamingIndicatorDisplayNumber()6807     public @EriIconIndex int getCdmaEnhancedRoamingIndicatorDisplayNumber() {
6808         return getCdmaEriIconIndex(getSubId());
6809     }
6810 
6811     /**
6812      * Returns the CDMA ERI icon index to display for a subscription.
6813      * @hide
6814      */
6815     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6816     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)6817     public @EriIconIndex int getCdmaEriIconIndex(int subId) {
6818         try {
6819             ITelephony telephony = getITelephony();
6820             if (telephony == null)
6821                 return -1;
6822             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
6823                     getAttributionTag());
6824         } catch (RemoteException ex) {
6825             // the phone process is restarting.
6826             return -1;
6827         } catch (NullPointerException ex) {
6828             return -1;
6829         }
6830     }
6831 
6832     /**
6833      * Returns the CDMA ERI icon mode for a subscription.
6834      * 0 - ON
6835      * 1 - FLASHING
6836      *
6837      * @hide
6838      */
6839     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6840     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)6841     public @EriIconMode int getCdmaEriIconMode(int subId) {
6842         try {
6843             ITelephony telephony = getITelephony();
6844             if (telephony == null)
6845                 return -1;
6846             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
6847                     getAttributionTag());
6848         } catch (RemoteException ex) {
6849             // the phone process is restarting.
6850             return -1;
6851         } catch (NullPointerException ex) {
6852             return -1;
6853         }
6854     }
6855 
6856     /**
6857      * Returns the CDMA ERI text,
6858      *
6859      * @hide
6860      */
6861     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()6862     public String getCdmaEriText() {
6863         return getCdmaEriText(getSubId());
6864     }
6865 
6866     /**
6867      * Returns the CDMA ERI text, of a subscription
6868      *
6869      * @hide
6870      */
6871     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6872     @UnsupportedAppUsage
getCdmaEriText(int subId)6873     public String getCdmaEriText(int subId) {
6874         try {
6875             ITelephony telephony = getITelephony();
6876             if (telephony == null)
6877                 return null;
6878             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
6879                     getAttributionTag());
6880         } catch (RemoteException ex) {
6881             // the phone process is restarting.
6882             return null;
6883         } catch (NullPointerException ex) {
6884             return null;
6885         }
6886     }
6887 
6888     // TODO(b/316183370): replace all @code with @link in javadoc after feature is released
6889     /**
6890      * @return true if the current device is "voice capable".
6891      * <p>
6892      * "Voice capable" means that this device supports circuit-switched
6893      * (i.e. voice) phone calls over the telephony network, and is allowed
6894      * to display the in-call UI while a cellular voice call is active.
6895      * This will be false on "data only" devices which can't make voice
6896      * calls and don't support any in-call UI.
6897      * <p>
6898      * Note: the meaning of this flag is subtly different from the
6899      * PackageManager.FEATURE_TELEPHONY system feature, which is available
6900      * on any device with a telephony radio, even if the device is
6901      * data-only.
6902      * @deprecated Replaced by {@code #isDeviceVoiceCapable()}. Starting from Android 15, voice
6903      * capability may also be overridden by carriers for a given subscription. For voice capable
6904      * device (when {@code #isDeviceVoiceCapable} return {@code true}), caller should check for
6905      * subscription-level voice capability as well. See {@code #isDeviceVoiceCapable} for details.
6906      */
6907     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
6908     @Deprecated
isVoiceCapable()6909     public boolean isVoiceCapable() {
6910         if (mContext == null) return true;
6911         return mContext.getResources().getBoolean(
6912                 com.android.internal.R.bool.config_voice_capable);
6913     }
6914 
6915     /**
6916      * @return true if the current device is "voice capable".
6917      * <p>
6918      * "Voice capable" means that this device supports circuit-switched or IMS packet switched
6919      * (i.e. voice) phone calls over the telephony network, and is allowed to display the in-call
6920      * UI while a cellular voice call is active. This will be false on "data only" devices which
6921      * can't make voice calls and don't support any in-call UI.
6922      * <p>
6923      * Note: the meaning of this flag is subtly different from the PackageManager
6924      * .FEATURE_TELEPHONY system feature, which is available on any device with a telephony
6925      * radio, even if the device is data-only.
6926      * <p>
6927      * Starting from Android 15, voice capability may also be overridden by carrier for a given
6928      * subscription on a voice capable device. To check if a subscription is "voice capable",
6929      * call method {@code SubscriptionInfo#getServiceCapabilities()} and check if
6930      * {@code SubscriptionManager#SERVICE_CAPABILITY_VOICE} is included.
6931      *
6932      * @see SubscriptionInfo#getServiceCapabilities()
6933      */
6934     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
6935     @FlaggedApi(Flags.FLAG_DATA_ONLY_CELLULAR_SERVICE)
isDeviceVoiceCapable()6936     public boolean isDeviceVoiceCapable() {
6937         return isVoiceCapable();
6938     }
6939 
6940     /**
6941      * @return true if the current device supports sms service.
6942      * <p>
6943      * If true, this means that the device supports both sending and
6944      * receiving sms via the telephony network.
6945      * <p>
6946      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
6947      *       disabled when device doesn't support sms.
6948      * @deprecated Replaced by {@code #isDeviceSmsCapable()}. Starting from Android 15, SMS
6949      * capability may also be overridden by carriers for a given subscription. For SMS capable
6950      * device (when {@code #isDeviceSmsCapable} return {@code true}), caller should check for
6951      * subscription-level SMS capability as well. See {@code #isDeviceSmsCapable} for details.
6952      */
6953     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
isSmsCapable()6954     public boolean isSmsCapable() {
6955         if (mContext == null) return true;
6956         return mContext.getResources().getBoolean(
6957                 com.android.internal.R.bool.config_sms_capable);
6958     }
6959 
6960     /**
6961      * @return true if the current device supports SMS service.
6962      * <p>
6963      * If true, this means that the device supports both sending and
6964      * receiving SMS via the telephony network.
6965      * <p>
6966      * Note: Voicemail waiting SMS, cell broadcasting SMS, and MMS are
6967      *       disabled when device doesn't support SMS.
6968      * <p>
6969      * Starting from Android 15, SMS capability may also be overridden by carriers for a given
6970      * subscription on an SMS capable device. To check if a subscription is "SMS capable",
6971      * call method {@code SubscriptionInfo#getServiceCapabilities()} and check if
6972      * {@code SubscriptionManager#SERVICE_CAPABILITY_SMS} is included.
6973      *
6974      * @see SubscriptionInfo#getServiceCapabilities()
6975      */
6976     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
6977     @FlaggedApi(Flags.FLAG_DATA_ONLY_CELLULAR_SERVICE)
isDeviceSmsCapable()6978     public boolean isDeviceSmsCapable() {
6979         return isSmsCapable();
6980     }
6981 
6982     /**
6983      * Requests all available cell information from all radios on the device including the
6984      * camped/registered, serving, and neighboring cells.
6985      *
6986      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
6987      * {@link android.telephony.CellInfoCdma CellInfoCdma},
6988      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
6989      * {@link android.telephony.CellInfoLte CellInfoLte}, and
6990      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
6991      * It is typical to see instances of one or more of any these in the list. In addition, zero
6992      * or more of the returned objects may be considered registered; that is, their
6993      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
6994      * methods may return true, indicating that the cell is being used or would be used for
6995      * signaling communication if necessary.
6996      *
6997      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
6998      * if this API results in a change of the cached CellInfo, that change will be reported via
6999      * {@link TelephonyCallback.CellInfoListener#onCellInfoChanged(List) onCellInfoChanged()}.
7000      *
7001      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
7002      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
7003      * will receive the latest cached results, which may not be current. Apps targeting
7004      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
7005      * CellInfo should call
7006      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
7007      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
7008      * recency of CellInfo data, callers should check
7009      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
7010      *
7011      * <p>This method returns valid data for devices with
7012      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
7013      * where only partial information is available for a particular CellInfo entry, unavailable
7014      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
7015      * cells will include at least a valid set of technology-specific identification info and a
7016      * power level measurement.
7017      *
7018      * <p>This method is preferred over using {@link
7019      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
7020      *
7021      * @return List of {@link android.telephony.CellInfo}; null if cell
7022      * information is unavailable.
7023      *
7024      * @throws UnsupportedOperationException If the device does not have
7025      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
7026      */
7027     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
7028     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getAllCellInfo()7029     public List<CellInfo> getAllCellInfo() {
7030         try {
7031             ITelephony telephony = getITelephony();
7032             if (telephony == null)
7033                 return null;
7034             return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
7035         } catch (RemoteException ex) {
7036         } catch (NullPointerException ex) {
7037         }
7038         return null;
7039     }
7040 
7041     /** Callback for providing asynchronous {@link CellInfo} on request */
7042     public abstract static class CellInfoCallback {
7043         /**
7044          * Success response to
7045          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
7046          *
7047          * Invoked when there is a response to
7048          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
7049          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
7050          * list will be provided. If an error occurs, null will be provided unless the onError
7051          * callback is overridden.
7052          *
7053          * @param cellInfo a list of {@link CellInfo} or an empty list.
7054          *
7055          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
7056          */
onCellInfo(@onNull List<CellInfo> cellInfo)7057         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
7058 
7059         /** @hide */
7060         @Retention(RetentionPolicy.SOURCE)
7061         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
7062         public @interface CellInfoCallbackError {}
7063 
7064         /**
7065          * The system timed out waiting for a response from the Radio.
7066          */
7067         public static final int ERROR_TIMEOUT = 1;
7068 
7069         /**
7070          * The modem returned a failure.
7071          */
7072         public static final int ERROR_MODEM_ERROR = 2;
7073 
7074         /**
7075          * Error response to
7076          * {@link TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
7077          *
7078          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
7079          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
7080          * function to receive detailed status information in the event of an error. By default,
7081          * this function will invoke onCellInfo() with null.
7082          *
7083          * @param errorCode an error code indicating the type of failure.
7084          * @param detail a Throwable object with additional detail regarding the failure if
7085          *     available, otherwise null.
7086          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)7087         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
7088             // By default, simply invoke the success callback with an empty list.
7089             onCellInfo(new ArrayList<CellInfo>());
7090         }
7091     };
7092 
7093     /**
7094      * Used for checking if the target SDK version for the current process is S or above.
7095      *
7096      * <p> Applies to the following methods:
7097      * {@link #requestCellInfoUpdate},
7098      * {@link #setPreferredOpportunisticDataSubscription},
7099      * {@link #updateAvailableNetworks},
7100      * requestNumberVerification(),
7101      * setSimPowerStateForSlot(),
7102      */
7103     @ChangeId
7104     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.R)
7105     private static final long NULL_TELEPHONY_THROW_NO_CB = 182185642L;
7106 
7107     /**
7108      * Requests all available cell information from the current subscription for observed
7109      * camped/registered, serving, and neighboring cells.
7110      *
7111      * <p>Any available results from this request will be provided by calls to
7112      * {@link TelephonyCallback.CellInfoListener#onCellInfoChanged(List) onCellInfoChanged()}
7113      * for each active subscription.
7114      *
7115      * <p>This method returns valid data for devices with
7116      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
7117      * that do not implement this feature, the behavior is not reliable.
7118      *
7119      * @param executor the executor on which callback will be invoked.
7120      * @param callback a callback to receive CellInfo.
7121      *
7122      * @throws UnsupportedOperationException If the device does not have
7123      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
7124      */
7125     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
7126     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)7127     public void requestCellInfoUpdate(
7128             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
7129         try {
7130             ITelephony telephony = getITelephony();
7131             if (telephony == null) {
7132                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
7133                     throw new IllegalStateException("Telephony is null");
7134                 } else {
7135                     return;
7136                 }
7137             }
7138 
7139             telephony.requestCellInfoUpdate(
7140                     getSubId(),
7141                     new ICellInfoCallback.Stub() {
7142                         @Override
7143                         public void onCellInfo(List<CellInfo> cellInfo) {
7144                             final long identity = Binder.clearCallingIdentity();
7145                             try {
7146                                 executor.execute(() -> callback.onCellInfo(cellInfo));
7147                             } finally {
7148                                 Binder.restoreCallingIdentity(identity);
7149                             }
7150                         }
7151 
7152                         @Override
7153                         public void onError(int errorCode, String exceptionName, String message) {
7154                             final long identity = Binder.clearCallingIdentity();
7155                             try {
7156                                 executor.execute(() -> callback.onError(
7157                                         errorCode,
7158                                         createThrowableByClassName(exceptionName, message)));
7159                             } finally {
7160                                 Binder.restoreCallingIdentity(identity);
7161                             }
7162                         }
7163                     }, getOpPackageName(), getAttributionTag());
7164         } catch (RemoteException ex) {
7165             runOnBackgroundThread(() -> executor.execute(
7166                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
7167         }
7168     }
7169 
7170     /**
7171      * Requests all available cell information from the current subscription for observed
7172      * camped/registered, serving, and neighboring cells.
7173      *
7174      * <p>Any available results from this request will be provided by calls to
7175      * {@link TelephonyCallback.CellInfoListener#onCellInfoChanged(List) onCellInfoChanged()}
7176      * for each active subscription.
7177      *
7178      * <p>This method returns valid data for devices with
7179      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
7180      * that do not implement this feature, the behavior is not reliable.
7181      *
7182      * @param workSource the requestor to whom the power consumption for this should be attributed.
7183      * @param executor the executor on which callback will be invoked.
7184      * @param callback a callback to receive CellInfo.
7185      *
7186      * @throws UnsupportedOperationException If the device does not have
7187      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
7188      * @hide
7189      */
7190     @SystemApi
7191     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
7192             android.Manifest.permission.MODIFY_PHONE_STATE})
7193     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)7194     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
7195             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
7196         try {
7197             ITelephony telephony = getITelephony();
7198             if (telephony == null) {
7199                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
7200                     throw new IllegalStateException("Telephony is null");
7201                 } else {
7202                     return;
7203                 }
7204             }
7205 
7206             telephony.requestCellInfoUpdateWithWorkSource(
7207                     getSubId(),
7208                     new ICellInfoCallback.Stub() {
7209                         @Override
7210                         public void onCellInfo(List<CellInfo> cellInfo) {
7211                             final long identity = Binder.clearCallingIdentity();
7212                             try {
7213                                 executor.execute(() -> callback.onCellInfo(cellInfo));
7214                             } finally {
7215                                 Binder.restoreCallingIdentity(identity);
7216                             }
7217 
7218                         }
7219 
7220                         @Override
7221                         public void onError(int errorCode, String exceptionName, String message) {
7222                             final long identity = Binder.clearCallingIdentity();
7223                             try {
7224                                 executor.execute(() -> callback.onError(
7225                                         errorCode,
7226                                         createThrowableByClassName(exceptionName, message)));
7227                             } finally {
7228                                 Binder.restoreCallingIdentity(identity);
7229                             }
7230                         }
7231                     }, getOpPackageName(), getAttributionTag(), workSource);
7232         } catch (RemoteException ex) {
7233             runOnBackgroundThread(() -> executor.execute(
7234                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
7235         }
7236     }
7237 
createThrowableByClassName(String className, String message)7238     private static Throwable createThrowableByClassName(String className, String message) {
7239         if (className == null) {
7240             return null;
7241         }
7242         try {
7243             Class<?> c = Class.forName(className);
7244             return (Throwable) c.getConstructor(String.class).newInstance(message);
7245         } catch (ReflectiveOperationException | ClassCastException e) {
7246         }
7247         return new RuntimeException(className + ": " + message);
7248     }
7249 
7250     /**
7251      * Sets the minimum time in milli-seconds between {@link
7252      * TelephonyCallback.CellInfoListener#onCellInfoChanged(List)} will be invoked.
7253      *<p>
7254      * The default, 0, means invoke onCellInfoChanged when any of the reported
7255      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
7256      * A onCellInfoChanged.
7257      *<p>
7258      * @param rateInMillis the rate
7259      *
7260      * @hide
7261      */
setCellInfoListRate(int rateInMillis, int subId)7262     public void setCellInfoListRate(int rateInMillis, int subId) {
7263         try {
7264             ITelephony telephony = getITelephony();
7265             if (telephony != null)
7266                 telephony.setCellInfoListRate(rateInMillis, subId);
7267         } catch (RemoteException ex) {
7268         } catch (NullPointerException ex) {
7269         }
7270     }
7271 
7272     /**
7273      * Returns the MMS user agent.
7274      *
7275      * @throws UnsupportedOperationException If the device does not have
7276      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
7277      */
7278     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getMmsUserAgent()7279     public String getMmsUserAgent() {
7280         try {
7281             ITelephony telephony = getITelephony();
7282             if (telephony != null) {
7283                 return telephony.getMmsUserAgent(getSubId());
7284             }
7285         } catch (RemoteException ex) {
7286         } catch (NullPointerException ex) {
7287         }
7288         return null;
7289     }
7290 
7291     /**
7292      * Returns the MMS user agent profile URL.
7293      *
7294      * @throws UnsupportedOperationException If the device does not have
7295      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
7296      */
7297     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getMmsUAProfUrl()7298     public String getMmsUAProfUrl() {
7299         try {
7300             ITelephony telephony = getITelephony();
7301             if (telephony != null) {
7302                 return telephony.getMmsUAProfUrl(getSubId());
7303             }
7304         } catch (RemoteException ex) {
7305         } catch (NullPointerException ex) {
7306         }
7307         return null;
7308     }
7309 
7310     /**
7311      * Get the first active portIndex from the corresponding physical slot index.
7312      * @param physicalSlotIndex physical slot index
7313      * @return first active port index or INVALID_PORT_INDEX if no port is active
7314      */
getFirstActivePortIndex(int physicalSlotIndex)7315     private int getFirstActivePortIndex(int physicalSlotIndex) {
7316         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
7317         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length
7318                 && slotInfos[physicalSlotIndex] != null) {
7319             Optional<UiccPortInfo> result =  slotInfos[physicalSlotIndex].getPorts().stream()
7320                     .filter(portInfo -> portInfo.isActive()).findFirst();
7321             if (result.isPresent()) {
7322                 return result.get().getPortIndex();
7323             }
7324         }
7325         return INVALID_PORT_INDEX;
7326     }
7327 
7328     /**
7329      * Opens a logical channel to the ICC card.
7330      *
7331      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7332      *
7333      * <p>Requires Permission:
7334      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7335      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7336      *
7337      * @param AID Application id. See ETSI 102.221 and 101.220.
7338      * @return an IccOpenLogicalChannelResponse object.
7339      *
7340      * @throws UnsupportedOperationException If the device does not have
7341      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7342      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
7343      */
7344     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7345     @Deprecated
iccOpenLogicalChannel(String AID)7346     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
7347         return iccOpenLogicalChannel(getSubId(), AID, -1);
7348     }
7349 
7350     /**
7351      * Opens a logical channel to the ICC card using the physical slot index.
7352      *
7353      * Use this method when no subscriptions are available on the SIM and the operation must be
7354      * performed using the physical slot index.
7355      *
7356      * This operation wraps two APDU instructions:
7357      * <ul>
7358      *     <li>MANAGE CHANNEL to open a logical channel</li>
7359      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7360      * </ul>
7361      *
7362      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7363      * and 0x0C are guaranteed to be supported.
7364      *
7365      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7366      * considered an error and the channel shall not be opened.
7367      *
7368      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7369      *
7370      * <p>Requires Permission:
7371      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7372      *
7373      * @param slotIndex the physical slot index of the ICC card
7374      * @param aid Application id. See ETSI 102.221 and 101.220.
7375      * @param p2 P2 parameter (described in ISO 7816-4).
7376      * @return an IccOpenLogicalChannelResponse object.
7377      * @throws UnsupportedOperationException If the device does not have
7378      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7379      * @hide
7380      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7381      * instead use {@link #iccOpenLogicalChannelByPort(int, int, String, int)}
7382      */
7383     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7384     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7385     @SystemApi
7386     @Nullable
7387     @Deprecated
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)7388     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
7389             @Nullable String aid, int p2) {
7390         try {
7391             ITelephony telephony = getITelephony();
7392             if (telephony != null) {
7393                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7394                 request.slotIndex = slotIndex;
7395                 request.portIndex = getFirstActivePortIndex(slotIndex);
7396                 request.aid = aid;
7397                 request.p2 = p2;
7398                 request.callingPackage = getOpPackageName();
7399                 request.binder = new Binder();
7400                 return telephony.iccOpenLogicalChannel(request);
7401             }
7402         } catch (RemoteException ex) {
7403         } catch (NullPointerException ex) {
7404         }
7405         return null;
7406     }
7407 
7408     /**
7409      * Opens a logical channel to the ICC card using the physical slot index and port index.
7410      *
7411      * Use this method when no subscriptions are available on the SIM and the operation must be
7412      * performed using the physical slot index and port index.
7413      *
7414      * This operation wraps two APDU instructions:
7415      * <ul>
7416      *     <li>MANAGE CHANNEL to open a logical channel</li>
7417      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7418      * </ul>
7419      *
7420      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7421      * and 0x0C are guaranteed to be supported.
7422      *
7423      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7424      * considered an error and the channel shall not be opened.
7425      *
7426      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7427      *
7428      * @param slotIndex the physical slot index of the ICC card
7429      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7430      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7431      * @param aid Application id. See ETSI 102.221 and 101.220.
7432      * @param p2 P2 parameter (described in ISO 7816-4).
7433      * @return an IccOpenLogicalChannelResponse object.
7434      *
7435      * @throws UnsupportedOperationException If the device does not have
7436      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7437      * @hide
7438      */
7439     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7440     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7441     @SystemApi
7442     @NonNull
iccOpenLogicalChannelByPort(int slotIndex, int portIndex, @Nullable String aid, int p2)7443     public IccOpenLogicalChannelResponse iccOpenLogicalChannelByPort(int slotIndex,
7444             int portIndex, @Nullable String aid, int p2) {
7445         try {
7446             ITelephony telephony = getITelephony();
7447             if (telephony != null) {
7448                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7449                 request.slotIndex = slotIndex;
7450                 request.portIndex = portIndex;
7451                 request.aid = aid;
7452                 request.p2 = p2;
7453                 request.callingPackage = getOpPackageName();
7454                 request.binder = new Binder();
7455                 return telephony.iccOpenLogicalChannel(request);
7456             } else {
7457                 throw new IllegalStateException("telephony service is null.");
7458             }
7459         } catch (RemoteException ex) {
7460             throw ex.rethrowAsRuntimeException();
7461         }
7462     }
7463 
7464     /**
7465      * Opens a logical channel to the ICC card.
7466      *
7467      * This operation wraps two APDU instructions:
7468      * <ul>
7469      *     <li>MANAGE CHANNEL to open a logical channel</li>
7470      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7471      * </ul>
7472      *
7473      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7474      * and 0x0C are guaranteed to be supported.
7475      *
7476      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7477      * considered an error and the channel shall not be opened.
7478      *
7479      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7480      *
7481      * It is strongly recommended that callers of this should firstly create a new TelephonyManager
7482      * instance by calling {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so
7483      * can result in unpredictable and detrimental behavior like callers can end up talking to the
7484      * wrong SIM card.
7485      *
7486      * <p>Requires Permission:
7487      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7488      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7489      *
7490      * @param AID Application id. See ETSI 102.221 and 101.220.
7491      * @param p2 P2 parameter (described in ISO 7816-4).
7492      * @return an IccOpenLogicalChannelResponse object.
7493      *
7494      * @throws UnsupportedOperationException If the device does not have
7495      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7496      */
7497     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccOpenLogicalChannel(String AID, int p2)7498     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
7499         return iccOpenLogicalChannel(getSubId(), AID, p2);
7500     }
7501 
7502     /**
7503      * Opens a logical channel to the ICC card.
7504      *
7505      * This operation wraps two APDU instructions:
7506      * <ul>
7507      *     <li>MANAGE CHANNEL to open a logical channel</li>
7508      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7509      * </ul>
7510      *
7511      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7512      * and 0x0C are guaranteed to be supported.
7513      *
7514      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7515      * considered an error and the channel shall not be opened.
7516      *
7517      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7518      *
7519      * <p>Requires Permission:
7520      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7521      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7522      *
7523      * @param subId The subscription to use.
7524      * @param AID Application id. See ETSI 102.221 and 101.220.
7525      * @param p2 P2 parameter (described in ISO 7816-4).
7526      * @return an IccOpenLogicalChannelResponse object.
7527      * @hide
7528      */
iccOpenLogicalChannel(int subId, String AID, int p2)7529     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
7530         try {
7531             ITelephony telephony = getITelephony();
7532             if (telephony != null) {
7533                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7534                 request.subId = subId;
7535                 request.callingPackage = getOpPackageName();
7536                 request.aid = AID;
7537                 request.p2 = p2;
7538                 request.binder = new Binder();
7539                 return telephony.iccOpenLogicalChannel(request);
7540             }
7541         } catch (RemoteException ex) {
7542         } catch (NullPointerException ex) {
7543         }
7544         return null;
7545     }
7546 
7547     /**
7548      * Closes a previously opened logical channel to the ICC card using the physical slot index.
7549      *
7550      * Use this method when no subscriptions are available on the SIM and the operation must be
7551      * performed using the physical slot index.
7552      *
7553      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7554      *
7555      * <p>Requires Permission:
7556      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7557      *
7558      * @param slotIndex the physical slot index of the ICC card
7559      * @param channel is the channel id to be closed as returned by a successful
7560      *            iccOpenLogicalChannel.
7561      * @return true if the channel was closed successfully.
7562      *
7563      * @throws UnsupportedOperationException If the device does not have
7564      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7565      * @hide
7566      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7567      * instead use {@link #iccCloseLogicalChannelByPort(int, int, int)}
7568      */
7569     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7570     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7571     @SystemApi
7572     @Deprecated
iccCloseLogicalChannelBySlot(int slotIndex, int channel)7573     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
7574         try {
7575             ITelephony telephony = getITelephony();
7576             if (telephony != null) {
7577                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7578                 request.slotIndex = slotIndex;
7579                 request.portIndex = getFirstActivePortIndex(slotIndex);
7580                 request.channel = channel;
7581                 return telephony.iccCloseLogicalChannel(request);
7582             }
7583         } catch (RemoteException ex) {
7584         } catch (NullPointerException ex) {
7585         } catch (IllegalStateException ex) {
7586             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7587         }
7588         return false;
7589     }
7590 
7591     /**
7592      * Closes a previously opened logical channel to the ICC card using the physical slot index and
7593      * port index.
7594      *
7595      * Use this method when no subscriptions are available on the SIM and the operation must be
7596      * performed using the physical slot index and port index.
7597      *
7598      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7599      *
7600      * @param slotIndex the physical slot index of the ICC card
7601      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7602      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7603      * @param channel is the channel id to be closed as returned by a successful
7604      *            iccOpenLogicalChannel.
7605      *
7606      * @throws IllegalStateException if the Telephony process is not currently available or modem
7607      *                               currently can't process this command.
7608      * @throws IllegalArgumentException if invalid arguments are passed.
7609      * @throws UnsupportedOperationException If the device does not have
7610      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7611      * @hide
7612      */
7613     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7614     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7615     @SystemApi
iccCloseLogicalChannelByPort(int slotIndex, int portIndex, int channel)7616     public void iccCloseLogicalChannelByPort(int slotIndex, int portIndex, int channel) {
7617         try {
7618             ITelephony telephony = getITelephony();
7619             if (telephony != null) {
7620                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7621                 request.slotIndex = slotIndex;
7622                 request.portIndex = portIndex;
7623                 request.channel = channel;
7624                 telephony.iccCloseLogicalChannel(request);
7625             } else {
7626                 throw new IllegalStateException("telephony service is null.");
7627             }
7628         } catch (RemoteException ex) {
7629             throw ex.rethrowAsRuntimeException();
7630         }
7631     }
7632 
7633     /**
7634      * Closes a previously opened logical channel to the ICC card.
7635      *
7636      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7637      * It is strongly recommended that callers of this API should firstly create
7638      * new TelephonyManager instance by calling
7639      * {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so can result in
7640      * unpredictable and detrimental behavior like callers can end up talking to the wrong SIM card.
7641      *
7642      * <p>Requires Permission:
7643      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7644      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7645      *
7646      * @param channel is the channel id to be closed as returned by a successful
7647      *            iccOpenLogicalChannel.
7648      * @return true if the channel was closed successfully.
7649      * @throws IllegalArgumentException if input parameters are wrong. e.g., invalid channel
7650      * @throws UnsupportedOperationException If the device does not have
7651      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7652      */
7653     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccCloseLogicalChannel(int channel)7654     public boolean iccCloseLogicalChannel(int channel) {
7655         try {
7656             return iccCloseLogicalChannel(getSubId(), channel);
7657         } catch (IllegalStateException ex) {
7658             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7659         }
7660         return false;
7661     }
7662 
7663     /**
7664      * Closes a previously opened logical channel to the ICC card.
7665      *
7666      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7667      *
7668      * <p>Requires Permission:
7669      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7670      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7671      *
7672      * @param subId The subscription to use.
7673      * @param channel is the channel id to be closed as returned by a successful
7674      *            iccOpenLogicalChannel.
7675      * @return true if the channel was closed successfully.
7676      * @hide
7677      */
iccCloseLogicalChannel(int subId, int channel)7678     public boolean iccCloseLogicalChannel(int subId, int channel) {
7679         try {
7680             ITelephony telephony = getITelephony();
7681             if (telephony != null) {
7682                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7683                 request.subId = subId;
7684                 request.channel = channel;
7685                 return telephony.iccCloseLogicalChannel(request);
7686             }
7687         } catch (RemoteException ex) {
7688         } catch (NullPointerException ex) {
7689         } catch (IllegalStateException ex) {
7690             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7691         }
7692         return false;
7693     }
7694 
7695     /**
7696      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
7697      *
7698      * Use this method when no subscriptions are available on the SIM and the operation must be
7699      * performed using the physical slot index.
7700      *
7701      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7702      *
7703      * <p>Requires Permission:
7704      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7705      *
7706      * @param slotIndex the physical slot index of the ICC card
7707      * @param channel is the channel id to be closed as returned by a successful
7708      *            iccOpenLogicalChannel.
7709      * @param cla Class of the APDU command.
7710      * @param instruction Instruction of the APDU command.
7711      * @param p1 P1 value of the APDU command.
7712      * @param p2 P2 value of the APDU command.
7713      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7714      *            is sent to the SIM.
7715      * @param data Data to be sent with the APDU.
7716      * @return The APDU response from the ICC card with the status appended at the end, or null if
7717      * there is an issue connecting to the Telephony service.
7718      * @throws UnsupportedOperationException If the device does not have
7719      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7720      * @hide
7721      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7722      * instead use
7723      * {@link #iccTransmitApduLogicalChannelByPort(int, int, int, int, int, int, int, int, String)}
7724      */
7725     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7726     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7727     @SystemApi
7728     @Nullable
7729     @Deprecated
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7730     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
7731             int instruction, int p1, int p2, int p3, @Nullable String data) {
7732         try {
7733             ITelephony telephony = getITelephony();
7734             if (telephony != null) {
7735                 return telephony.iccTransmitApduLogicalChannelByPort(slotIndex,
7736                         getFirstActivePortIndex(slotIndex), channel, cla, instruction,
7737                         p1, p2, p3, data);
7738             }
7739         } catch (RemoteException ex) {
7740         } catch (NullPointerException ex) {
7741         }
7742         return null;
7743     }
7744 
7745     /**
7746      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
7747      *
7748      * Use this method when no subscriptions are available on the SIM and the operation must be
7749      * performed using the physical slot index.
7750      *
7751      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7752      *
7753      * @param slotIndex the physical slot index of the ICC card
7754      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7755      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7756      * @param channel is the channel id to be closed as returned by a successful
7757      *            iccOpenLogicalChannel.
7758      * @param cla Class of the APDU command.
7759      * @param instruction Instruction of the APDU command.
7760      * @param p1 P1 value of the APDU command.
7761      * @param p2 P2 value of the APDU command.
7762      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7763      *            is sent to the SIM.
7764      * @param data Data to be sent with the APDU.
7765      * @return The APDU response from the ICC card with the status appended at the end, or null if
7766      * there is an issue connecting to the Telephony service.
7767      *
7768      * @throws UnsupportedOperationException If the device does not have
7769      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7770      * @hide
7771      */
7772     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7773     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7774     @SystemApi
7775     @NonNull
iccTransmitApduLogicalChannelByPort(int slotIndex, int portIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7776     public String iccTransmitApduLogicalChannelByPort(int slotIndex, int portIndex, int channel,
7777             int cla, int instruction, int p1, int p2, int p3, @Nullable String data) {
7778         String response;
7779         try {
7780             ITelephony telephony = getITelephony();
7781             if (telephony != null) {
7782                 response = telephony.iccTransmitApduLogicalChannelByPort(slotIndex, portIndex,
7783                         channel, cla, instruction, p1, p2, p3, data);
7784             } else {
7785                 throw new IllegalStateException("telephony service is null.");
7786             }
7787         } catch (RemoteException ex) {
7788             throw ex.rethrowAsRuntimeException();
7789         }
7790         return response;
7791     }
7792 
7793     /**
7794      * Transmit an APDU to the ICC card over a logical channel.
7795      *
7796      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7797      *
7798      * It is strongly recommended that callers of this API should firstly create a new
7799      * TelephonyManager instance by calling
7800      * {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so can result in
7801      * unpredictable and detrimental behavior like callers can end up talking to the wrong SIM card.
7802      *
7803      * <p>Requires Permission:
7804      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7805      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7806      *
7807      * @param channel is the channel id to be closed as returned by a successful
7808      *            iccOpenLogicalChannel.
7809      * @param cla Class of the APDU command.
7810      * @param instruction Instruction of the APDU command.
7811      * @param p1 P1 value of the APDU command.
7812      * @param p2 P2 value of the APDU command.
7813      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7814      *            is sent to the SIM.
7815      * @param data Data to be sent with the APDU.
7816      * @return The APDU response from the ICC card with the status appended at
7817      *            the end.
7818      *
7819      * @throws UnsupportedOperationException If the device does not have
7820      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7821      */
7822     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)7823     public String iccTransmitApduLogicalChannel(int channel, int cla,
7824             int instruction, int p1, int p2, int p3, String data) {
7825         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
7826                     instruction, p1, p2, p3, data);
7827     }
7828 
7829     /**
7830      * Transmit an APDU to the ICC card over a logical channel.
7831      *
7832      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7833      *
7834      * <p>Requires Permission:
7835      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7836      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7837      *
7838      * @param subId The subscription to use.
7839      * @param channel is the channel id to be closed as returned by a successful
7840      *            iccOpenLogicalChannel.
7841      * @param cla Class of the APDU command.
7842      * @param instruction Instruction of the APDU command.
7843      * @param p1 P1 value of the APDU command.
7844      * @param p2 P2 value of the APDU command.
7845      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7846      *            is sent to the SIM.
7847      * @param data Data to be sent with the APDU.
7848      * @return The APDU response from the ICC card with the status appended at
7849      *            the end.
7850      * @hide
7851      */
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)7852     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
7853             int instruction, int p1, int p2, int p3, String data) {
7854         try {
7855             ITelephony telephony = getITelephony();
7856             if (telephony != null)
7857                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
7858                     instruction, p1, p2, p3, data);
7859         } catch (RemoteException ex) {
7860         } catch (NullPointerException ex) {
7861         }
7862         return "";
7863     }
7864 
7865     /**
7866      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
7867      *
7868      * Use this method when no subscriptions are available on the SIM and the operation must be
7869      * performed using the physical slot index.
7870      *
7871      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7872      *
7873      * <p>Requires Permission:
7874      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7875      *
7876      * @param slotIndex the physical slot index of the ICC card to target
7877      * @param cla Class of the APDU command.
7878      * @param instruction Instruction of the APDU command.
7879      * @param p1 P1 value of the APDU command.
7880      * @param p2 P2 value of the APDU command.
7881      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7882      *            is sent to the SIM.
7883      * @param data Data to be sent with the APDU.
7884      * @return The APDU response from the ICC card with the status appended at
7885      *            the end.
7886      *
7887      * @throws UnsupportedOperationException If the device does not have
7888      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7889      * @hide
7890      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7891      * instead use
7892      * {@link #iccTransmitApduBasicChannelByPort(int, int, int, int, int, int, int, String)}
7893      */
7894     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7895     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7896     @SystemApi
7897     @NonNull
7898     @Deprecated
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7899     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
7900             int p2, int p3, @Nullable String data) {
7901         try {
7902             ITelephony telephony = getITelephony();
7903             if (telephony != null) {
7904                 return telephony.iccTransmitApduBasicChannelByPort(slotIndex,
7905                         getFirstActivePortIndex(slotIndex), getOpPackageName(),
7906                         cla, instruction, p1, p2, p3, data);
7907             }
7908         } catch (RemoteException ex) {
7909         } catch (NullPointerException ex) {
7910         }
7911         return null;
7912     }
7913 
7914     /**
7915      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
7916      *
7917      * Use this method when no subscriptions are available on the SIM and the operation must be
7918      * performed using the physical slot index.
7919      *
7920      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7921      *
7922      * @param slotIndex the physical slot index of the ICC card to target
7923      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7924      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7925      * @param cla Class of the APDU command.
7926      * @param instruction Instruction of the APDU command.
7927      * @param p1 P1 value of the APDU command.
7928      * @param p2 P2 value of the APDU command.
7929      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7930      *            is sent to the SIM.
7931      * @param data Data to be sent with the APDU.
7932      * @return The APDU response from the ICC card with the status appended at
7933      *            the end.
7934      *
7935      * @throws UnsupportedOperationException If the device does not have
7936      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7937      * @hide
7938      */
7939     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7940     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7941     @SystemApi
7942     @NonNull
iccTransmitApduBasicChannelByPort(int slotIndex, int portIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7943     public String iccTransmitApduBasicChannelByPort(int slotIndex, int portIndex, int cla,
7944             int instruction, int p1, int p2, int p3, @Nullable String data) {
7945         String response;
7946         try {
7947             ITelephony telephony = getITelephony();
7948             if (telephony != null) {
7949                 response = telephony.iccTransmitApduBasicChannelByPort(slotIndex, portIndex,
7950                         getOpPackageName(), cla, instruction, p1, p2, p3, data);
7951             } else {
7952                 throw new IllegalStateException("telephony service is null.");
7953             }
7954         } catch (RemoteException ex) {
7955             throw ex.rethrowAsRuntimeException();
7956         }
7957         return response;
7958     }
7959     /**
7960      * Transmit an APDU to the ICC card over the basic channel.
7961      *
7962      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7963      *
7964      * <p>Requires Permission:
7965      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7966      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7967      *
7968      * @param cla Class of the APDU command.
7969      * @param instruction Instruction of the APDU command.
7970      * @param p1 P1 value of the APDU command.
7971      * @param p2 P2 value of the APDU command.
7972      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7973      *            is sent to the SIM.
7974      * @param data Data to be sent with the APDU.
7975      * @return The APDU response from the ICC card with the status appended at
7976      *            the end.
7977      *
7978      * @throws UnsupportedOperationException If the device does not have
7979      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7980      */
7981     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)7982     public String iccTransmitApduBasicChannel(int cla,
7983             int instruction, int p1, int p2, int p3, String data) {
7984         return iccTransmitApduBasicChannel(getSubId(), cla,
7985                     instruction, p1, p2, p3, data);
7986     }
7987 
7988     /**
7989      * Transmit an APDU to the ICC card over the basic channel.
7990      *
7991      * Input parameters equivalent to TS 27.007 AT+CSIM command.
7992      *
7993      * <p>Requires Permission:
7994      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7995      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7996      *
7997      * @param subId The subscription to use.
7998      * @param cla Class of the APDU command.
7999      * @param instruction Instruction of the APDU command.
8000      * @param p1 P1 value of the APDU command.
8001      * @param p2 P2 value of the APDU command.
8002      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
8003      *            is sent to the SIM.
8004      * @param data Data to be sent with the APDU.
8005      * @return The APDU response from the ICC card with the status appended at
8006      *            the end.
8007      * @hide
8008      */
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)8009     public String iccTransmitApduBasicChannel(int subId, int cla,
8010             int instruction, int p1, int p2, int p3, String data) {
8011         try {
8012             ITelephony telephony = getITelephony();
8013             if (telephony != null)
8014                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
8015                     instruction, p1, p2, p3, data);
8016         } catch (RemoteException ex) {
8017         } catch (NullPointerException ex) {
8018         }
8019         return "";
8020     }
8021 
8022     /**
8023      * Returns the response APDU for a command APDU sent through SIM_IO.
8024      *
8025      * <p>Requires Permission:
8026      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8027      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8028      *
8029      * @param fileID
8030      * @param command
8031      * @param p1 P1 value of the APDU command.
8032      * @param p2 P2 value of the APDU command.
8033      * @param p3 P3 value of the APDU command.
8034      * @param filePath
8035      * @return The APDU response.
8036      *
8037      * @throws UnsupportedOperationException If the device does not have
8038      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8039      */
8040     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)8041     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
8042             String filePath) {
8043         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
8044     }
8045 
8046     /**
8047      * Returns the response APDU for a command APDU sent through SIM_IO.
8048      *
8049      * <p>Requires Permission:
8050      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8051      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8052      *
8053      * @param subId The subscription to use.
8054      * @param fileID
8055      * @param command
8056      * @param p1 P1 value of the APDU command.
8057      * @param p2 P2 value of the APDU command.
8058      * @param p3 P3 value of the APDU command.
8059      * @param filePath
8060      * @return The APDU response.
8061      * @hide
8062      */
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)8063     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
8064             int p3, String filePath) {
8065         try {
8066             ITelephony telephony = getITelephony();
8067             if (telephony != null)
8068                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
8069         } catch (RemoteException ex) {
8070         } catch (NullPointerException ex) {
8071         }
8072         return null;
8073     }
8074 
8075     /**
8076      * Send ENVELOPE to the SIM and return the response.
8077      *
8078      * <p>Requires Permission:
8079      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8080      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8081      *
8082      * @param content String containing SAT/USAT response in hexadecimal
8083      *                format starting with command tag. See TS 102 223 for
8084      *                details.
8085      * @return The APDU response from the ICC card in hexadecimal format
8086      *         with the last 4 bytes being the status word. If the command fails,
8087      *         returns an empty string.
8088      *
8089      * @throws UnsupportedOperationException If the device does not have
8090      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8091      */
8092     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
sendEnvelopeWithStatus(String content)8093     public String sendEnvelopeWithStatus(String content) {
8094         return sendEnvelopeWithStatus(getSubId(), content);
8095     }
8096 
8097     /**
8098      * Send ENVELOPE to the SIM and return the response.
8099      *
8100      * <p>Requires Permission:
8101      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8102      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8103      *
8104      * @param subId The subscription to use.
8105      * @param content String containing SAT/USAT response in hexadecimal
8106      *                format starting with command tag. See TS 102 223 for
8107      *                details.
8108      * @return The APDU response from the ICC card in hexadecimal format
8109      *         with the last 4 bytes being the status word. If the command fails,
8110      *         returns an empty string.
8111      * @hide
8112      */
sendEnvelopeWithStatus(int subId, String content)8113     public String sendEnvelopeWithStatus(int subId, String content) {
8114         try {
8115             ITelephony telephony = getITelephony();
8116             if (telephony != null)
8117                 return telephony.sendEnvelopeWithStatus(subId, content);
8118         } catch (RemoteException ex) {
8119         } catch (NullPointerException ex) {
8120         }
8121         return "";
8122     }
8123 
8124     /**
8125      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
8126      * Used for device configuration by some CDMA operators.
8127      *
8128      * <p>Requires Permission:
8129      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8130      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8131      *
8132      * @param itemID the ID of the item to read.
8133      * @return the NV item as a String, or null on any failure.
8134      *
8135      * @hide
8136      */
8137     @UnsupportedAppUsage
nvReadItem(int itemID)8138     public String nvReadItem(int itemID) {
8139         try {
8140             ITelephony telephony = getITelephony();
8141             if (telephony != null)
8142                 return telephony.nvReadItem(itemID);
8143         } catch (RemoteException ex) {
8144             Rlog.e(TAG, "nvReadItem RemoteException", ex);
8145         } catch (NullPointerException ex) {
8146             Rlog.e(TAG, "nvReadItem NPE", ex);
8147         }
8148         return "";
8149     }
8150 
8151     /**
8152      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
8153      * Used for device configuration by some CDMA operators.
8154      *
8155      * <p>Requires Permission:
8156      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8157      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8158      *
8159      * @param itemID the ID of the item to read.
8160      * @param itemValue the value to write, as a String.
8161      * @return true on success; false on any failure.
8162      *
8163      * @hide
8164      */
nvWriteItem(int itemID, String itemValue)8165     public boolean nvWriteItem(int itemID, String itemValue) {
8166         try {
8167             ITelephony telephony = getITelephony();
8168             if (telephony != null)
8169                 return telephony.nvWriteItem(itemID, itemValue);
8170         } catch (RemoteException ex) {
8171             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
8172         } catch (NullPointerException ex) {
8173             Rlog.e(TAG, "nvWriteItem NPE", ex);
8174         }
8175         return false;
8176     }
8177 
8178     /**
8179      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
8180      * Used for device configuration by some CDMA operators.
8181      *
8182      * <p>Requires Permission:
8183      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8184      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8185      *
8186      * @param preferredRoamingList byte array containing the new PRL.
8187      * @return true on success; false on any failure.
8188      *
8189      * @hide
8190      */
nvWriteCdmaPrl(byte[] preferredRoamingList)8191     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
8192         try {
8193             ITelephony telephony = getITelephony();
8194             if (telephony != null)
8195                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
8196         } catch (RemoteException ex) {
8197             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
8198         } catch (NullPointerException ex) {
8199             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
8200         }
8201         return false;
8202     }
8203 
8204     /**
8205      * Perform the specified type of NV config reset. The radio will be taken offline
8206      * and the device must be rebooted after the operation. Used for device
8207      * configuration by some CDMA operators.
8208      *
8209      * <p>Requires Permission:
8210      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8211      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8212      *
8213      * TODO: remove this one. use {@link #rebootModem()} for reset type 1 and
8214      * {@link #resetRadioConfig()} for reset type 3 (b/116476729)
8215      *
8216      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
8217      * @return true on success; false on any failure.
8218      *
8219      * @hide
8220      */
8221     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
nvResetConfig(int resetType)8222     public boolean nvResetConfig(int resetType) {
8223         try {
8224             ITelephony telephony = getITelephony();
8225             if (telephony != null) {
8226                 if (resetType == 1 /*1: reload NV reset */) {
8227                     return telephony.rebootModem(getSlotIndex());
8228                 } else if (resetType == 3 /*3: factory NV reset */) {
8229                     return telephony.resetModemConfig(getSlotIndex());
8230                 } else {
8231                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
8232                 }
8233             }
8234         } catch (RemoteException ex) {
8235             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
8236         } catch (NullPointerException ex) {
8237             Rlog.e(TAG, "nvResetConfig NPE", ex);
8238         }
8239         return false;
8240     }
8241 
8242     /**
8243      * Rollback modem configurations to factory default except some config which are in allowlist.
8244      * Used for device configuration by some carriers.
8245      *
8246      * <p>Requires Permission:
8247      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8248      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8249      *
8250      * @return {@code true} on success; {@code false} on any failure.
8251      *
8252      * @throws UnsupportedOperationException If the device does not have
8253      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
8254      * @hide
8255      */
8256     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8257     @SystemApi
8258     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
resetRadioConfig()8259     public boolean resetRadioConfig() {
8260         try {
8261             ITelephony telephony = getITelephony();
8262             if (telephony != null) {
8263                 return telephony.resetModemConfig(getSlotIndex());
8264             }
8265         } catch (RemoteException ex) {
8266             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
8267         } catch (NullPointerException ex) {
8268             Rlog.e(TAG, "resetRadioConfig NPE", ex);
8269         }
8270         return false;
8271     }
8272 
8273     /**
8274      * Generate a radio modem reset. Used for device configuration by some carriers.
8275      *
8276      * <p>Requires Permission:
8277      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8278      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8279      *
8280      * @return {@code true} on success; {@code false} on any failure.
8281      *
8282      * @deprecated  Using {@link #rebootModem()} instead.
8283      *
8284      * @throws UnsupportedOperationException If the device does not have
8285      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
8286      * @hide
8287      */
8288     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8289     @SystemApi
8290     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
rebootRadio()8291     public boolean rebootRadio() {
8292         try {
8293             ITelephony telephony = getITelephony();
8294             if (telephony != null) {
8295                 return telephony.rebootModem(getSlotIndex());
8296             }
8297         } catch (RemoteException ex) {
8298             Rlog.e(TAG, "rebootRadio RemoteException", ex);
8299         } catch (NullPointerException ex) {
8300             Rlog.e(TAG, "rebootRadio NPE", ex);
8301         }
8302         return false;
8303     }
8304 
8305     /**
8306      * Generate a radio modem reset. Used for device configuration by some carriers.
8307      *
8308      * <p>Requires Permission:
8309      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8310      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8311      * @throws IllegalStateException if the Telephony process is not currently available.
8312      * @throws RuntimeException
8313      * @throws UnsupportedOperationException If the device does not have
8314      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
8315      */
8316     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8317     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
rebootModem()8318     public void rebootModem() {
8319         try {
8320             ITelephony telephony = getITelephony();
8321             if (telephony == null) {
8322                 throw new IllegalStateException("telephony service is null.");
8323             }
8324             telephony.rebootModem(getSlotIndex());
8325         } catch (RemoteException ex) {
8326             Rlog.e(TAG, "rebootRadio RemoteException", ex);
8327             throw ex.rethrowAsRuntimeException();
8328         }
8329     }
8330 
8331     /**
8332      * Return an appropriate subscription ID for any situation.
8333      *
8334      * If this object has been created with {@link #createForSubscriptionId}, then the provided
8335      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
8336      *
8337      */
8338     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriptionId()8339     public int getSubscriptionId() {
8340         return getSubId();
8341     }
8342 
8343     /**
8344      * Return an appropriate subscription ID for any situation.
8345      *
8346      * If this object has been created with {@link #createForSubscriptionId}, then the provided
8347      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
8348      *
8349      */
getSubId()8350     private int getSubId() {
8351       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
8352         return mSubId;
8353       }
8354       return SubscriptionManager.getDefaultSubscriptionId();
8355     }
8356 
8357     /**
8358      * Return an appropriate subscription ID for any situation.
8359      *
8360      * If this object has been created with {@link #createForSubscriptionId}, then the provided
8361      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
8362      * returned.
8363      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
8364      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
8365      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
8366      */
8367     @UnsupportedAppUsage
getSubId(int preferredSubId)8368     private int getSubId(int preferredSubId) {
8369         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
8370             return mSubId;
8371         }
8372         return preferredSubId;
8373     }
8374 
8375     /**
8376      * Return an appropriate phone ID for any situation.
8377      *
8378      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
8379      * associated with the provided subId is returned. Otherwise, the default phoneId associated
8380      * with the default subId will be returned.
8381      */
getPhoneId()8382     private int getPhoneId() {
8383         return SubscriptionManager.getPhoneId(getSubId());
8384     }
8385 
8386     /**
8387      * Return an appropriate phone ID for any situation.
8388      *
8389      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
8390      * associated with the provided subId is returned. Otherwise, return the phoneId associated
8391      * with the preferred subId based on caller's context.
8392      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
8393      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
8394      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
8395      */
8396     @UnsupportedAppUsage
getPhoneId(int preferredSubId)8397     private int getPhoneId(int preferredSubId) {
8398         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
8399     }
8400 
8401     /**
8402      * Return an appropriate slot index for any situation.
8403      *
8404      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
8405      * associated with the provided subId is returned. Otherwise, return the slot index associated
8406      * with the default subId.
8407      * If SIM is not inserted, return default SIM slot index.
8408      *
8409      * {@hide}
8410      */
8411     @VisibleForTesting
8412     @UnsupportedAppUsage
getSlotIndex()8413     public int getSlotIndex() {
8414         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
8415         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
8416             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
8417         }
8418         return slotIndex;
8419     }
8420 
8421     /**
8422      * Request that the next incoming call from a number matching {@code range} be intercepted.
8423      *
8424      * This API is intended for OEMs to provide a service for apps to verify the device's phone
8425      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
8426      * intercept the next incoming call from a number that lies within the range, within a timeout
8427      * specified by {@code timeoutMillis}.
8428      *
8429      * If such a phone call is received, the caller will be notified via
8430      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
8431      * If verification fails for any reason, the caller will be notified via
8432      * {@link NumberVerificationCallback#onVerificationFailed(int)}
8433      * on the provided {@link Executor}.
8434      *
8435      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
8436      * API must also be listed in the device configuration as an authorized app in
8437      * {@code packages/services/Telephony/res/values/config.xml} under the
8438      * {@code platform_number_verification_package} key.
8439      *
8440      * @hide
8441      * @param range The range of phone numbers the caller expects a phone call from.
8442      * @param timeoutMillis The amount of time to wait for such a call, or the value of
8443      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
8444      * @param executor The {@link Executor} that callbacks should be executed on.
8445      * @param callback The callback to use for delivering results.
8446      *
8447      * @throws UnsupportedOperationException If the device does not have
8448      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
8449      */
8450     @SystemApi
8451     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8452     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)8453     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
8454             @NonNull @CallbackExecutor Executor executor,
8455             @NonNull NumberVerificationCallback callback) {
8456         if (executor == null) {
8457             throw new NullPointerException("Executor must be non-null");
8458         }
8459         if (callback == null) {
8460             throw new NullPointerException("Callback must be non-null");
8461         }
8462 
8463         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
8464             @Override
8465             public void onCallReceived(String phoneNumber) {
8466                 final long identity = Binder.clearCallingIdentity();
8467                 try {
8468                     executor.execute(() ->
8469                             callback.onCallReceived(phoneNumber));
8470                 } finally {
8471                     Binder.restoreCallingIdentity(identity);
8472                 }
8473             }
8474 
8475             @Override
8476             public void onVerificationFailed(int reason) {
8477                 final long identity = Binder.clearCallingIdentity();
8478                 try {
8479                     executor.execute(() ->
8480                             callback.onVerificationFailed(reason));
8481                 } finally {
8482                     Binder.restoreCallingIdentity(identity);
8483                 }
8484             }
8485         };
8486 
8487         try {
8488             ITelephony telephony = getITelephony();
8489             if (telephony == null) {
8490                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
8491                     throw new IllegalStateException("Telephony is null");
8492                 } else {
8493                     return;
8494                 }
8495             }
8496 
8497             telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
8498                     getOpPackageName());
8499         } catch (RemoteException ex) {
8500             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
8501             runOnBackgroundThread(() -> executor.execute(
8502                     () -> callback.onVerificationFailed(
8503                             NumberVerificationCallback.REASON_UNSPECIFIED)));
8504         }
8505     }
8506 
8507     /**
8508      * Inserts or updates a list property. Expands the list if its length is not enough.
8509      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)8510     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
8511         List<T> ret = new ArrayList<>(prop);
8512         while (ret.size() <= phoneId) ret.add(null);
8513         ret.set(phoneId, value);
8514         return ret;
8515     }
8516     /**
8517      * Convenience function for retrieving a value from the secure settings
8518      * value list as an integer.  Note that internally setting values are
8519      * always stored as strings; this function converts the string to an
8520      * integer for you.
8521      * <p>
8522      * This version does not take a default value.  If the setting has not
8523      * been set, or the string value is not a number,
8524      * it throws {@link SettingNotFoundException}.
8525      *
8526      * @param cr The ContentResolver to access.
8527      * @param name The name of the setting to retrieve.
8528      * @param index The index of the list
8529      *
8530      * @throws SettingNotFoundException Thrown if a setting by the given
8531      * name can't be found or the setting value is not an integer.
8532      *
8533      * @return The value at the given index of settings.
8534      * @hide
8535      */
8536     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getIntAtIndex(android.content.ContentResolver cr, String name, int index)8537     public static int getIntAtIndex(android.content.ContentResolver cr,
8538             String name, int index)
8539             throws android.provider.Settings.SettingNotFoundException {
8540         String v = android.provider.Settings.Global.getString(cr, name);
8541         if (v != null) {
8542             String valArray[] = v.split(",");
8543             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
8544                 try {
8545                     return Integer.parseInt(valArray[index]);
8546                 } catch (NumberFormatException e) {
8547                     //Log.e(TAG, "Exception while parsing Integer: ", e);
8548                 }
8549             }
8550         }
8551         throw new android.provider.Settings.SettingNotFoundException(name);
8552     }
8553 
8554     /**
8555      * Convenience function for updating settings value as coma separated
8556      * integer values. This will either create a new entry in the table if the
8557      * given name does not exist, or modify the value of the existing row
8558      * with that name.  Note that internally setting values are always
8559      * stored as strings, so this function converts the given value to a
8560      * string before storing it.
8561      *
8562      * @param cr The ContentResolver to access.
8563      * @param name The name of the setting to modify.
8564      * @param index The index of the list
8565      * @param value The new value for the setting to be added to the list.
8566      * @return true if the value was set, false on database errors
8567      * @hide
8568      */
8569     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)8570     public static boolean putIntAtIndex(android.content.ContentResolver cr,
8571             String name, int index, int value) {
8572         String data = "";
8573         String valArray[] = null;
8574         String v = android.provider.Settings.Global.getString(cr, name);
8575 
8576         if (index == Integer.MAX_VALUE) {
8577             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
8578         }
8579         if (index < 0) {
8580             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
8581         }
8582         if (v != null) {
8583             valArray = v.split(",");
8584         }
8585 
8586         // Copy the elements from valArray till index
8587         for (int i = 0; i < index; i++) {
8588             String str = "";
8589             if ((valArray != null) && (i < valArray.length)) {
8590                 str = valArray[i];
8591             }
8592             data = data + str + ",";
8593         }
8594 
8595         data = data + value;
8596 
8597         // Copy the remaining elements from valArray if any.
8598         if (valArray != null) {
8599             for (int i = index+1; i < valArray.length; i++) {
8600                 data = data + "," + valArray[i];
8601             }
8602         }
8603         return android.provider.Settings.Global.putString(cr, name, data);
8604     }
8605 
8606     /**
8607      * Gets a per-phone telephony property from a property name.
8608      *
8609      * @hide
8610      */
8611     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)8612     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
8613         String propVal = null;
8614         String prop = SystemProperties.get(property);
8615         if ((prop != null) && (prop.length() > 0)) {
8616             String values[] = prop.split(",");
8617             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
8618                 propVal = values[phoneId];
8619             }
8620         }
8621         return propVal == null ? defaultVal : propVal;
8622     }
8623 
8624     /**
8625      * Gets a typed per-phone telephony property from a schematized list property.
8626      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)8627     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
8628         T ret = null;
8629         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
8630         return ret != null ? ret : defaultValue;
8631     }
8632 
8633     /**
8634      * Gets a global telephony property.
8635      *
8636      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
8637      * per-phone.
8638      *
8639      * @hide
8640      */
8641     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getTelephonyProperty(String property, String defaultVal)8642     public static String getTelephonyProperty(String property, String defaultVal) {
8643         String propVal = SystemProperties.get(property);
8644         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
8645     }
8646 
8647     /** @hide */
8648     @UnsupportedAppUsage
getSimCount()8649     public int getSimCount() {
8650         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
8651         // and then this method shouldn't be used at all!
8652         return getPhoneCount();
8653     }
8654 
8655     /**
8656      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
8657      *
8658      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
8659      *
8660      * @return IMS Service Table or null if not present or not loaded
8661      *
8662      * @throws UnsupportedOperationException If the device does not have
8663      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8664      * @hide
8665      */
8666     @Nullable
8667     @SystemApi
8668     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8669     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIsimIst()8670     public String getIsimIst() {
8671         try {
8672             IPhoneSubInfo info = getSubscriberInfoService();
8673             if (info == null)
8674                 return null;
8675             //get the Isim Ist based on subId
8676             return info.getIsimIst(getSubId());
8677         } catch (RemoteException ex) {
8678             return null;
8679         } catch (NullPointerException ex) {
8680             // This could happen before phone restarts due to crashing
8681             return null;
8682         }
8683     }
8684 
8685     /**
8686      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
8687      * @return an array of PCSCF strings with one PCSCF per string, or null if
8688      *         not present or not loaded
8689      * @hide
8690      */
8691     @UnsupportedAppUsage
getIsimPcscf()8692     public String[] getIsimPcscf() {
8693         try {
8694             IPhoneSubInfo info = getSubscriberInfoService();
8695             if (info == null)
8696                 return null;
8697             //get the Isim Pcscf based on subId
8698             return info.getIsimPcscf(getSubId());
8699         } catch (RemoteException ex) {
8700             return null;
8701         } catch (NullPointerException ex) {
8702             // This could happen before phone restarts due to crashing
8703             return null;
8704         }
8705     }
8706 
8707     /** UICC application type is unknown or not specified */
8708     public static final int APPTYPE_UNKNOWN = PhoneConstants.APPTYPE_UNKNOWN;
8709     /** UICC application type is SIM */
8710     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
8711     /** UICC application type is USIM */
8712     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
8713     /** UICC application type is RUIM */
8714     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
8715     /** UICC application type is CSIM */
8716     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
8717     /** UICC application type is ISIM */
8718     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
8719 
8720     // authContext (parameter P2) when doing UICC challenge,
8721     // per 3GPP TS 31.102 (Section 7.1.2)
8722     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
8723     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
8724     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
8725     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
8726     /**
8727      * Authentication type for GBA Bootstrap Challenge.
8728      * Pass this authentication type into the {@link #getIccAuthentication} API to perform a GBA
8729      * Bootstrap challenge (BSF), with {@code data} (generated according to the procedure defined in
8730      * 3GPP 33.220 Section 5.3.2 step.4) in base64 encoding.
8731      * This method will return the Bootstrapping response in base64 encoding when ICC authentication
8732      * is completed.
8733      * Ref 3GPP 33.220 Section 5.3.2.
8734      */
8735     public static final int AUTHTYPE_GBA_BOOTSTRAP = PhoneConstants.AUTH_CONTEXT_GBA_BOOTSTRAP;
8736     /**
8737      * Authentication type for GBA Network Application Functions (NAF) key External Challenge.
8738      * Pass this authentication type into the {@link #getIccAuthentication} API to perform a GBA
8739      * Network Applications Functions (NAF) key External challenge using the NAF_ID parameter
8740      * as the {@code data} in base64 encoding.
8741      * This method will return the Ks_Ext_Naf key in base64 encoding when ICC authentication
8742      * is completed.
8743      * Ref 3GPP 33.220 Section 5.3.2.
8744      */
8745     public static final int AUTHTYPE_GBA_NAF_KEY_EXTERNAL =
8746             PhoneConstants.AUTHTYPE_GBA_NAF_KEY_EXTERNAL;
8747 
8748     /** @hide */
8749     @Retention(RetentionPolicy.SOURCE)
8750     @IntDef({
8751             AUTHTYPE_EAP_SIM,
8752             AUTHTYPE_EAP_AKA,
8753             AUTHTYPE_GBA_BOOTSTRAP,
8754             AUTHTYPE_GBA_NAF_KEY_EXTERNAL
8755     })
8756     public @interface AuthType {}
8757 
8758     /**
8759      * Returns the response of authentication for the default subscription.
8760      * Returns null if the authentication hasn't been successful
8761      *
8762      * <p>Requires one of the following permissions:
8763      * <ul>
8764      *     <li>READ_PRIVILEGED_PHONE_STATE
8765      *     <li>the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8766      *     <li>the calling app has been granted the
8767      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
8768      * </ul>
8769      *
8770      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8771      * @param authType the authentication type, any one of {@link #AUTHTYPE_EAP_AKA} or
8772      * {@link #AUTHTYPE_EAP_SIM} or {@link #AUTHTYPE_GBA_BOOTSTRAP} or
8773      * {@link #AUTHTYPE_GBA_NAF_KEY_EXTERNAL}
8774      * @param data authentication challenge data, base64 encoded.
8775      * See 3GPP TS 31.102 7.1.2 for more details.
8776      * @return the response of authentication. This value will be null in the following cases:
8777      *   Authentication error, incorrect MAC
8778      *   Authentication error, security context not supported
8779      *   Key freshness failure
8780      *   Authentication error, no memory space available
8781      *   Authentication error, no memory space available in EFMUK
8782      *
8783      * @throws UnsupportedOperationException If the device does not have
8784      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8785      */
8786     // TODO(b/73660190): This should probably require MODIFY_PHONE_STATE, not
8787     // READ_PRIVILEGED_PHONE_STATE. It certainly shouldn't reference the permission in Javadoc since
8788     // it's not public API.
8789     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIccAuthentication(int appType,@AuthType int authType, String data)8790     public String getIccAuthentication(int appType,@AuthType int authType, String data) {
8791         return getIccAuthentication(getSubId(), appType, authType, data);
8792     }
8793 
8794     /**
8795      * Returns the response of USIM Authentication for specified subId.
8796      * Returns null if the authentication hasn't been successful
8797      *
8798      * <p>See {@link #getIccAuthentication(int, int, String)} for details on the required
8799      * permissions.
8800      *
8801      * @param subId subscription ID used for authentication
8802      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8803      * @param authType the authentication type, any one of {@link #AUTHTYPE_EAP_AKA} or
8804      * {@link #AUTHTYPE_EAP_SIM} or {@link #AUTHTYPE_GBA_BOOTSTRAP} or
8805      * {@link #AUTHTYPE_GBA_NAF_KEY_EXTERNAL}
8806      * @param data authentication challenge data, base64 encoded.
8807      * See 3GPP TS 31.102 7.1.2 for more details.
8808      * @return the response of authentication. This value will be null in the following cases only
8809      * (see 3GPP TS 31.102 7.3.1):
8810      *   Authentication error, incorrect MAC
8811      *   Authentication error, security context not supported
8812      *   Key freshness failure
8813      *   Authentication error, no memory space available
8814      *   Authentication error, no memory space available in EFMUK
8815      * @hide
8816      */
8817     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType,@AuthType int authType, String data)8818     public String getIccAuthentication(int subId, int appType,@AuthType int authType, String data) {
8819         try {
8820             IPhoneSubInfo info = getSubscriberInfoService();
8821             if (info == null)
8822                 return null;
8823             return info.getIccSimChallengeResponse(subId, appType, authType, data,
8824                     getOpPackageName(), getAttributionTag());
8825         } catch (RemoteException ex) {
8826             return null;
8827         } catch (NullPointerException ex) {
8828             // This could happen before phone starts
8829             return null;
8830         }
8831     }
8832 
8833     /**
8834      * Returns an array of Forbidden PLMNs from the USIM App
8835      * Returns null if the query fails.
8836      *
8837      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
8838      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8839      *
8840      * @return an array of forbidden PLMNs or null if not available
8841      *
8842      * @throws UnsupportedOperationException If the device does not have
8843      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8844      */
8845     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8846     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
8847     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getForbiddenPlmns()8848     public String[] getForbiddenPlmns() {
8849       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
8850     }
8851 
8852     /**
8853      * Returns an array of Forbidden PLMNs from the specified SIM App
8854      * Returns null if the query fails.
8855      *
8856      * @param subId subscription ID used for authentication
8857      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8858      * @return fplmns an array of forbidden PLMNs
8859      * @hide
8860      */
8861     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)8862     public String[] getForbiddenPlmns(int subId, int appType) {
8863         try {
8864             ITelephony telephony = getITelephony();
8865             if (telephony == null)
8866                 return null;
8867             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
8868                     getAttributionTag());
8869         } catch (RemoteException ex) {
8870             return null;
8871         } catch (NullPointerException ex) {
8872             // This could happen before phone starts
8873             return null;
8874         }
8875     }
8876 
8877     /**
8878      * Replace the contents of the forbidden PLMN SIM file with the provided values.
8879      * Passing an empty list will clear the contents of the EFfplmn file.
8880      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
8881      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
8882      * If the list is longer than the size of EFfplmn, then the file will be written from the
8883      * beginning of the list up to the file size.
8884      *
8885      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
8886      * MODIFY_PHONE_STATE}
8887      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8888      *
8889      * @param fplmns a list of PLMNs to be forbidden.
8890      *
8891      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
8892      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
8893      * room for all of the values passed in. Return -1 in the event of an unexpected failure
8894      *
8895      * @throws UnsupportedOperationException If the device does not have
8896      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8897      */
8898     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8899     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8900     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setForbiddenPlmns(@onNull List<String> fplmns)8901     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
8902         try {
8903             ITelephony telephony = getITelephony();
8904             if (telephony == null) return -1;
8905             return telephony.setForbiddenPlmns(
8906                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
8907         } catch (RemoteException ex) {
8908             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
8909         } catch (NullPointerException ex) {
8910             // This could happen before phone starts
8911             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
8912         }
8913         return -1;
8914     }
8915 
8916     /**
8917      * Fetches the sim service table from the EFUST/EFIST based on the application type
8918      * {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}. The return value is hexaString format
8919      * representing X bytes (x >= 1). Each bit of every byte indicates which optional services
8920      * are available for the given application type.
8921      * The USIM service table EF is described in as per Section 4.2.8 of 3GPP TS 31.102.
8922      * The ISIM service table EF is described in as per Section 4.2.7 of 3GPP TS 31.103.
8923      * The list of services mapped to the exact nth byte of response as mentioned in Section 4.2
8924      * .7 of 3GPP TS 31.103. Eg. Service n°1: Local Phone Book, Service n°2: Fixed Dialling
8925      * Numbers (FDN) - Bit 1 and 2 of the 1st Byte represent service Local Phone Book and Fixed
8926      * Dialling Numbers (FDN)respectively. The coding format for each service type  should be
8927      * interpreted as bit = 1: service available;bit = 0:service not available.
8928      *
8929      * @param appType of type int of either {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}.
8930      * @return HexString represents sim service table else null.
8931      * @throws SecurityException if the caller does not have the required permission/privileges
8932      * @throws UnsupportedOperationException If the device does not have
8933      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8934      * @hide
8935      */
8936 
8937     @Nullable
8938     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8939     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimServiceTable(int appType)8940     public String getSimServiceTable(int appType) {
8941         try {
8942             IPhoneSubInfo info = getSubscriberInfoService();
8943             if (info == null) {
8944                 Rlog.e(TAG, "getSimServiceTable(): IPhoneSubInfo is null");
8945                 return null;
8946             }
8947             //Fetches the sim service table based on subId and appType
8948             if (appType == APPTYPE_ISIM) {
8949                 return info.getIsimIst(getSubId());
8950             } else if ((appType == APPTYPE_USIM)) {
8951                 return info.getSimServiceTable(getSubId(), APPTYPE_USIM);
8952             } else {
8953                 return null;
8954             }
8955         } catch (RemoteException ex) {
8956             Rlog.e(TAG, "getSimServiceTable(): RemoteException=" + ex.getMessage());
8957         } catch (NullPointerException ex) {
8958             Rlog.e(TAG, "getSimServiceTable(): NullPointerException=" + ex.getMessage());
8959         }
8960         return null;
8961     }
8962 
8963     /**
8964      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
8965      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
8966      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
8967      * state.
8968      *
8969      * @param slotIndex the sim slot to reset the IMS stack on.
8970      *
8971      * @throws UnsupportedOperationException If the device does not have
8972      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
8973      * @hide */
8974     @SystemApi
8975     @WorkerThread
8976     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8977     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
resetIms(int slotIndex)8978     public void resetIms(int slotIndex) {
8979         try {
8980             ITelephony telephony = getITelephony();
8981             if (telephony != null) {
8982                 telephony.resetIms(slotIndex);
8983             }
8984         } catch (RemoteException e) {
8985             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
8986                     + e.getMessage());
8987         }
8988     }
8989 
8990     /**
8991      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
8992      * status updates, if not already enabled.
8993      * @hide
8994      */
enableIms(int slotId)8995     public void enableIms(int slotId) {
8996         try {
8997             ITelephony telephony = getITelephony();
8998             if (telephony != null) {
8999                 telephony.enableIms(slotId);
9000             }
9001         } catch (RemoteException e) {
9002             Rlog.e(TAG, "enableIms, RemoteException: "
9003                     + e.getMessage());
9004         }
9005     }
9006 
9007     /**
9008      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
9009      * status updates to disabled.
9010      * @hide
9011      */
disableIms(int slotId)9012     public void disableIms(int slotId) {
9013         try {
9014             ITelephony telephony = getITelephony();
9015             if (telephony != null) {
9016                 telephony.disableIms(slotId);
9017             }
9018         } catch (RemoteException e) {
9019             Rlog.e(TAG, "disableIms, RemoteException: "
9020                     + e.getMessage());
9021         }
9022     }
9023 
9024     /**
9025      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
9026      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
9027      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
9028      * Corresponds to features defined in ImsFeature.
9029      * @hide
9030      */
9031     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsRegistration(int slotIndex, int feature)9032     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
9033         try {
9034             ITelephony telephony = getITelephony();
9035             if (telephony != null) {
9036                 return telephony.getImsRegistration(slotIndex, feature);
9037             }
9038         } catch (RemoteException e) {
9039             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
9040         }
9041         return null;
9042     }
9043 
9044     /**
9045      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
9046      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
9047      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
9048      * Corresponds to features defined in ImsFeature.
9049      * @hide
9050      */
9051     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsConfig(int slotIndex, int feature)9052     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
9053         try {
9054             ITelephony telephony = getITelephony();
9055             if (telephony != null) {
9056                 return telephony.getImsConfig(slotIndex, feature);
9057             }
9058         } catch (RemoteException e) {
9059             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
9060         }
9061         return null;
9062     }
9063 
9064     /**
9065      * Set IMS registration state on all active subscriptions.
9066      * <p/>
9067      * Use {@link android.telephony.ims.stub.ImsRegistrationImplBase#onRegistered} and
9068      * {@link android.telephony.ims.stub.ImsRegistrationImplBase#onDeregistered} to set Ims
9069      * registration state instead.
9070      *
9071      * @param registered whether ims is registered
9072      *
9073      * @hide
9074      */
9075     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setImsRegistrationState(final boolean registered)9076     public void setImsRegistrationState(final boolean registered) {
9077         try {
9078             final ITelephony telephony = getITelephony();
9079             if (telephony != null)
9080                 telephony.setImsRegistrationState(registered);
9081         } catch (final RemoteException e) {
9082         }
9083     }
9084 
9085     /** @hide */
9086     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
9087             NETWORK_MODE_WCDMA_PREF,
9088             NETWORK_MODE_GSM_ONLY,
9089             NETWORK_MODE_WCDMA_ONLY,
9090             NETWORK_MODE_GSM_UMTS,
9091             NETWORK_MODE_CDMA_EVDO,
9092             NETWORK_MODE_CDMA_NO_EVDO,
9093             NETWORK_MODE_EVDO_NO_CDMA,
9094             NETWORK_MODE_GLOBAL,
9095             NETWORK_MODE_LTE_CDMA_EVDO,
9096             NETWORK_MODE_LTE_GSM_WCDMA,
9097             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
9098             NETWORK_MODE_LTE_ONLY,
9099             NETWORK_MODE_LTE_WCDMA,
9100             NETWORK_MODE_TDSCDMA_ONLY,
9101             NETWORK_MODE_TDSCDMA_WCDMA,
9102             NETWORK_MODE_LTE_TDSCDMA,
9103             NETWORK_MODE_TDSCDMA_GSM,
9104             NETWORK_MODE_LTE_TDSCDMA_GSM,
9105             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
9106             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
9107             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
9108             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
9109             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
9110             NETWORK_MODE_NR_ONLY,
9111             NETWORK_MODE_NR_LTE,
9112             NETWORK_MODE_NR_LTE_CDMA_EVDO,
9113             NETWORK_MODE_NR_LTE_GSM_WCDMA,
9114             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
9115             NETWORK_MODE_NR_LTE_WCDMA,
9116             NETWORK_MODE_NR_LTE_TDSCDMA,
9117             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
9118             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
9119             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
9120             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
9121     })
9122     @Retention(RetentionPolicy.SOURCE)
9123     public @interface PrefNetworkMode{}
9124 
9125     /**
9126      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
9127      * @hide
9128      */
9129     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
9130 
9131     /**
9132      * Preferred network mode is GSM only.
9133      * @hide
9134      */
9135     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
9136 
9137     /**
9138      * Preferred network mode is WCDMA only.
9139      * @hide
9140      */
9141     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
9142 
9143     /**
9144      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
9145      * @hide
9146      */
9147     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
9148 
9149     /**
9150      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
9151      * @hide
9152      */
9153     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
9154 
9155     /**
9156      * Preferred network mode is CDMA only.
9157      * @hide
9158      */
9159     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
9160 
9161     /**
9162      * Preferred network mode is EvDo only.
9163      * @hide
9164      */
9165     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
9166 
9167     /**
9168      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
9169      * @hide
9170      */
9171     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
9172 
9173     /**
9174      * Preferred network mode is LTE, CDMA and EvDo.
9175      * @hide
9176      */
9177     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
9178 
9179     /**
9180      * Preferred network mode is LTE, GSM/WCDMA.
9181      * @hide
9182      */
9183     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
9184 
9185     /**
9186      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
9187      * @hide
9188      */
9189     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
9190             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
9191 
9192     /**
9193      * Preferred network mode is LTE Only.
9194      * @hide
9195      */
9196     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
9197 
9198     /**
9199      * Preferred network mode is LTE/WCDMA.
9200      * @hide
9201      */
9202     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
9203 
9204     /**
9205      * Preferred network mode is TD-SCDMA only.
9206      * @hide
9207      */
9208     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
9209 
9210     /**
9211      * Preferred network mode is TD-SCDMA and WCDMA.
9212      * @hide
9213      */
9214     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
9215 
9216     /**
9217      * Preferred network mode is TD-SCDMA and LTE.
9218      * @hide
9219      */
9220     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
9221 
9222     /**
9223      * Preferred network mode is TD-SCDMA and GSM.
9224      * @hide
9225      */
9226     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
9227 
9228     /**
9229      * Preferred network mode is TD-SCDMA,GSM and LTE.
9230      * @hide
9231      */
9232     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
9233             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
9234 
9235     /**
9236      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
9237      * @hide
9238      */
9239     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
9240             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
9241 
9242     /**
9243      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
9244      * @hide
9245      */
9246     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
9247             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
9248 
9249     /**
9250      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
9251      * @hide
9252      */
9253     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
9254             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
9255 
9256     /**
9257      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
9258      * @hide
9259      */
9260     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
9261             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
9262     /**
9263      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
9264      * @hide
9265      */
9266     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
9267             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
9268 
9269     /**
9270      * Preferred network mode is NR 5G only.
9271      * @hide
9272      */
9273     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
9274 
9275     /**
9276      * Preferred network mode is NR 5G, LTE.
9277      * @hide
9278      */
9279     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
9280 
9281     /**
9282      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
9283      * @hide
9284      */
9285     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
9286             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
9287 
9288     /**
9289      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
9290      * @hide
9291      */
9292     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
9293             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
9294 
9295     /**
9296      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
9297      * @hide
9298      */
9299     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
9300             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
9301 
9302     /**
9303      * Preferred network mode is NR 5G, LTE and WCDMA.
9304      * @hide
9305      */
9306     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
9307 
9308     /**
9309      * Preferred network mode is NR 5G, LTE and TDSCDMA.
9310      * @hide
9311      */
9312     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
9313 
9314     /**
9315      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
9316      * @hide
9317      */
9318     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
9319             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
9320 
9321     /**
9322      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
9323      * @hide
9324      */
9325     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
9326             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
9327 
9328     /**
9329      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
9330      * @hide
9331      */
9332     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
9333             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
9334 
9335     /**
9336      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
9337      * @hide
9338      */
9339     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
9340             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
9341 
9342     /**
9343      * The default preferred network mode constant.
9344      *
9345      * <p> This constant is used in case of nothing is set in
9346      * TelephonyProperties#default_network().
9347      *
9348      * @hide
9349      */
9350     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
9351             RILConstants.PREFERRED_NETWORK_MODE;
9352 
9353     /**
9354      * Get the preferred network type.
9355      * Used for device configuration by some CDMA operators.
9356      *
9357      * <p>Requires Permission:
9358      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9359      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9360      *
9361      * @return the preferred network type.
9362      * @hide
9363      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
9364      */
9365     @Deprecated
9366     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
9367     @UnsupportedAppUsage
getPreferredNetworkType(int subId)9368     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
9369         return RadioAccessFamily.getNetworkTypeFromRaf((int) getAllowedNetworkTypesBitmask());
9370     }
9371 
9372     /**
9373      * Get the preferred network type bitmask.
9374      *
9375      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9376      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9377      *
9378      * <p>Requires Permission:
9379      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9380      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9381      *
9382      * @return The bitmask of preferred network types.
9383      *
9384      * @throws UnsupportedOperationException If the device does not have
9385      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9386      * @hide
9387      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
9388      */
9389     @Deprecated
9390     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9391     @SystemApi
9392     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getPreferredNetworkTypeBitmask()9393     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
9394         return getAllowedNetworkTypesBitmask();
9395     }
9396 
9397     /**
9398      * Get the allowed network type bitmask.
9399      * Note that the device can only register on the network of {@link NetworkTypeBitmask}
9400      * (except for emergency call cases).
9401      *
9402      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9403      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9404      *
9405      * <p>Requires Permission:
9406      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9407      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9408      *
9409      * @return The bitmask of allowed network types.
9410      *
9411      * @throws UnsupportedOperationException If the device does not have
9412      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9413      * @hide
9414      */
9415     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9416     @SystemApi
9417     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getAllowedNetworkTypesBitmask()9418     public @NetworkTypeBitMask long getAllowedNetworkTypesBitmask() {
9419         try {
9420             ITelephony telephony = getITelephony();
9421             if (telephony != null) {
9422                 return (long) telephony.getAllowedNetworkTypesBitmask(getSubId());
9423             }
9424         } catch (RemoteException ex) {
9425             Rlog.e(TAG, "getAllowedNetworkTypesBitmask RemoteException", ex);
9426         }
9427         return 0;
9428     }
9429 
9430     /**
9431      * Get the allowed network types by carriers.
9432      *
9433      * <p>Requires Permission:
9434      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9435      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9436      *
9437      * @return the allowed network type bitmask
9438      *
9439      * @throws UnsupportedOperationException If the device does not have
9440      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9441      * @hide
9442      * @deprecated Use {@link #getAllowedNetworkTypesForReason} instead.
9443      */
9444     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9445     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
9446     @SystemApi
9447     @Deprecated
getAllowedNetworkTypes()9448     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
9449         try {
9450             ITelephony telephony = getITelephony();
9451             if (telephony != null) {
9452                 return telephony.getAllowedNetworkTypesForReason(getSubId(),
9453                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER);
9454             }
9455         } catch (RemoteException ex) {
9456             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
9457         }
9458         return -1;
9459     }
9460 
9461     /**
9462      * Sets the network selection mode to automatic.
9463      *
9464      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9465      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9466      *
9467      * <p>Requires Permission:
9468      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9469      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9470      *
9471      * @throws UnsupportedOperationException If the device does not have
9472      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9473      */
9474     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9475     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9476     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeAutomatic()9477     public void setNetworkSelectionModeAutomatic() {
9478         try {
9479             ITelephony telephony = getITelephony();
9480             if (telephony != null) {
9481                 telephony.setNetworkSelectionModeAutomatic(getSubId());
9482             }
9483         } catch (RemoteException ex) {
9484             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
9485         } catch (NullPointerException ex) {
9486             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
9487         }
9488     }
9489 
9490     /**
9491      * Perform a radio scan and return the list of available networks.
9492      *
9493      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9494      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9495      *
9496      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
9497      *
9498      * <p>Requires Permissions:
9499      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
9500      * privileges (see {@link #hasCarrierPrivileges})
9501      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
9502      *
9503      * @return {@link CellNetworkScanResult} with the status
9504      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
9505      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
9506      * caused will be included in the result.
9507      *
9508      * @hide
9509      */
9510     @RequiresPermission(allOf = {
9511             android.Manifest.permission.MODIFY_PHONE_STATE,
9512             Manifest.permission.ACCESS_COARSE_LOCATION
9513     })
getAvailableNetworks()9514     public CellNetworkScanResult getAvailableNetworks() {
9515         try {
9516             ITelephony telephony = getITelephony();
9517             if (telephony != null) {
9518                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
9519                         getAttributionTag());
9520             }
9521         } catch (RemoteException ex) {
9522             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
9523         } catch (NullPointerException ex) {
9524             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
9525         }
9526         return new CellNetworkScanResult(
9527                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
9528     }
9529 
9530     /**
9531      * Request a network scan.
9532      *
9533      * This method is asynchronous, so the network scan results will be returned by callback.
9534      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
9535      *
9536      * <p>Requires Permission:
9537      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9538      * app has carrier privileges (see {@link #hasCarrierPrivileges})
9539      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
9540      *
9541      * If the system-wide location switch is off, apps may still call this API, with the
9542      * following constraints:
9543      * <ol>
9544      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
9545      *     <li>The app must not supply any specific bands or channels to scan.</li>
9546      *     <li>The app must only specify MCC/MNC pairs that are
9547      *     associated to a SIM in the device.</li>
9548      *     <li>Returned results will have no meaningful info other than signal strength
9549      *     and MCC/MNC info.</li>
9550      * </ol>
9551      *
9552      * @param request Contains all the RAT with bands/channels that need to be scanned.
9553      * @param executor The executor through which the callback should be invoked. Since the scan
9554      *        request may trigger multiple callbacks and they must be invoked in the same order as
9555      *        they are received by the platform, the user should provide an executor which executes
9556      *        tasks one at a time in serial order.
9557      * @param callback Returns network scan results or errors.
9558      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
9559      *
9560      * @throws UnsupportedOperationException If the device does not have
9561      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9562      */
9563     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9564     @RequiresPermission(allOf = {
9565             android.Manifest.permission.MODIFY_PHONE_STATE,
9566             Manifest.permission.ACCESS_FINE_LOCATION
9567     })
9568     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)9569     public NetworkScan requestNetworkScan(
9570             NetworkScanRequest request, Executor executor,
9571             TelephonyScanManager.NetworkScanCallback callback) {
9572         return requestNetworkScan(INCLUDE_LOCATION_DATA_FINE, request, executor, callback);
9573     }
9574 
9575     /**
9576      * Request a network scan.
9577      *
9578      * This method is asynchronous, so the network scan results will be returned by callback.
9579      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
9580      *
9581      * <p>Requires Permission:
9582      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9583      * app has carrier privileges (see {@link #hasCarrierPrivileges})
9584      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION} if includeLocationData is
9585      * set to {@link #INCLUDE_LOCATION_DATA_FINE}.
9586      *
9587      * If the system-wide location switch is off, apps may still call this API, with the
9588      * following constraints:
9589      * <ol>
9590      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
9591      *     <li>The app must not supply any specific bands or channels to scan.</li>
9592      *     <li>The app must only specify MCC/MNC pairs that are
9593      *     associated to a SIM in the device.</li>
9594      *     <li>Returned results will have no meaningful info other than signal strength
9595      *     and MCC/MNC info.</li>
9596      * </ol>
9597      *
9598      * @param includeLocationData Specifies if the caller would like to receive
9599      * location related information. If this parameter is set to
9600      * {@link #INCLUDE_LOCATION_DATA_FINE} then the application will be checked for
9601      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission and available
9602      * location related information received during network scan will be sent to the caller.
9603      * @param request Contains all the RAT with bands/channels that need to be scanned.
9604      * @param executor The executor through which the callback should be invoked. Since the scan
9605      *        request may trigger multiple callbacks and they must be invoked in the same order as
9606      *        they are received by the platform, the user should provide an executor which executes
9607      *        tasks one at a time in serial order.
9608      * @param callback Returns network scan results or errors.
9609      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
9610      *
9611      * @throws UnsupportedOperationException If the device does not have
9612      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9613      */
9614     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9615     @RequiresPermission(allOf = {
9616             android.Manifest.permission.MODIFY_PHONE_STATE
9617     })
9618     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( @ncludeLocationData int includeLocationData, @NonNull NetworkScanRequest request, @NonNull Executor executor, @NonNull TelephonyScanManager.NetworkScanCallback callback)9619     public @Nullable NetworkScan requestNetworkScan(
9620             @IncludeLocationData int includeLocationData,
9621             @NonNull NetworkScanRequest request,
9622             @NonNull Executor executor,
9623             @NonNull TelephonyScanManager.NetworkScanCallback callback) {
9624         synchronized (sCacheLock) {
9625             if (mTelephonyScanManager == null) {
9626                 mTelephonyScanManager = new TelephonyScanManager();
9627             }
9628         }
9629         return mTelephonyScanManager.requestNetworkScan(getSubId(),
9630                 includeLocationData != INCLUDE_LOCATION_DATA_FINE,
9631                 request, executor, callback,
9632                 getOpPackageName(), getAttributionTag());
9633     }
9634 
9635     /**
9636      * @throws UnsupportedOperationException If the device does not have
9637      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9638      *
9639      * @deprecated
9640      * Use {@link
9641      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
9642      * @removed
9643      */
9644     @Deprecated
9645     @RequiresPermission(allOf = {
9646             android.Manifest.permission.MODIFY_PHONE_STATE,
9647             Manifest.permission.ACCESS_FINE_LOCATION
9648     })
9649     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)9650     public NetworkScan requestNetworkScan(
9651         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
9652         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
9653     }
9654 
9655     /**
9656      * Ask the radio to connect to the input network and change selection mode to manual.
9657      *
9658      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9659      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9660      *
9661      * <p>Requires Permission:
9662      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9663      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9664      *
9665      * @param operatorNumeric the PLMN ID of the network to select.
9666      * @param persistSelection whether the selection will persist until reboot. If true, only allows
9667      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
9668      * normal network selection next time.
9669      * @return {@code true} on success; {@code false} on any failure.
9670      *
9671      * @throws UnsupportedOperationException If the device does not have
9672      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9673      */
9674     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9675     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9676     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)9677     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
9678         return setNetworkSelectionModeManual(
9679                 new OperatorInfo(
9680                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
9681                 persistSelection);
9682     }
9683 
9684     /**
9685      * Ask the radio to connect to the input network and change selection mode to manual.
9686      *
9687      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9688      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9689      *
9690      * <p>Requires Permission:
9691      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9692      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9693      *
9694      * @param operatorNumeric the PLMN ID of the network to select.
9695      * @param persistSelection whether the selection will persist until reboot.
9696      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
9697      *         attach to the chosen PLMN and resume normal network selection next time.
9698      * @param ran the initial suggested radio access network type.
9699      *         If registration fails, the RAN is not available after, the RAN is not within the
9700      *         network types specified by the preferred network types, or the value is
9701      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
9702      *         the next best RAN for network registration.
9703      * @return {@code true} on success; {@code false} on any failure.
9704      *
9705      * @throws UnsupportedOperationException If the device does not have
9706      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9707      */
9708     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9709     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)9710     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
9711             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
9712         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
9713                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
9714     }
9715 
9716     /**
9717      * Ask the radio to connect to the input network and change selection mode to manual.
9718      *
9719      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9720      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9721      *
9722      * <p>Requires Permission:
9723      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9724      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9725      *
9726      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
9727      * @param persistSelection whether the selection will persist until reboot. If true, only allows
9728      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
9729      * normal network selection next time.
9730      * @return {@code true} on success; {@code true} on any failure.
9731      *
9732      * @hide
9733      */
9734     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)9735     public boolean setNetworkSelectionModeManual(
9736             OperatorInfo operatorInfo, boolean persistSelection) {
9737         try {
9738             ITelephony telephony = getITelephony();
9739             if (telephony != null) {
9740                 return telephony.setNetworkSelectionModeManual(
9741                         getSubId(), operatorInfo, persistSelection);
9742             }
9743         } catch (RemoteException ex) {
9744             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
9745         }
9746         return false;
9747     }
9748 
9749     /**
9750      * Get the network selection mode.
9751      *
9752      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9753      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9754      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
9755      * READ_PRECISE_PHONE_STATE}
9756      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9757      *
9758      * @return the network selection mode.
9759      *
9760      * @throws UnsupportedOperationException If the device does not have
9761      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9762      */
9763     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
9764     @RequiresPermission(anyOf = {
9765             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9766             android.Manifest.permission.READ_PRECISE_PHONE_STATE
9767     })
9768     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkSelectionMode()9769     public @NetworkSelectionMode int getNetworkSelectionMode() {
9770         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
9771         try {
9772             ITelephony telephony = getITelephony();
9773             if (telephony != null) {
9774                 mode = telephony.getNetworkSelectionMode(getSubId());
9775             }
9776         } catch (RemoteException ex) {
9777             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
9778         }
9779         return mode;
9780     }
9781 
9782     /**
9783      * Get the PLMN chosen for Manual Network Selection if active.
9784      * Return empty string if in automatic selection.
9785      *
9786      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
9787      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
9788      * (see {@link #hasCarrierPrivileges})
9789      *
9790      * @return manually selected network info on success or empty string on failure
9791      *
9792      * @throws UnsupportedOperationException If the device does not have
9793      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9794      */
9795     @SuppressAutoDoc // No support carrier privileges (b/72967236).
9796     @RequiresPermission(android.Manifest.permission.READ_PRECISE_PHONE_STATE)
9797     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getManualNetworkSelectionPlmn()9798     public @NonNull String getManualNetworkSelectionPlmn() {
9799         try {
9800             ITelephony telephony = getITelephony();
9801             if (telephony != null && isManualNetworkSelectionAllowed()) {
9802                 return telephony.getManualNetworkSelectionPlmn(getSubId());
9803             }
9804         } catch (RemoteException ex) {
9805             Rlog.e(TAG, "getManualNetworkSelectionPlmn RemoteException", ex);
9806         }
9807         return "";
9808     }
9809 
9810     /**
9811      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
9812      * user and we are still within the time interval after the emergency SMS was sent that we are
9813      * considered in Emergency SMS mode.
9814      *
9815      * <p>This mode is used by other applications to allow them to perform special functionality,
9816      * such as allow the GNSS service to provide user location to the carrier network for emergency
9817      * when an emergency SMS is sent. This interval is set by
9818      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
9819      * the carrier does not support this mode, this function will always return false.
9820      *
9821      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
9822      *
9823      * @throws UnsupportedOperationException If the device does not have
9824      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
9825      * @hide
9826      */
9827     @SystemApi
9828     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9829     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
isInEmergencySmsMode()9830     public boolean isInEmergencySmsMode() {
9831         try {
9832             ITelephony telephony = getITelephony();
9833             if (telephony != null) {
9834                 return telephony.isInEmergencySmsMode();
9835             }
9836         } catch (RemoteException ex) {
9837             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
9838         }
9839         return false;
9840     }
9841 
9842     /**
9843      * Set the preferred network type.
9844      *
9845      * <p>Requires Permission:
9846      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9847      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9848      * <p>
9849      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
9850      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
9851      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
9852      * setPreferredNetworkTypesBitmap is used instead.
9853      *
9854      * @param subId the id of the subscription to set the preferred network type for.
9855      * @param networkType the preferred network type
9856      * @return true on success; false on any failure.
9857      * @hide
9858      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
9859      */
9860     @Deprecated
9861     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)9862     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
9863         try {
9864             ITelephony telephony = getITelephony();
9865             if (telephony != null) {
9866                 return telephony.setAllowedNetworkTypesForReason(subId,
9867                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
9868                         RadioAccessFamily.getRafFromNetworkType(networkType));
9869             }
9870         } catch (RemoteException ex) {
9871             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
9872         }
9873         return false;
9874     }
9875 
9876     /**
9877      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
9878      * only the allowed network type will set to the modem.
9879      *
9880      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9881      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9882      *
9883      * <p>Requires Permission:
9884      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9885      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9886      * <p>
9887      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
9888      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
9889      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
9890      * setPreferredNetworkTypesBitmap is used instead.
9891      *
9892      * @param networkTypeBitmask The bitmask of preferred network types.
9893      * @return true on success; false on any failure.
9894      *
9895      * @throws UnsupportedOperationException If the device does not have
9896      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9897      * @hide
9898      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
9899      */
9900     @Deprecated
9901     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9902     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
9903     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)9904     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
9905         try {
9906             ITelephony telephony = getITelephony();
9907             if (telephony != null) {
9908                 networkTypeBitmask = checkNetworkTypeBitmask(networkTypeBitmask);
9909                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
9910                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER, networkTypeBitmask);
9911             }
9912         } catch (RemoteException ex) {
9913             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
9914         }
9915         return false;
9916     }
9917 
9918     /**
9919      * If {@link #NETWORK_TYPE_BITMASK_LTE_CA} bit is set, convert it to NETWORK_TYPE_BITMASK_LTE.
9920      *
9921      * @param networkTypeBitmask The networkTypeBitmask being checked
9922      * @return The checked/converted networkTypeBitmask
9923      */
checkNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)9924     private long checkNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
9925         if ((networkTypeBitmask & NETWORK_TYPE_BITMASK_LTE_CA) != 0) {
9926             networkTypeBitmask ^= NETWORK_TYPE_BITMASK_LTE_CA;
9927             networkTypeBitmask |= NETWORK_TYPE_BITMASK_LTE;
9928         }
9929         return networkTypeBitmask;
9930     }
9931 
9932     /**
9933      * Set the allowed network types of the device. This is for carrier or privileged apps to
9934      * enable/disable certain network types on the device. The user preferred network types should
9935      * be set through {@link #setPreferredNetworkTypeBitmask}.
9936      * <p>
9937      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
9938      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
9939      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
9940      * setPreferredNetworkTypesBitmap is used instead.
9941      *
9942      * @param allowedNetworkTypes The bitmask of allowed network types.
9943      * @return true on success; false on any failure.
9944      *
9945      * @throws UnsupportedOperationException If the device does not have
9946      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9947      *
9948      * @hide
9949      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead with reason
9950      * {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}.
9951      */
9952     @Deprecated
9953     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9954     @RequiresFeature(
9955             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
9956             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
9957     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)9958     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
9959         try {
9960             ITelephony telephony = getITelephony();
9961             if (telephony != null) {
9962                 allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
9963                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
9964                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER, allowedNetworkTypes);
9965             }
9966         } catch (RemoteException ex) {
9967             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
9968         }
9969         return false;
9970     }
9971 
9972     /** @hide */
9973     @IntDef({
9974             ALLOWED_NETWORK_TYPES_REASON_USER,
9975             ALLOWED_NETWORK_TYPES_REASON_POWER,
9976             ALLOWED_NETWORK_TYPES_REASON_CARRIER,
9977             ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G,
9978     })
9979     @Retention(RetentionPolicy.SOURCE)
9980     public @interface AllowedNetworkTypesReason {
9981     }
9982 
9983     /**
9984      * To indicate allowed network type change is requested by user.
9985      */
9986     public static final int ALLOWED_NETWORK_TYPES_REASON_USER = 0;
9987 
9988     /**
9989      * To indicate allowed network type change is requested by power manager.
9990      * Power Manger configuration won't affect the settings configured through
9991      * other reasons and will result in allowing network types that are in both
9992      * configurations (i.e intersection of both sets).
9993      *
9994      * @hide
9995      */
9996     @SystemApi
9997     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 1;
9998 
9999     /**
10000      * To indicate allowed network type change is requested by carrier.
10001      * Carrier configuration won't affect the settings configured through
10002      * other reasons and will result in allowing network types that are in both
10003      * configurations (i.e intersection of both sets).
10004      */
10005     public static final int ALLOWED_NETWORK_TYPES_REASON_CARRIER = 2;
10006 
10007     /**
10008      * To indicate allowed network type change is requested by the user via the 2G toggle.
10009      *
10010      * @hide
10011      */
10012     @SystemApi
10013     public static final int ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G = 3;
10014 
10015     /**
10016      * Set the allowed network types of the device and provide the reason triggering the allowed
10017      * network change.
10018      * <p>Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
10019      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10020      *
10021      * This can be called for following reasons:
10022      * <ol>
10023      * <li>Allowed network types control by USER
10024      * {@link TelephonyManager#ALLOWED_NETWORK_TYPES_REASON_USER}
10025      * <li>Allowed network types control by carrier {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}
10026      * </ol>
10027      * This API will result in allowing an intersection of allowed network types for all reasons,
10028      * including the configuration done through other reasons.
10029      *
10030      * @param reason the reason the allowed network type change is taking place
10031      * @param allowedNetworkTypes The bitmask of allowed network type
10032      * @throws IllegalStateException if the Telephony process is not currently available.
10033      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
10034      * @throws SecurityException if the caller does not have the required privileges or if the
10035      * @throws UnsupportedOperationException If the device does not have
10036      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10037      * caller tries to use one of the following security-based reasons without
10038      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} permissions.
10039      * <ol>
10040      *     <li>{@code TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G}</li>
10041      * </ol>
10042      *
10043      * @throws UnsupportedOperationException If the device does not have
10044      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10045      */
10046     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10047     @RequiresFeature(
10048             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
10049             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)10050     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
10051             @NetworkTypeBitMask long allowedNetworkTypes) {
10052         if (!isValidAllowedNetworkTypesReason(reason)) {
10053             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
10054         }
10055 
10056         try {
10057             ITelephony telephony = getITelephony();
10058             if (telephony != null) {
10059                 allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
10060                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
10061                         allowedNetworkTypes);
10062             } else {
10063                 throw new IllegalStateException("telephony service is null.");
10064             }
10065         } catch (RemoteException ex) {
10066             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
10067             ex.rethrowFromSystemServer();
10068         }
10069     }
10070 
10071     /**
10072      * Get the allowed network types for certain reason.
10073      *
10074      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
10075      * specific reason.
10076      * <p>Requires permission: android.Manifest.READ_PRIVILEGED_PHONE_STATE or
10077      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10078      *
10079      * @param reason the reason the allowed network type change is taking place
10080      * @return the allowed network type bitmask
10081      * @throws IllegalStateException    if the Telephony process is not currently available.
10082      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
10083      * @throws SecurityException if the caller does not have the required permission/privileges
10084      * @throws UnsupportedOperationException If the device does not have
10085      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10086      */
10087     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10088     @RequiresFeature(
10089             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
10090             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)10091     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
10092             @AllowedNetworkTypesReason int reason) {
10093         if (!isValidAllowedNetworkTypesReason(reason)) {
10094             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
10095         }
10096 
10097         try {
10098             ITelephony telephony = getITelephony();
10099             if (telephony != null) {
10100                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
10101             } else {
10102                 throw new IllegalStateException("telephony service is null.");
10103             }
10104         } catch (RemoteException ex) {
10105             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
10106             ex.rethrowFromSystemServer();
10107         }
10108         return -1;
10109     }
10110     /**
10111      * Verifies that the reason provided is valid.
10112      * @hide
10113      */
isValidAllowedNetworkTypesReason(@llowedNetworkTypesReason int reason)10114     public static boolean isValidAllowedNetworkTypesReason(@AllowedNetworkTypesReason int reason) {
10115         switch (reason) {
10116             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER:
10117             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER:
10118             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER:
10119             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G:
10120                 return true;
10121         }
10122         return false;
10123     }
10124     /**
10125      * Get bit mask of all network types.
10126      *
10127      * @return bit mask of all network types
10128      * @hide
10129      */
getAllNetworkTypesBitmask()10130     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
10131         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
10132     }
10133 
10134     /**
10135      * Returns a string representation of the allowed network types{@link NetworkTypeBitMask}.
10136      *
10137      * @param networkTypeBitmask The bitmask of allowed network types.
10138      * @return the name of the allowed network types
10139      * @hide
10140      */
convertNetworkTypeBitmaskToString( @etworkTypeBitMask long networkTypeBitmask)10141     public static String convertNetworkTypeBitmaskToString(
10142             @NetworkTypeBitMask long networkTypeBitmask) {
10143         String networkTypeName = IntStream.rangeClosed(NETWORK_TYPE_GPRS, NETWORK_TYPE_NR)
10144                 .filter(x -> {
10145                     return (networkTypeBitmask & getBitMaskForNetworkType(x))
10146                             == getBitMaskForNetworkType(x);
10147                 })
10148                 .mapToObj(x -> getNetworkTypeName(x))
10149                 .collect(Collectors.joining("|"));
10150         return TextUtils.isEmpty(networkTypeName) ? "UNKNOWN" : networkTypeName;
10151     }
10152 
10153     /**
10154      * Set the preferred network type to global mode which includes NR, LTE, CDMA, EvDo
10155      * and GSM/WCDMA.
10156      *
10157      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10158      *
10159      * @return true on success; false on any failure.
10160      *
10161      * @throws UnsupportedOperationException If the device does not have
10162      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10163      */
10164     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setPreferredNetworkTypeToGlobal()10165     public boolean setPreferredNetworkTypeToGlobal() {
10166         return setPreferredNetworkTypeToGlobal(getSubId());
10167     }
10168 
10169     /**
10170      * Set the preferred network type to global mode which includes NR, LTE, CDMA, EvDo
10171      * and GSM/WCDMA.
10172      *
10173      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10174      *
10175      * @return true on success; false on any failure.
10176      * @hide
10177      */
setPreferredNetworkTypeToGlobal(int subId)10178     public boolean setPreferredNetworkTypeToGlobal(int subId) {
10179         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA);
10180     }
10181 
10182     /**
10183      * Check whether DUN APN is required for tethering.
10184      * <p>
10185      * Requires Permission: MODIFY_PHONE_STATE.
10186      *
10187      * @return {@code true} if DUN APN is required for tethering.
10188      *
10189      * @throws UnsupportedOperationException If the device does not have
10190      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
10191      * @hide
10192      */
10193     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10194     @SystemApi
10195     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isTetheringApnRequired()10196     public boolean isTetheringApnRequired() {
10197         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
10198     }
10199 
10200     /**
10201      * Check whether DUN APN is required for tethering with subId.
10202      *
10203      * @param subId the id of the subscription to require tethering.
10204      * @return {@code true} if DUN APN is required for tethering.
10205      * @hide
10206      */
isTetheringApnRequired(int subId)10207     public boolean isTetheringApnRequired(int subId) {
10208         try {
10209             ITelephony telephony = getITelephony();
10210             if (telephony != null)
10211                 return telephony.isTetheringApnRequiredForSubscriber(subId);
10212         } catch (RemoteException ex) {
10213             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
10214         } catch (NullPointerException ex) {
10215             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
10216         }
10217         return false;
10218     }
10219 
10220 
10221     /**
10222      * Values used to return status for hasCarrierPrivileges call.
10223      */
10224     /** @hide */ @SystemApi
10225     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
10226     /** @hide */ @SystemApi
10227     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
10228     /** @hide */ @SystemApi
10229     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
10230     /** @hide */ @SystemApi
10231     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
10232 
10233     /**
10234      * Has the calling application been granted carrier privileges by the carrier.
10235      *
10236      * If any of the packages in the calling UID has carrier privileges, the
10237      * call will return true. This access is granted by the owner of the UICC
10238      * card and does not depend on the registered carrier.
10239      *
10240      * Note that this API applies to both physical and embedded subscriptions and
10241      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
10242      *
10243      * @return true if the app has carrier privileges.
10244      *
10245      * @throws UnsupportedOperationException If the device does not have
10246      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10247      */
10248     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
hasCarrierPrivileges()10249     public boolean hasCarrierPrivileges() {
10250         return hasCarrierPrivileges(getSubId());
10251     }
10252 
10253     /**
10254      * Has the calling application been granted carrier privileges by the carrier.
10255      *
10256      * If any of the packages in the calling UID has carrier privileges, the
10257      * call will return true. This access is granted by the owner of the UICC
10258      * card and does not depend on the registered carrier.
10259      *
10260      * Note that this API applies to both physical and embedded subscriptions and
10261      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
10262      *
10263      * @param subId The subscription to use.
10264      * @return true if the app has carrier privileges.
10265      * @hide
10266      */
hasCarrierPrivileges(int subId)10267     public boolean hasCarrierPrivileges(int subId) {
10268         try {
10269             ITelephony telephony = getITelephony();
10270             if (telephony != null) {
10271                 return telephony.getCarrierPrivilegeStatus(subId)
10272                         == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
10273             }
10274         } catch (RemoteException ex) {
10275             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
10276         } catch (NullPointerException ex) {
10277             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
10278         }
10279         return false;
10280     }
10281 
10282     /**
10283      * Override the branding for the current ICCID.
10284      *
10285      * Once set, whenever the SIM is present in the device, the service
10286      * provider name (SPN) and the operator name will both be replaced by the
10287      * brand value input. To unset the value, the same function should be
10288      * called with a null brand value.
10289      *
10290      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10291      *
10292      * @param brand The brand name to display/set.
10293      * @return true if the operation was executed correctly.
10294      *
10295      * @throws UnsupportedOperationException If the device does not have
10296      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10297      */
10298     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setOperatorBrandOverride(String brand)10299     public boolean setOperatorBrandOverride(String brand) {
10300         return setOperatorBrandOverride(getSubId(), brand);
10301     }
10302 
10303     /**
10304      * Override the branding for the current ICCID.
10305      *
10306      * Once set, whenever the SIM is present in the device, the service
10307      * provider name (SPN) and the operator name will both be replaced by the
10308      * brand value input. To unset the value, the same function should be
10309      * called with a null brand value.
10310      *
10311      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10312      *
10313      * @param subId The subscription to use.
10314      * @param brand The brand name to display/set.
10315      * @return true if the operation was executed correctly.
10316      * @hide
10317      */
setOperatorBrandOverride(int subId, String brand)10318     public boolean setOperatorBrandOverride(int subId, String brand) {
10319         try {
10320             ITelephony telephony = getITelephony();
10321             if (telephony != null)
10322                 return telephony.setOperatorBrandOverride(subId, brand);
10323         } catch (RemoteException ex) {
10324             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
10325         } catch (NullPointerException ex) {
10326             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
10327         }
10328         return false;
10329     }
10330 
10331     /**
10332      * Override the roaming preference for the current ICCID.
10333      *
10334      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
10335      * the platform's notion of a network operator being considered roaming or not.
10336      * The change only affects the ICCID that was active when this call was made.
10337      *
10338      * If null is passed as any of the input, the corresponding value is deleted.
10339      *
10340      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
10341      *
10342      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
10343      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
10344      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
10345      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
10346      * @return true if the operation was executed correctly.
10347      *
10348      * @hide
10349      */
10350     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)10351     public boolean setRoamingOverride(List<String> gsmRoamingList,
10352             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
10353             List<String> cdmaNonRoamingList) {
10354         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
10355                 cdmaRoamingList, cdmaNonRoamingList);
10356     }
10357 
10358     /**
10359      * Override the roaming preference for the current ICCID.
10360      *
10361      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
10362      * the platform's notion of a network operator being considered roaming or not.
10363      * The change only affects the ICCID that was active when this call was made.
10364      *
10365      * If null is passed as any of the input, the corresponding value is deleted.
10366      *
10367      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
10368      *
10369      * @param subId for which the roaming overrides apply.
10370      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
10371      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
10372      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
10373      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
10374      * @return true if the operation was executed correctly.
10375      *
10376      * @hide
10377      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)10378     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
10379             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
10380             List<String> cdmaNonRoamingList) {
10381         try {
10382             ITelephony telephony = getITelephony();
10383             if (telephony != null)
10384                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
10385                         cdmaRoamingList, cdmaNonRoamingList);
10386         } catch (RemoteException ex) {
10387             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
10388         } catch (NullPointerException ex) {
10389             Rlog.e(TAG, "setRoamingOverride NPE", ex);
10390         }
10391         return false;
10392     }
10393 
10394     /**
10395      * Expose the rest of ITelephony to @SystemApi
10396      */
10397 
10398     /**
10399      * @throws UnsupportedOperationException If the device does not have
10400      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10401      * @hide
10402      */
10403     @SystemApi
10404     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10405     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMdn()10406     public String getCdmaMdn() {
10407         return getCdmaMdn(getSubId());
10408     }
10409 
10410     /**
10411      * @throws UnsupportedOperationException If the device does not have
10412      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10413      * @hide
10414      */
10415     @SystemApi
10416     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10417     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMdn(int subId)10418     public String getCdmaMdn(int subId) {
10419         try {
10420             ITelephony telephony = getITelephony();
10421             if (telephony == null)
10422                 return null;
10423             return telephony.getCdmaMdn(subId);
10424         } catch (RemoteException ex) {
10425             return null;
10426         } catch (NullPointerException ex) {
10427             return null;
10428         }
10429     }
10430 
10431     /**
10432      * @throws UnsupportedOperationException If the device does not have
10433      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10434      * @hide
10435      */
10436     @SystemApi
10437     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10438     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMin()10439     public String getCdmaMin() {
10440         return getCdmaMin(getSubId());
10441     }
10442 
10443     /**
10444      * @throws UnsupportedOperationException If the device does not have
10445      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10446      * @hide
10447      */
10448     @SystemApi
10449     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10450     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMin(int subId)10451     public String getCdmaMin(int subId) {
10452         try {
10453             ITelephony telephony = getITelephony();
10454             if (telephony == null)
10455                 return null;
10456             return telephony.getCdmaMin(subId);
10457         } catch (RemoteException ex) {
10458             return null;
10459         } catch (NullPointerException ex) {
10460             return null;
10461         }
10462     }
10463 
10464     /**
10465      * @throws UnsupportedOperationException If the device does not have
10466      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10467      * @hide
10468      */
10469     @SystemApi
10470     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10471     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
checkCarrierPrivilegesForPackage(String pkgName)10472     public int checkCarrierPrivilegesForPackage(String pkgName) {
10473         try {
10474             ITelephony telephony = getITelephony();
10475             if (telephony != null)
10476                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
10477         } catch (RemoteException ex) {
10478             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
10479         } catch (NullPointerException ex) {
10480             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
10481         }
10482         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
10483     }
10484 
10485     /**
10486      * @throws UnsupportedOperationException If the device does not have
10487      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10488      * @hide
10489      */
10490     @SystemApi
10491     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10492     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)10493     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
10494         try {
10495             ITelephony telephony = getITelephony();
10496             if (telephony != null)
10497                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
10498         } catch (RemoteException ex) {
10499             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
10500         } catch (NullPointerException ex) {
10501             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
10502         }
10503         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
10504     }
10505 
10506     /**
10507      * @throws UnsupportedOperationException If the device does not have
10508      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10509      * @hide
10510      */
10511     @SystemApi
10512     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPackageNamesForIntent(Intent intent)10513     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
10514         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
10515     }
10516 
10517     /**
10518      * @throws UnsupportedOperationException If the device does not have
10519      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10520      * @hide
10521      */
10522     @SystemApi
10523     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10524     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)10525     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
10526         try {
10527             ITelephony telephony = getITelephony();
10528             if (telephony != null)
10529                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
10530         } catch (RemoteException ex) {
10531             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
10532         } catch (NullPointerException ex) {
10533             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
10534         }
10535         return null;
10536     }
10537 
10538     /**
10539      * Returns the package name that provides the {@link CarrierService} implementation for the
10540      * current subscription, or {@code null} if no package with carrier privileges declares one.
10541      *
10542      * <p>If this object has been created with {@link #createForSubscriptionId}, then the provided
10543      * subscription ID is used. Otherwise, the default subscription ID will be used.
10544      *
10545      * @return The system-selected package that provides the {@link CarrierService} implementation
10546      * for the current subscription, or {@code null} if none is resolved
10547      *
10548      * @throws UnsupportedOperationException If the device does not have
10549      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10550      * @hide
10551      */
10552     @SystemApi
10553     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10554     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierServicePackageName()10555     public @Nullable String getCarrierServicePackageName() {
10556         return getCarrierServicePackageNameForLogicalSlot(getPhoneId());
10557     }
10558 
10559     /**
10560      * Returns the package name that provides the {@link CarrierService} implementation for the
10561      * specified {@code logicalSlotIndex}, or {@code null} if no package with carrier privileges
10562      * declares one.
10563      *
10564      * @param logicalSlotIndex The slot index to fetch the {@link CarrierService} package for
10565      * @return The system-selected package that provides the {@link CarrierService} implementation
10566      * for the slot, or {@code null} if none is resolved
10567      *
10568      * @throws UnsupportedOperationException If the device does not have
10569      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10570      * @hide
10571      */
10572     @SystemApi
10573     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10574     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex)10575     public @Nullable String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex) {
10576         try {
10577             ITelephony telephony = getITelephony();
10578             if (telephony != null) {
10579                 return telephony.getCarrierServicePackageNameForLogicalSlot(logicalSlotIndex);
10580             }
10581         } catch (RemoteException ex) {
10582             Rlog.e(TAG, "getCarrierServicePackageNameForLogicalSlot RemoteException", ex);
10583         } catch (NullPointerException ex) {
10584             Rlog.e(TAG, "getCarrierServicePackageNameForLogicalSlot NPE", ex);
10585         }
10586         return null;
10587     }
10588 
10589     /** @hide */
10590     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPackagesWithCarrierPrivileges()10591     public List<String> getPackagesWithCarrierPrivileges() {
10592         try {
10593             ITelephony telephony = getITelephony();
10594             if (telephony != null) {
10595                 return telephony.getPackagesWithCarrierPrivileges(getPhoneId());
10596             }
10597         } catch (RemoteException ex) {
10598             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
10599         } catch (NullPointerException ex) {
10600             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
10601         }
10602         return Collections.EMPTY_LIST;
10603     }
10604 
10605     /**
10606      * Get the names of packages with carrier privileges for all the active subscriptions.
10607      *
10608      * @throws UnsupportedOperationException If the device does not have
10609      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10610      * @hide
10611      */
10612     @SystemApi
10613     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10614     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
10615     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()10616     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
10617         try {
10618             ITelephony telephony = getITelephony();
10619             if (telephony != null) {
10620                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
10621             }
10622         } catch (RemoteException ex) {
10623             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
10624                     ex);
10625         } catch (NullPointerException ex) {
10626             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
10627         }
10628         return Collections.EMPTY_LIST;
10629     }
10630 
10631     /**
10632      * Call composer status <b>OFF</b> from user setting.
10633      */
10634     public static final int CALL_COMPOSER_STATUS_OFF = 0;
10635 
10636     /**
10637      * Call composer status <b>ON</b> from user setting.
10638      */
10639     public static final int CALL_COMPOSER_STATUS_ON = 1;
10640 
10641     /**
10642      * Call composer status <b>Business Only</b> from user setting.
10643      */
10644     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_BUSINESS_CALL_COMPOSER)
10645     public static final int CALL_COMPOSER_STATUS_BUSINESS_ONLY = 2;
10646 
10647     /** @hide */
10648     @IntDef(prefix = {"CALL_COMPOSER_STATUS_"},
10649             value = {
10650                 CALL_COMPOSER_STATUS_ON,
10651                 CALL_COMPOSER_STATUS_OFF,
10652                 CALL_COMPOSER_STATUS_BUSINESS_ONLY
10653             })
10654     @Retention(RetentionPolicy.SOURCE)
10655     public @interface CallComposerStatus {}
10656 
10657     /**
10658      * Set the user-set status for enriched calling with call composer.
10659      *
10660      * @param status user-set status for enriched calling with call composer.
10661      *
10662      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10663      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10664      *
10665      * @throws IllegalArgumentException if requested state is invalid.
10666      * @throws SecurityException if the caller does not have the permission.
10667      * @throws UnsupportedOperationException If the device does not have
10668      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
10669      */
10670     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10671     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallComposerStatus(@allComposerStatus int status)10672     public void setCallComposerStatus(@CallComposerStatus int status) {
10673         if (com.android.server.telecom.flags.Flags.businessCallComposer()) {
10674             if (status > CALL_COMPOSER_STATUS_BUSINESS_ONLY
10675                     || status < CALL_COMPOSER_STATUS_OFF) {
10676                 throw new IllegalArgumentException("requested status is invalid");
10677             }
10678         } else {
10679             if (status > CALL_COMPOSER_STATUS_ON
10680                     || status < CALL_COMPOSER_STATUS_OFF) {
10681                 throw new IllegalArgumentException("requested status is invalid");
10682             }
10683         }
10684         try {
10685             ITelephony telephony = getITelephony();
10686             if (telephony != null) {
10687                 telephony.setCallComposerStatus(getSubId(), status);
10688             }
10689         } catch (RemoteException ex) {
10690             Log.e(TAG, "Error calling ITelephony#setCallComposerStatus", ex);
10691             ex.rethrowFromSystemServer();
10692         }
10693     }
10694 
10695     /**
10696      * Get the user-set status for enriched calling with call composer.
10697      *
10698      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10699      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10700      *
10701      * @throws SecurityException if the caller does not have the permission.
10702      *
10703      * @return the user-set status for enriched calling with call composer, either of
10704      * {@link #CALL_COMPOSER_STATUS_ON} or {@link #CALL_COMPOSER_STATUS_OFF}.
10705      *
10706      * @throws UnsupportedOperationException If the device does not have
10707      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
10708      */
10709     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10710     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallComposerStatus()10711     public @CallComposerStatus int getCallComposerStatus() {
10712         try {
10713             ITelephony telephony = getITelephony();
10714             if (telephony != null) {
10715                 return telephony.getCallComposerStatus(getSubId());
10716             }
10717         } catch (RemoteException ex) {
10718             Log.e(TAG, "Error calling ITelephony#getCallComposerStatus", ex);
10719             ex.rethrowFromSystemServer();
10720         }
10721         return CALL_COMPOSER_STATUS_OFF;
10722     }
10723 
10724     /**
10725      * @throws UnsupportedOperationException If the device does not have
10726      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
10727      * @hide
10728      */
10729     @SystemApi
10730     @SuppressLint("RequiresPermission")
10731     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
dial(String number)10732     public void dial(String number) {
10733         try {
10734             ITelephony telephony = getITelephony();
10735             if (telephony != null)
10736                 telephony.dial(number);
10737         } catch (RemoteException e) {
10738             Log.e(TAG, "Error calling ITelephony#dial", e);
10739         }
10740     }
10741 
10742     /**
10743      * @throws UnsupportedOperationException If the device does not have
10744      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
10745      *
10746      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
10747      * Bundle extras)} instead.
10748      * @hide
10749      */
10750     @Deprecated
10751     @SystemApi
10752     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
10753     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
call(String callingPackage, String number)10754     public void call(String callingPackage, String number) {
10755         try {
10756             ITelephony telephony = getITelephony();
10757             if (telephony != null)
10758                 telephony.call(callingPackage, number);
10759         } catch (RemoteException e) {
10760             Log.e(TAG, "Error calling ITelephony#call", e);
10761         }
10762     }
10763 
10764     /**
10765      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
10766      * @hide
10767      * @removed
10768      */
10769     @Deprecated
10770     @SystemApi
10771     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()10772     public boolean endCall() {
10773         return false;
10774     }
10775 
10776     /**
10777      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
10778      * @hide
10779      * @removed
10780      */
10781     @Deprecated
10782     @SystemApi
10783     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()10784     public void answerRingingCall() {
10785         // No-op
10786     }
10787 
10788     /**
10789      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
10790      * @hide
10791      */
10792     @Deprecated
10793     @SystemApi
10794     @SuppressLint("RequiresPermission")
silenceRinger()10795     public void silenceRinger() {
10796         // No-op
10797     }
10798 
10799     /**
10800    * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
10801      * @hide
10802      */
10803     @Deprecated
10804     @SystemApi
10805     @RequiresPermission(anyOf = {
10806             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10807             android.Manifest.permission.READ_PHONE_STATE
10808     })
isOffhook()10809     public boolean isOffhook() {
10810         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
10811         return tm.isInCall();
10812     }
10813 
10814     /**
10815      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
10816      * @hide
10817      */
10818     @Deprecated
10819     @SystemApi
10820     @RequiresPermission(anyOf = {
10821             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10822             android.Manifest.permission.READ_PHONE_STATE
10823     })
isRinging()10824     public boolean isRinging() {
10825         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
10826         return tm.isRinging();
10827     }
10828 
10829     /**
10830      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
10831      * @hide
10832      */
10833     @Deprecated
10834     @SystemApi
10835     @RequiresPermission(anyOf = {
10836             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10837             android.Manifest.permission.READ_PHONE_STATE
10838     })
isIdle()10839     public boolean isIdle() {
10840         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
10841         return !tm.isInCall();
10842     }
10843 
10844     /**
10845      * @throws UnsupportedOperationException If the device does not have
10846      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10847      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
10848      * @hide
10849      */
10850     @Deprecated
10851     @SystemApi
10852     @RequiresPermission(anyOf = {
10853             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10854             android.Manifest.permission.READ_PHONE_STATE
10855     })
10856     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isRadioOn()10857     public boolean isRadioOn() {
10858         try {
10859             ITelephony telephony = getITelephony();
10860             if (telephony != null)
10861                 return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
10862         } catch (RemoteException e) {
10863             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
10864         }
10865         return false;
10866     }
10867 
10868     /**
10869      * @throws UnsupportedOperationException If the device does not have
10870      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10871      * @hide
10872      */
10873     @SystemApi
10874     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10875     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyPin(String pin)10876     public boolean supplyPin(String pin) {
10877         try {
10878             ITelephony telephony = getITelephony();
10879             if (telephony != null)
10880                 return telephony.supplyPinForSubscriber(getSubId(), pin);
10881         } catch (RemoteException e) {
10882             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
10883         }
10884         return false;
10885     }
10886 
10887     /**
10888      * @throws UnsupportedOperationException If the device does not have
10889      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10890      * @hide
10891      */
10892     @SystemApi
10893     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10894     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyPuk(String puk, String pin)10895     public boolean supplyPuk(String puk, String pin) {
10896         try {
10897             ITelephony telephony = getITelephony();
10898             if (telephony != null)
10899                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
10900         } catch (RemoteException e) {
10901             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
10902         }
10903         return false;
10904     }
10905 
10906     /**
10907      * @throws UnsupportedOperationException If the device does not have
10908      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10909      *
10910      * @deprecated use {@link #supplyIccLockPin(String)} instead.
10911      * @hide
10912      */
10913     @SystemApi
10914     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10915     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
10916     @Deprecated
supplyPinReportResult(String pin)10917     public int[] supplyPinReportResult(String pin) {
10918         try {
10919             ITelephony telephony = getITelephony();
10920             if (telephony != null)
10921                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
10922         } catch (RemoteException e) {
10923             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
10924         }
10925         return new int[0];
10926     }
10927 
10928     /**
10929      * @throws UnsupportedOperationException If the device does not have
10930      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10931      *
10932      * @deprecated use {@link #supplyIccLockPuk(String, String)} instead.
10933      * @hide
10934      */
10935     @SystemApi
10936     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10937     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
10938     @Deprecated
supplyPukReportResult(String puk, String pin)10939     public int[] supplyPukReportResult(String puk, String pin) {
10940         try {
10941             ITelephony telephony = getITelephony();
10942             if (telephony != null)
10943                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
10944         } catch (RemoteException e) {
10945             Log.e(TAG, "Error calling ITelephony#supplyPukReportResultForSubscriber", e);
10946         }
10947         return new int[0];
10948     }
10949 
10950     /**
10951      * Supplies a PIN to unlock the ICC and returns the corresponding {@link PinResult}.
10952      * Used when the user enters their ICC unlock PIN to attempt an unlock.
10953      *
10954      * @param pin The user entered PIN.
10955      * @return The result of the PIN.
10956      * @throws SecurityException if the caller doesn't have the permission.
10957      * @throws IllegalStateException if the Telephony process is not currently available.
10958      *
10959      * <p>Requires Permission:
10960      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10961      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10962      *
10963      * @throws UnsupportedOperationException If the device does not have
10964      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10965      * @hide
10966      */
10967     @SystemApi
10968     @NonNull
10969     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10970     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyIccLockPin(@onNull String pin)10971     public PinResult supplyIccLockPin(@NonNull String pin) {
10972         try {
10973             ITelephony telephony = getITelephony();
10974             if (telephony != null) {
10975                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
10976                 return new PinResult(result[0], result[1]);
10977             } else {
10978                 throw new IllegalStateException("telephony service is null.");
10979             }
10980         } catch (RemoteException e) {
10981             Log.e(TAG, "Error calling ITelephony#supplyIccLockPin", e);
10982             e.rethrowFromSystemServer();
10983         }
10984         return PinResult.getDefaultFailedResult();
10985     }
10986 
10987     /**
10988      * Supplies a PUK and PIN to unlock the ICC and returns the corresponding {@link PinResult}.
10989      * Used when the user enters their ICC unlock PUK and PIN to attempt an unlock.
10990      *
10991      * @param puk The product unlocking key.
10992      * @param pin The user entered PIN.
10993      * @return The result of the PUK and PIN.
10994      * @throws SecurityException if the caller doesn't have the permission.
10995      * @throws IllegalStateException if the Telephony process is not currently available.
10996      *
10997      * <p>Requires Permission:
10998      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10999      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11000      *
11001      * @throws UnsupportedOperationException If the device does not have
11002      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11003      * @hide
11004      */
11005     @SystemApi
11006     @NonNull
11007     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11008     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyIccLockPuk(@onNull String puk, @NonNull String pin)11009     public PinResult supplyIccLockPuk(@NonNull String puk, @NonNull String pin) {
11010         try {
11011             ITelephony telephony = getITelephony();
11012             if (telephony != null) {
11013                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
11014                 return new PinResult(result[0], result[1]);
11015             } else {
11016                 throw new IllegalStateException("telephony service is null.");
11017             }
11018         } catch (RemoteException e) {
11019             Log.e(TAG, "Error calling ITelephony#supplyIccLockPuk", e);
11020             e.rethrowFromSystemServer();
11021         }
11022         return PinResult.getDefaultFailedResult();
11023     }
11024 
11025     /**
11026      * Used to notify callers of
11027      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
11028      * network either successfully executes a USSD request, or if there was a failure while
11029      * executing the request.
11030      * <p>
11031      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
11032      * USSD request has succeeded.
11033      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
11034      * USSD request has failed.
11035      */
11036     public static abstract class UssdResponseCallback {
11037        /**
11038         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
11039         * response received from the network.  The calling app can choose to either display the
11040         * response to the user or perform some operation based on the response.
11041         * <p>
11042         * USSD responses are unstructured text and their content is determined by the mobile network
11043         * operator.
11044         *
11045         * @param telephonyManager the TelephonyManager the callback is registered to.
11046         * @param request the USSD request sent to the mobile network.
11047         * @param response the response to the USSD request provided by the mobile network.
11048         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)11049        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
11050                                          String request, CharSequence response) {};
11051 
11052        /**
11053         * Called when a USSD request has failed to complete.
11054         *
11055         * @param telephonyManager the TelephonyManager the callback is registered to.
11056         * @param request the USSD request sent to the mobile network.
11057         * @param failureCode failure code indicating why the request failed.  Will be either
11058         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
11059         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
11060         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)11061        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
11062                                                String request, int failureCode) {};
11063     }
11064 
11065     /**
11066      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
11067      * informs the caller of the response via the supplied {@code callback}.
11068      * <p>Carriers define USSD codes which can be sent by the user to request information such as
11069      * the user's current data balance or minutes balance.
11070      * <p>Requires permission:
11071      * {@link android.Manifest.permission#CALL_PHONE}
11072      * @param ussdRequest the USSD command to be executed.
11073      * @param callback called by the framework to inform the caller of the result of executing the
11074      *                 USSD request (see {@link UssdResponseCallback}).
11075      * @param handler the {@link Handler} to run the request on.
11076      *
11077      * @throws UnsupportedOperationException If the device does not have
11078      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11079      */
11080     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
11081     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)11082     public void sendUssdRequest(String ussdRequest,
11083                                 final UssdResponseCallback callback, Handler handler) {
11084         checkNotNull(callback, "UssdResponseCallback cannot be null.");
11085         final TelephonyManager telephonyManager = this;
11086 
11087         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
11088             @Override
11089             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
11090                 Rlog.d(TAG, "USSD:" + resultCode);
11091                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
11092                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE, android.telephony.UssdResponse.class);
11093 
11094                 if (resultCode == USSD_RETURN_SUCCESS) {
11095                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
11096                             response.getReturnMessage());
11097                 } else {
11098                     callback.onReceiveUssdResponseFailed(telephonyManager,
11099                             response.getUssdRequest(), resultCode);
11100                 }
11101             }
11102         };
11103 
11104         try {
11105             ITelephony telephony = getITelephony();
11106             if (telephony != null) {
11107                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
11108             }
11109         } catch (RemoteException e) {
11110             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
11111             UssdResponse response = new UssdResponse(ussdRequest, "");
11112             Bundle returnData = new Bundle();
11113             returnData.putParcelable(USSD_RESPONSE, response);
11114             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
11115         }
11116     }
11117 
11118     /**
11119      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
11120      * voice and data simultaneously. This can change based on location or network condition.
11121      *
11122      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
11123      *
11124      * @throws UnsupportedOperationException If the device does not have
11125      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11126      */
11127     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isConcurrentVoiceAndDataSupported()11128     public boolean isConcurrentVoiceAndDataSupported() {
11129         try {
11130             ITelephony telephony = getITelephony();
11131             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
11132                     getSubId()));
11133         } catch (RemoteException e) {
11134             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
11135         }
11136         return false;
11137     }
11138 
11139     /**
11140      * @throws UnsupportedOperationException If the device does not have
11141      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11142      * @hide */
11143     @SystemApi
11144     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11145     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
handlePinMmi(String dialString)11146     public boolean handlePinMmi(String dialString) {
11147         try {
11148             ITelephony telephony = getITelephony();
11149             if (telephony != null)
11150                 return telephony.handlePinMmi(dialString);
11151         } catch (RemoteException e) {
11152             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
11153         }
11154         return false;
11155     }
11156 
11157     /**
11158      * @throws UnsupportedOperationException If the device does not have
11159      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11160      * @hide
11161      */
11162     @SystemApi
11163     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11164     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
handlePinMmiForSubscriber(int subId, String dialString)11165     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
11166         try {
11167             ITelephony telephony = getITelephony();
11168             if (telephony != null)
11169                 return telephony.handlePinMmiForSubscriber(subId, dialString);
11170         } catch (RemoteException e) {
11171             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
11172         }
11173         return false;
11174     }
11175 
11176     /**
11177      * @throws UnsupportedOperationException If the device does not have
11178      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11179      * @hide
11180      */
11181     @SystemApi
11182     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11183     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
toggleRadioOnOff()11184     public void toggleRadioOnOff() {
11185         try {
11186             ITelephony telephony = getITelephony();
11187             if (telephony != null)
11188                 telephony.toggleRadioOnOff();
11189         } catch (RemoteException e) {
11190             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
11191         }
11192     }
11193 
11194     /**
11195      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
11196      * {@link clearRadioPowerOffForReason}.
11197      *
11198      * @throws UnsupportedOperationException If the device does not have
11199      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11200      * @hide
11201      */
11202     @Deprecated
11203     @SystemApi
11204     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11205     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadio(boolean turnOn)11206     public boolean setRadio(boolean turnOn) {
11207         boolean result = true;
11208         try {
11209             if (turnOn) {
11210                 clearRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11211             } else {
11212                 requestRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11213             }
11214         } catch (Exception e) {
11215             String calledFunction =
11216                     turnOn ? "clearRadioPowerOffForReason" : "requestRadioPowerOffForReason";
11217             Log.e(TAG, "Error calling " + calledFunction, e);
11218             result = false;
11219         }
11220         return result;
11221     }
11222 
11223     /**
11224      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
11225      * {@link clearRadioPowerOffForReason}.
11226      *
11227      * @throws UnsupportedOperationException If the device does not have
11228      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11229      * @hide
11230      */
11231     @Deprecated
11232     @SystemApi
11233     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11234     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadioPower(boolean turnOn)11235     public boolean setRadioPower(boolean turnOn) {
11236         boolean result = true;
11237         try {
11238             if (turnOn) {
11239                 clearRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11240             } else {
11241                 requestRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11242             }
11243         } catch (Exception e) {
11244             String calledFunction =
11245                     turnOn ? "clearRadioPowerOffForReason" : "requestRadioPowerOffForReason";
11246             Log.e(TAG, "Error calling " + calledFunction, e);
11247             result = false;
11248         }
11249         return result;
11250     }
11251 
11252     /**
11253      * Vote on powering off the radio for a reason. The radio will be turned on only when there is
11254      * no reason to power it off. When any of the voters want to power it off, it will be turned
11255      * off. In case of emergency, the radio will be turned on even if there are some reasons for
11256      * powering it off, and these radio off votes will be cleared.
11257      * <p>
11258      * Each API call is for one reason. However, an app can call the API multiple times for multiple
11259      * reasons. Multiple apps can vote for the same reason but the vote of one app does not affect
11260      * the vote of another app.
11261      * <p>
11262      * Each app is responsible for its vote. A powering-off vote for a reason of an app will be
11263      * maintained until it is cleared by calling {@link #clearRadioPowerOffForReason(int)} for that
11264      * reason by the app, or an emergency call is made, or the device is rebooted. When an app
11265      * comes backup from a crash, it needs to make sure if its vote is as expected. An app can use
11266      * the API {@link #getRadioPowerOffReasons()} to check its votes. Votes won't be removed when
11267      * an app crashes.
11268      * <p>
11269      * User setting for power state is persistent across device reboots. This applies to all users,
11270      * callers must be careful to update the off reasons when the current user changes.
11271      *
11272      * @param reason The reason for powering off radio.
11273      * @throws SecurityException if the caller does not have MODIFY_PHONE_STATE permission.
11274      * @throws IllegalStateException if the Telephony service is not currently available.
11275      *
11276      * @throws UnsupportedOperationException If the device does not have
11277      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11278      * @hide
11279      */
11280     @SystemApi
11281     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11282     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestRadioPowerOffForReason(@adioPowerReason int reason)11283     public void requestRadioPowerOffForReason(@RadioPowerReason int reason) {
11284         try {
11285             ITelephony telephony = getITelephony();
11286             if (telephony != null) {
11287                 if (!telephony.requestRadioPowerOffForReason(getSubId(), reason)) {
11288                     throw new IllegalStateException("Telephony service is not available.");
11289                 }
11290             } else {
11291                 throw new IllegalStateException("Telephony service is null.");
11292             }
11293         } catch (RemoteException e) {
11294             Log.e(TAG, "Error calling ITelephony#requestRadioPowerOffForReason", e);
11295             e.rethrowAsRuntimeException();
11296         }
11297     }
11298 
11299     /**
11300      * Remove the vote on powering off the radio for a reason, as requested by
11301      * {@link requestRadioPowerOffForReason}.
11302      *
11303      * @param reason The reason for powering off radio.
11304      * @throws SecurityException if the caller does not have MODIFY_PHONE_STATE permission.
11305      * @throws IllegalStateException if the Telephony service is not currently available.
11306      *
11307      * @throws UnsupportedOperationException If the device does not have
11308      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11309      * @hide
11310      */
11311     @SystemApi
11312     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11313     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
clearRadioPowerOffForReason(@adioPowerReason int reason)11314     public void clearRadioPowerOffForReason(@RadioPowerReason int reason) {
11315         try {
11316             ITelephony telephony = getITelephony();
11317             if (telephony != null) {
11318                 if (!telephony.clearRadioPowerOffForReason(getSubId(), reason)) {
11319                     throw new IllegalStateException("Telephony service is not available.");
11320                 }
11321             } else {
11322                 throw new IllegalStateException("Telephony service is null.");
11323             }
11324         } catch (RemoteException e) {
11325             Log.e(TAG, "Error calling ITelephony#clearRadioPowerOffForReason", e);
11326             e.rethrowAsRuntimeException();
11327         }
11328     }
11329 
11330     /**
11331      * Get reasons for powering off radio of the calling app, as requested by
11332      * {@link #requestRadioPowerOffForReason(int)}.
11333      *
11334      * @return Set of reasons for powering off radio of the calling app.
11335      * @throws SecurityException if the caller does not have READ_PRIVILEGED_PHONE_STATE permission.
11336      * @throws IllegalStateException if the Telephony service is not currently available.
11337      *
11338      * @throws UnsupportedOperationException If the device does not have
11339      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11340      * @hide
11341      */
11342     @SystemApi
11343     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11344     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
11345     @NonNull
getRadioPowerOffReasons()11346     public Set<Integer> getRadioPowerOffReasons() {
11347         Set<Integer> result = new HashSet<>();
11348         try {
11349             ITelephony telephony = getITelephony();
11350             if (telephony != null) {
11351                 result.addAll(telephony.getRadioPowerOffReasons(getSubId(),
11352                         mContext.getOpPackageName(), mContext.getAttributionTag()));
11353             } else {
11354                 throw new IllegalStateException("Telephony service is null.");
11355             }
11356         } catch (RemoteException e) {
11357             Log.e(TAG, "Error calling ITelephony#getRadioPowerOffReasons", e);
11358             e.rethrowAsRuntimeException();
11359         }
11360         return result;
11361     }
11362 
11363     /**
11364      * Shut down all the live radios over all the slot indexes.
11365      *
11366      * <p>To know when the radio has completed powering off, use
11367      * {@link TelephonyCallback.ServiceStateListener}.
11368      *
11369      * @throws UnsupportedOperationException If the device does not have
11370      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11371      * @hide
11372      */
11373     @SystemApi
11374     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11375     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
shutdownAllRadios()11376     public void shutdownAllRadios() {
11377         try {
11378             ITelephony telephony = getITelephony();
11379             if (telephony != null) {
11380                 telephony.shutdownMobileRadios();
11381             }
11382         } catch (RemoteException e) {
11383             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
11384             e.rethrowAsRuntimeException();
11385         }
11386     }
11387 
11388     /**
11389      * Check if any radio is on over all the slot indexes.
11390      *
11391      * @return {@code true} if any radio is on over any slot index.
11392      *
11393      * @throws UnsupportedOperationException If the device does not have
11394      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11395      * @hide
11396      */
11397     @SystemApi
11398     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11399     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isAnyRadioPoweredOn()11400     public boolean isAnyRadioPoweredOn() {
11401         try {
11402             ITelephony telephony = getITelephony();
11403             if (telephony != null) {
11404                 return telephony.needMobileRadioShutdown();
11405             }
11406         } catch (RemoteException e) {
11407             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
11408             e.rethrowAsRuntimeException();
11409         }
11410         return false;
11411     }
11412 
11413     /**
11414      * Radio explicitly powered off (e.g, airplane mode).
11415      * @hide
11416      */
11417     @SystemApi
11418     public static final int RADIO_POWER_OFF = 0;
11419 
11420     /**
11421      * Radio power is on.
11422      * @hide
11423      */
11424     @SystemApi
11425     public static final int RADIO_POWER_ON = 1;
11426 
11427     /**
11428      * Radio power unavailable (eg, modem resetting or not booted).
11429      * @hide
11430      */
11431     @SystemApi
11432     public static final int RADIO_POWER_UNAVAILABLE = 2;
11433 
11434     /**
11435      * @return current modem radio state.
11436      *
11437      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
11438      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
11439      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11440      *
11441      * @throws UnsupportedOperationException If the device does not have
11442      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11443      * @hide
11444      */
11445     @SystemApi
11446     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11447             android.Manifest.permission.READ_PHONE_STATE})
11448     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getRadioPowerState()11449     public @RadioPowerState int getRadioPowerState() {
11450         try {
11451             ITelephony telephony = getITelephony();
11452             if (telephony != null) {
11453                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
11454                         mContext.getAttributionTag());
11455             }
11456         } catch (RemoteException ex) {
11457             // This could happen if binder process crashes.
11458         }
11459         return RADIO_POWER_UNAVAILABLE;
11460     }
11461 
11462     /**
11463      * This method should not be used due to privacy and stability concerns.
11464      *
11465      * @hide
11466      */
11467     @SystemApi
updateServiceLocation()11468     public void updateServiceLocation() {
11469         Log.e(TAG, "Do not call TelephonyManager#updateServiceLocation()");
11470     }
11471 
11472     /**
11473      * @throws UnsupportedOperationException If the device does not have
11474      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11475      * @hide
11476      */
11477     @SystemApi
11478     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11479     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
enableDataConnectivity()11480     public boolean enableDataConnectivity() {
11481         try {
11482             ITelephony telephony = getITelephony();
11483             if (telephony != null)
11484                 return telephony.enableDataConnectivity(getOpPackageName());
11485         } catch (RemoteException e) {
11486             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
11487         }
11488         return false;
11489     }
11490 
11491     /**
11492      * @throws UnsupportedOperationException If the device does not have
11493      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11494      * @hide
11495      */
11496     @SystemApi
11497     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11498     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
disableDataConnectivity()11499     public boolean disableDataConnectivity() {
11500         try {
11501             ITelephony telephony = getITelephony();
11502             if (telephony != null)
11503                 return telephony.disableDataConnectivity(getOpPackageName());
11504         } catch (RemoteException e) {
11505             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
11506         }
11507         return false;
11508     }
11509 
11510     /**
11511      * @throws UnsupportedOperationException If the device does not have
11512      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11513      * @hide
11514      */
11515     @SystemApi
11516     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataConnectivityPossible()11517     public boolean isDataConnectivityPossible() {
11518         try {
11519             ITelephony telephony = getITelephony();
11520             if (telephony != null)
11521                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
11522                         .getActiveDataSubscriptionId()));
11523         } catch (RemoteException e) {
11524             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
11525         }
11526         return false;
11527     }
11528 
11529     /**
11530      * @throws UnsupportedOperationException If the device does not have
11531      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11532      * @hide
11533      */
11534     @SystemApi
11535     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
needsOtaServiceProvisioning()11536     public boolean needsOtaServiceProvisioning() {
11537         try {
11538             ITelephony telephony = getITelephony();
11539             if (telephony != null)
11540                 return telephony.needsOtaServiceProvisioning();
11541         } catch (RemoteException e) {
11542             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
11543         }
11544         return false;
11545     }
11546 
11547     /**
11548      * Get the mobile provisioning url that is used to launch a browser to allow users to manage
11549      * their mobile plan.
11550      *
11551      * <p>Requires Permission:
11552      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}.
11553      *
11554      * TODO: The legacy design only supports single sim design. Ideally, this should support
11555      * multi-sim design in current world.
11556      *
11557      * {@hide}
11558      */
11559     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMobileProvisioningUrl()11560     public @Nullable String getMobileProvisioningUrl() {
11561         try {
11562             final ITelephony service = getITelephony();
11563             if (service != null) {
11564                 return service.getMobileProvisioningUrl();
11565             } else {
11566                 throw new IllegalStateException("telephony service is null.");
11567             }
11568         } catch (RemoteException ex) {
11569             Rlog.e(TAG, "Telephony#getMobileProvisioningUrl RemoteException" + ex);
11570         }
11571         return null;
11572     }
11573 
11574     /**
11575      * Turns mobile data on or off.
11576      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
11577      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11578      *
11579      * <p>Requires Permission:
11580      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11581      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11582      *
11583      * @param enable Whether to enable mobile data.
11584      * @throws UnsupportedOperationException If the device does not have
11585      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11586      * @deprecated use setDataEnabledForReason with reason DATA_ENABLED_REASON_USER instead.
11587      *
11588      */
11589     @Deprecated
11590     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
11591     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11592     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabled(boolean enable)11593     public void setDataEnabled(boolean enable) {
11594         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
11595     }
11596 
11597     /**
11598      * @throws UnsupportedOperationException If the device does not have
11599      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11600      * @hide
11601      * @deprecated use {@link #setDataEnabledForReason(int, boolean)} instead.
11602     */
11603     @SystemApi
11604     @Deprecated
11605     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11606     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabled(int subId, boolean enable)11607     public void setDataEnabled(int subId, boolean enable) {
11608         try {
11609             setDataEnabledForReason(subId, DATA_ENABLED_REASON_USER, enable);
11610         } catch (RuntimeException e) {
11611             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
11612         }
11613     }
11614 
11615     /**
11616      * @deprecated use {@link #isDataEnabled()} instead.
11617      *
11618      * @throws UnsupportedOperationException If the device does not have
11619      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11620      * @hide
11621      */
11622     @SystemApi
11623     @Deprecated
11624     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataEnabled()11625     public boolean getDataEnabled() {
11626         return isDataEnabled();
11627     }
11628 
11629     /**
11630      * Returns whether mobile data is enabled or not per user setting. There are other factors
11631      * that could disable mobile data, but they are not considered here.
11632      *
11633      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
11634      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11635      *
11636      * <p>Requires one of the following permissions:
11637      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
11638      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or
11639      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
11640      * READ_BASIC_PHONE_STATE} or that the calling app has carrier
11641      * privileges (see {@link #hasCarrierPrivileges}).
11642      *
11643      * <p>Note that this does not take into account any data restrictions that may be present on the
11644      * calling app. Such restrictions may be inspected with
11645      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
11646      *
11647      * @return true if mobile data is enabled.
11648      *
11649      * @throws UnsupportedOperationException If the device does not have
11650      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11651      */
11652     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
11653             android.Manifest.permission.MODIFY_PHONE_STATE,
11654             android.Manifest.permission.READ_PHONE_STATE,
11655             android.Manifest.permission.READ_BASIC_PHONE_STATE})
11656     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabled()11657     public boolean isDataEnabled() {
11658         try {
11659             return isDataEnabledForReason(DATA_ENABLED_REASON_USER);
11660         } catch (IllegalStateException ise) {
11661             // TODO(b/176163590): Remove this catch once TelephonyManager is booting safely.
11662             Log.e(TAG, "Error calling #isDataEnabled, returning default (false).", ise);
11663             return false;
11664         }
11665     }
11666 
11667     /**
11668      * Returns whether mobile data roaming is enabled on the subscription.
11669      *
11670      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11671      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11672      *
11673      * <p>Requires one of the following permissions:
11674      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
11675      * {@link android.Manifest.permission#READ_PHONE_STATE} or
11676      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
11677      * READ_BASIC_PHONE_STATE} or that the calling app
11678      * has carrier privileges (see {@link #hasCarrierPrivileges}).
11679      *
11680      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
11681      *
11682      * @throws UnsupportedOperationException If the device does not have
11683      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11684      * {@code false}.
11685      */
11686     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
11687             android.Manifest.permission.READ_PHONE_STATE,
11688             android.Manifest.permission.READ_BASIC_PHONE_STATE})
11689     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataRoamingEnabled()11690     public boolean isDataRoamingEnabled() {
11691         boolean isDataRoamingEnabled = false;
11692         try {
11693             ITelephony telephony = getITelephony();
11694             if (telephony != null) {
11695                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
11696                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
11697             }
11698         } catch (RemoteException e) {
11699             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
11700         }
11701         return isDataRoamingEnabled;
11702     }
11703 
11704     /**
11705      * Gets the roaming mode for CDMA phone.
11706      *
11707      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11708      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11709      *
11710      * @return the CDMA roaming mode.
11711      * @throws SecurityException if the caller does not have the permission.
11712      * @throws IllegalStateException if the Telephony process is not currently available.
11713      *
11714      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
11715      * @see #CDMA_ROAMING_MODE_HOME
11716      * @see #CDMA_ROAMING_MODE_AFFILIATED
11717      * @see #CDMA_ROAMING_MODE_ANY
11718      *
11719      * <p>Requires permission:
11720      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11721      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11722      *
11723      * @throws UnsupportedOperationException If the device does not have
11724      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
11725      * @hide
11726      */
11727     @SystemApi
11728     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11729     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaRoamingMode()11730     public @CdmaRoamingMode int getCdmaRoamingMode() {
11731         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
11732         try {
11733             ITelephony telephony = getITelephony();
11734             if (telephony != null) {
11735                 mode = telephony.getCdmaRoamingMode(getSubId());
11736             } else {
11737                 throw new IllegalStateException("telephony service is null.");
11738             }
11739         } catch (RemoteException ex) {
11740             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
11741             ex.rethrowFromSystemServer();
11742         }
11743         return mode;
11744     }
11745 
11746     /**
11747      * Sets the roaming mode for CDMA phone to the given mode {@code mode}. If the phone is not
11748      * CDMA capable, this method throws an IllegalStateException.
11749      *
11750      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11751      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11752      *
11753      * @param mode CDMA roaming mode.
11754      * @throws SecurityException if the caller does not have the permission.
11755      * @throws IllegalStateException if the Telephony process or radio is not currently available,
11756      *         the device is not CDMA capable, or the request fails.
11757      *
11758      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
11759      * @see #CDMA_ROAMING_MODE_HOME
11760      * @see #CDMA_ROAMING_MODE_AFFILIATED
11761      * @see #CDMA_ROAMING_MODE_ANY
11762      *
11763      * <p>Requires Permission:
11764      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11765      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11766      *
11767      * @throws UnsupportedOperationException If the device does not have
11768      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
11769      * @hide
11770      */
11771     @SystemApi
11772     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11773     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
setCdmaRoamingMode(@dmaRoamingMode int mode)11774     public void setCdmaRoamingMode(@CdmaRoamingMode int mode) {
11775         if (getPhoneType() != PHONE_TYPE_CDMA) {
11776             throw new IllegalStateException("Phone does not support CDMA.");
11777         }
11778         try {
11779             ITelephony telephony = getITelephony();
11780             if (telephony != null) {
11781                 boolean result = telephony.setCdmaRoamingMode(getSubId(), mode);
11782                 if (!result) throw new IllegalStateException("radio is unavailable.");
11783             } else {
11784                 throw new IllegalStateException("telephony service is null.");
11785             }
11786         } catch (RemoteException ex) {
11787             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
11788             ex.rethrowFromSystemServer();
11789         }
11790     }
11791 
11792     /** @hide */
11793     @IntDef(prefix = { "CDMA_SUBSCRIPTION_" }, value = {
11794             CDMA_SUBSCRIPTION_UNKNOWN,
11795             CDMA_SUBSCRIPTION_RUIM_SIM,
11796             CDMA_SUBSCRIPTION_NV
11797     })
11798     @Retention(RetentionPolicy.SOURCE)
11799     public @interface CdmaSubscription{}
11800 
11801     /**
11802      * Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
11803      * @hide
11804      */
11805     @SystemApi
11806     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
11807 
11808     /**
11809      * Used for CDMA subscription mode: RUIM/SIM (default)
11810      * @hide
11811      */
11812     @SystemApi
11813     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
11814 
11815     /**
11816      * Used for CDMA subscription mode: NV -> non-volatile memory
11817      * @hide
11818      */
11819     @SystemApi
11820     public static final int CDMA_SUBSCRIPTION_NV       = 1;
11821 
11822     /**
11823      * Gets the subscription mode for CDMA phone.
11824      *
11825      * @return the CDMA subscription mode.
11826      * @throws SecurityException if the caller does not have the permission.
11827      * @throws IllegalStateException if the Telephony process or radio is not currently available.
11828      *
11829      * @see #CDMA_SUBSCRIPTION_UNKNOWN
11830      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
11831      * @see #CDMA_SUBSCRIPTION_NV
11832      *
11833      * <p>Requires Permission:
11834      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11835      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
11836      *
11837      * @throws UnsupportedOperationException If the device does not have
11838      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
11839      * @hide
11840      */
11841     @SystemApi
11842     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11843     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaSubscriptionMode()11844     public @CdmaSubscription int getCdmaSubscriptionMode() {
11845         int mode = CDMA_SUBSCRIPTION_RUIM_SIM;
11846         try {
11847             ITelephony telephony = getITelephony();
11848             if (telephony != null) {
11849                 mode = telephony.getCdmaSubscriptionMode(getSubId());
11850             } else {
11851                 throw new IllegalStateException("telephony service is null.");
11852             }
11853         } catch (RemoteException ex) {
11854             Log.e(TAG, "Error calling ITelephony#getCdmaSubscriptionMode", ex);
11855             ex.rethrowFromSystemServer();
11856         }
11857         return mode;
11858     }
11859 
11860     /**
11861      * Sets the subscription mode for CDMA phone to the given mode {@code mode}. If the phone is not
11862      * CDMA capable, this method throws an IllegalStateException.
11863      *
11864      * @param mode CDMA subscription mode.
11865      * @throws SecurityException if the caller does not have the permission.
11866      * @throws IllegalStateException if the Telephony process or radio is not currently available,
11867      *         the device is not CDMA capable, or the request fails.
11868      *
11869      * @see #CDMA_SUBSCRIPTION_UNKNOWN
11870      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
11871      * @see #CDMA_SUBSCRIPTION_NV
11872      *
11873      * <p>Requires Permission:
11874      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11875      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11876      *
11877      * @throws UnsupportedOperationException If the device does not have
11878      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
11879      * @hide
11880      */
11881     @SystemApi
11882     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11883     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
setCdmaSubscriptionMode(@dmaSubscription int mode)11884     public void setCdmaSubscriptionMode(@CdmaSubscription int mode) {
11885         if (getPhoneType() != PHONE_TYPE_CDMA) {
11886             throw new IllegalStateException("Phone does not support CDMA.");
11887         }
11888         try {
11889             ITelephony telephony = getITelephony();
11890             if (telephony != null) {
11891                 boolean result = telephony.setCdmaSubscriptionMode(getSubId(), mode);
11892                 if (!result) throw new IllegalStateException("radio is unavailable.");
11893             } else {
11894                 throw new IllegalStateException("telephony service is null.");
11895             }
11896         } catch (RemoteException ex) {
11897             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
11898             ex.rethrowFromSystemServer();
11899         }
11900     }
11901 
11902     /**
11903      * Enables/Disables the data roaming on the subscription.
11904      *
11905      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11906      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11907      *
11908      * <p> Requires permission:
11909      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
11910      * privileges (see {@link #hasCarrierPrivileges}).
11911      *
11912      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
11913      *
11914      * @throws UnsupportedOperationException If the device does not have
11915      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11916      * @hide
11917      */
11918     @SystemApi
11919     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11920     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataRoamingEnabled(boolean isEnabled)11921     public void setDataRoamingEnabled(boolean isEnabled) {
11922         try {
11923             ITelephony telephony = getITelephony();
11924             if (telephony != null) {
11925                 telephony.setDataRoamingEnabled(
11926                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
11927             }
11928         } catch (RemoteException e) {
11929             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
11930         }
11931     }
11932 
11933     /**
11934      * @throws UnsupportedOperationException If the device does not have
11935      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11936      *
11937      * @deprecated use {@link #isDataEnabled()} instead.
11938      * @hide
11939      */
11940     @Deprecated
11941     @SystemApi
11942     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataEnabled(int subId)11943     public boolean getDataEnabled(int subId) {
11944         try {
11945             return isDataEnabledForReason(subId, DATA_ENABLED_REASON_USER);
11946         } catch (RuntimeException e) {
11947             Log.e(TAG, "Error calling isDataEnabledForReason e:" + e);
11948         }
11949         return false;
11950     }
11951 
11952     /**
11953      * @throws UnsupportedOperationException If the device does not have
11954      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
11955      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
11956      * instead.
11957      * @hide
11958      */
11959     @Deprecated
11960     @SystemApi
11961     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11962     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
enableVideoCalling(boolean enable)11963     public void enableVideoCalling(boolean enable) {
11964         try {
11965             ITelephony telephony = getITelephony();
11966             if (telephony != null)
11967                 telephony.enableVideoCalling(enable);
11968         } catch (RemoteException e) {
11969             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
11970         }
11971     }
11972 
11973     /**
11974      * @throws UnsupportedOperationException If the device does not have
11975      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
11976      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
11977      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
11978      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
11979      * determine if video calling is capable.
11980      * @hide
11981      */
11982     @Deprecated
11983     @SystemApi
11984     @RequiresPermission(anyOf = {
11985             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11986             android.Manifest.permission.READ_PHONE_STATE
11987     })
11988     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
isVideoCallingEnabled()11989     public boolean isVideoCallingEnabled() {
11990         try {
11991             ITelephony telephony = getITelephony();
11992             if (telephony != null)
11993                 return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
11994         } catch (RemoteException e) {
11995             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
11996         }
11997         return false;
11998     }
11999 
12000     /**
12001      * Whether the device supports configuring the DTMF tone length.
12002      *
12003      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
12004      *
12005      * @throws UnsupportedOperationException If the device does not have
12006      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
12007      */
12008     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
canChangeDtmfToneLength()12009     public boolean canChangeDtmfToneLength() {
12010         try {
12011             ITelephony telephony = getITelephony();
12012             if (telephony != null) {
12013                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
12014                         getAttributionTag());
12015             }
12016         } catch (RemoteException e) {
12017             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
12018         } catch (SecurityException e) {
12019             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
12020         }
12021         return false;
12022     }
12023 
12024     /**
12025      * Whether the device is a world phone.
12026      *
12027      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
12028      *
12029      * @throws UnsupportedOperationException If the device does not have
12030      *          {@link PackageManager#FEATURE_TELEPHONY}.
12031      */
12032     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
isWorldPhone()12033     public boolean isWorldPhone() {
12034         try {
12035             ITelephony telephony = getITelephony();
12036             if (telephony != null) {
12037                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
12038             }
12039         } catch (RemoteException e) {
12040             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
12041         } catch (SecurityException e) {
12042             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
12043         }
12044         return false;
12045     }
12046 
12047     /**
12048      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
12049      * Whether the phone supports TTY mode.
12050      *
12051      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
12052      *
12053      */
12054     @Deprecated
isTtyModeSupported()12055     public boolean isTtyModeSupported() {
12056         try {
12057             TelecomManager telecomManager = null;
12058             if (mContext != null) {
12059                 telecomManager = mContext.getSystemService(TelecomManager.class);
12060             }
12061             if (telecomManager != null) {
12062                 return telecomManager.isTtySupported();
12063             }
12064         } catch (SecurityException e) {
12065             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
12066         }
12067         return false;
12068     }
12069 
12070     /**
12071      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
12072      * support for the feature and device firmware support.
12073      *
12074      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
12075      *
12076      * @throws UnsupportedOperationException If the device does not have
12077      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
12078      */
12079     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
isRttSupported()12080     public boolean isRttSupported() {
12081         try {
12082             ITelephony telephony = getITelephony();
12083             if (telephony != null) {
12084                 return telephony.isRttSupported(mSubId);
12085             }
12086         } catch (RemoteException e) {
12087             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
12088         } catch (SecurityException e) {
12089             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
12090         }
12091         return false;
12092     }
12093     /**
12094      * Whether the phone supports hearing aid compatibility.
12095      *
12096      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
12097      * otherwise.
12098      *
12099      * @throws UnsupportedOperationException If the device does not have
12100      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
12101      */
12102     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isHearingAidCompatibilitySupported()12103     public boolean isHearingAidCompatibilitySupported() {
12104         try {
12105             ITelephony telephony = getITelephony();
12106             if (telephony != null) {
12107                 return telephony.isHearingAidCompatibilitySupported();
12108             }
12109         } catch (RemoteException e) {
12110             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
12111         } catch (SecurityException e) {
12112             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
12113         }
12114         return false;
12115     }
12116 
12117     /**
12118      * Returns the IMS Registration Status for a particular Subscription ID.
12119      *
12120      * @param subId Subscription ID
12121      * @return true if IMS status is registered, false if the IMS status is not registered or a
12122      * RemoteException occurred.
12123      * Use {@link ImsMmTelManager.RegistrationCallback} instead.
12124      * @hide
12125      */
isImsRegistered(int subId)12126     public boolean isImsRegistered(int subId) {
12127         try {
12128             return getITelephony().isImsRegistered(subId);
12129         } catch (RemoteException | NullPointerException ex) {
12130             return false;
12131         }
12132     }
12133 
12134     /**
12135      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
12136      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
12137      * invalid subscription ID is used during creation, will the default subscription ID will be
12138      * used.
12139      *
12140      * @return true if IMS status is registered, false if the IMS status is not registered or a
12141      * RemoteException occurred.
12142      * @see SubscriptionManager#getDefaultSubscriptionId()
12143      * @hide
12144      */
12145     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()12146     public boolean isImsRegistered() {
12147        try {
12148            return getITelephony().isImsRegistered(getSubId());
12149        } catch (RemoteException | NullPointerException ex) {
12150            return false;
12151        }
12152     }
12153 
12154     /**
12155      * The current status of Voice over LTE for the subscription associated with this instance when
12156      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
12157      * used during creation, the default subscription ID will be used.
12158      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
12159      * @see SubscriptionManager#getDefaultSubscriptionId()
12160      * <p>
12161      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
12162      * @hide
12163      */
12164     @UnsupportedAppUsage
isVolteAvailable()12165     public boolean isVolteAvailable() {
12166         try {
12167             return getITelephony().isAvailable(getSubId(),
12168                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
12169                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
12170         } catch (RemoteException | NullPointerException ex) {
12171             return false;
12172         }
12173     }
12174 
12175     /**
12176      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
12177      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
12178      * used during creation, the default subscription ID will be used. To query the
12179      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
12180      * @return true if VT is available, or false if it is unavailable or unknown.
12181      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
12182      * @hide
12183      */
12184     @UnsupportedAppUsage
isVideoTelephonyAvailable()12185     public boolean isVideoTelephonyAvailable() {
12186         try {
12187             return getITelephony().isVideoTelephonyAvailable(getSubId());
12188         } catch (RemoteException | NullPointerException ex) {
12189             return false;
12190         }
12191     }
12192 
12193     /**
12194      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
12195      * @param subId the subscription ID.
12196      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
12197      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
12198      * @hide
12199      */
12200     @UnsupportedAppUsage
isWifiCallingAvailable()12201     public boolean isWifiCallingAvailable() {
12202        try {
12203            return getITelephony().isWifiCallingAvailable(getSubId());
12204        } catch (RemoteException | NullPointerException ex) {
12205            return false;
12206        }
12207    }
12208 
12209     /**
12210      * The technology that IMS is registered for for the MMTEL feature.
12211      * @param subId subscription ID to get IMS registration technology for.
12212      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
12213      * Valid return results are:
12214      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
12215      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
12216      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_CROSS_SIM} for registration over
12217      *  other sim's internet, or
12218      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
12219      *  result is unavailable.
12220      *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
12221      *  @hide
12222      */
getImsRegTechnologyForMmTel()12223     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
12224         try {
12225             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
12226         } catch (RemoteException ex) {
12227             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
12228         }
12229     }
12230 
12231    /**
12232     * Set TelephonyProperties.icc_operator_numeric for the given phone.
12233     *
12234     * @hide
12235     */
12236     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setSimOperatorNumericForPhone(int phoneId, String numeric)12237     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
12238         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12239             List<String> newList = updateTelephonyProperty(
12240                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
12241             TelephonyProperties.icc_operator_numeric(newList);
12242         }
12243     }
12244 
12245     /**
12246      * Set TelephonyProperties.icc_operator_alpha for the given phone.
12247      *
12248      * @hide
12249      */
12250     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)12251     public void setSimOperatorNameForPhone(int phoneId, String name) {
12252         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12253             List<String> newList = updateTelephonyProperty(
12254                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
12255             TelephonyProperties.icc_operator_alpha(newList);
12256         }
12257     }
12258 
12259    /**
12260     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
12261     *
12262     * @hide
12263     */
setSimCountryIso(String iso)12264     public void setSimCountryIso(String iso) {
12265         int phoneId = getPhoneId();
12266         setSimCountryIsoForPhone(phoneId, iso);
12267     }
12268 
12269    /**
12270     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
12271     *
12272     * @hide
12273     */
12274     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)12275     public void setSimCountryIsoForPhone(int phoneId, String iso) {
12276         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12277             List<String> newList = updateTelephonyProperty(
12278                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
12279             TelephonyProperties.icc_operator_iso_country(newList);
12280         }
12281     }
12282 
12283     /**
12284      * Set TelephonyProperties.sim_state for the default phone.
12285      *
12286      * @hide
12287      */
setSimState(String state)12288     public void setSimState(String state) {
12289         int phoneId = getPhoneId();
12290         setSimStateForPhone(phoneId, state);
12291     }
12292 
12293     /**
12294      * Set TelephonyProperties.sim_state for the given phone.
12295      *
12296      * @hide
12297      */
12298     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)12299     public void setSimStateForPhone(int phoneId, String state) {
12300         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12301             List<String> newList = updateTelephonyProperty(
12302                     TelephonyProperties.sim_state(), phoneId, state);
12303             TelephonyProperties.sim_state(newList);
12304         }
12305     }
12306 
12307     /**
12308      * Powers down the SIM. SIM must be up prior.
12309      * @hide
12310      */
12311     public static final int CARD_POWER_DOWN = 0;
12312 
12313     /**
12314      * Powers up the SIM normally. SIM must be down prior.
12315      * @hide
12316      */
12317     public static final int CARD_POWER_UP = 1;
12318 
12319     /**
12320      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
12321      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
12322      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
12323      * and the SIM card is controlled completely by Telephony sending APDUs
12324      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
12325      * number of card apps will be 0.
12326      * No new error code is generated. Emergency calls are supported in the
12327      * same way as if the SIM card is absent.
12328      * The PASS_THROUGH mode is valid only for the specific card session where it
12329      * is activated, and normal behavior occurs at the next SIM initialization,
12330      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
12331      * is NOT persistent across boots. On reboot, SIM will power up normally.
12332      * @hide
12333      */
12334     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
12335 
12336     /** @hide */
12337     @Retention(RetentionPolicy.SOURCE)
12338     @IntDef(prefix = {"CARD_POWER"},
12339             value = {
12340                     CARD_POWER_DOWN,
12341                     CARD_POWER_UP,
12342                     CARD_POWER_UP_PASS_THROUGH,
12343             })
12344     public @interface SimPowerState {}
12345 
12346     /**
12347      * Set SIM card power state.
12348      *
12349      * @param state  State of SIM (power down, power up, pass through)
12350      * @see #CARD_POWER_DOWN
12351      * @see #CARD_POWER_UP
12352      * @see #CARD_POWER_UP_PASS_THROUGH
12353      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
12354      * broadcasts to determine success or failure and timeout if needed.
12355      *
12356      * @deprecated prefer {@link setSimPowerState(int, Executor, Consumer<Integer>)}.
12357      * There is no guarantee that SIM power changes will trigger ACTION_SIM_STATE_CHANGED on new
12358      * devices.
12359      *
12360      * <p>Requires Permission:
12361      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12362      *
12363      * @throws UnsupportedOperationException If the device does not have
12364      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12365      * {@hide}
12366      **/
12367     @SystemApi
12368     @Deprecated
12369     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12370     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerState(int state)12371     public void setSimPowerState(int state) {
12372         setSimPowerStateForSlot(getSlotIndex(), state);
12373     }
12374 
12375     /**
12376      * Set SIM card power state.
12377      *
12378      * @param slotIndex SIM slot id
12379      * @param state  State of SIM (power down, power up, pass through)
12380      * @see #CARD_POWER_DOWN
12381      * @see #CARD_POWER_UP
12382      * @see #CARD_POWER_UP_PASS_THROUGH
12383      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
12384      * broadcasts to determine success or failure and timeout if needed.
12385      *
12386      * @deprecated prefer {@link setSimPowerStateForSlot(int, int, Executor, Consumer<Integer>)}.
12387      * changes will trigger ACTION_SIM_STATE_CHANGED on new devices.
12388      *
12389      * <p>Requires Permission:
12390      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12391      *
12392      * @throws UnsupportedOperationException If the device does not have
12393      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12394      * {@hide}
12395      **/
12396     @SystemApi
12397     @Deprecated
12398     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12399     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerStateForSlot(int slotIndex, int state)12400     public void setSimPowerStateForSlot(int slotIndex, int state) {
12401         try {
12402             ITelephony telephony = getITelephony();
12403             if (telephony != null) {
12404                 telephony.setSimPowerStateForSlot(slotIndex, state);
12405             }
12406         } catch (RemoteException e) {
12407             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
12408         } catch (SecurityException e) {
12409             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
12410         }
12411     }
12412 
12413     /**
12414      * Set SIM card power state.
12415      *
12416      * @param state  State of SIM (power down, power up, pass through)
12417      * @see #CARD_POWER_DOWN
12418      * @see #CARD_POWER_UP
12419      * @see #CARD_POWER_UP_PASS_THROUGH
12420      * @param executor The executor of where the callback will execute.
12421      * @param callback Callback will be triggered once it succeeds or failed.
12422      * @see #SET_SIM_POWER_STATE_SUCCESS
12423      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
12424      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
12425      * @see #SET_SIM_POWER_STATE_SIM_ERROR
12426      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
12427      * @throws IllegalArgumentException if requested SIM state is invalid
12428      *
12429      * <p>Requires Permission:
12430      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12431      *
12432      * @throws UnsupportedOperationException If the device does not have
12433      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12434      * {@hide}
12435      **/
12436     @SystemApi
12437     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12438     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerState(@imPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)12439     public void setSimPowerState(@SimPowerState int state, @NonNull Executor executor,
12440             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
12441         setSimPowerStateForSlot(getSlotIndex(), state, executor, callback);
12442     }
12443 
12444     /**
12445      * Set SIM card power state.
12446      *
12447      * @param slotIndex SIM slot id
12448      * @param state  State of SIM (power down, power up, pass through)
12449      * @see #CARD_POWER_DOWN
12450      * @see #CARD_POWER_UP
12451      * @see #CARD_POWER_UP_PASS_THROUGH
12452      * @param executor The executor of where the callback will execute.
12453      * @param callback Callback will be triggered once it succeeds or failed.
12454      * @see #SET_SIM_POWER_STATE_SUCCESS
12455      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
12456      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
12457      * @see #SET_SIM_POWER_STATE_SIM_ERROR
12458      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
12459      * @throws IllegalArgumentException if requested SIM state is invalid
12460      *
12461      * <p>Requires Permission:
12462      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12463      *
12464      * @throws UnsupportedOperationException If the device does not have
12465      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12466      * {@hide}
12467      **/
12468     @SystemApi
12469     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12470     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerStateForSlot(int slotIndex, @SimPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)12471     public void setSimPowerStateForSlot(int slotIndex, @SimPowerState int state,
12472             @NonNull Executor executor,
12473             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
12474         if (state != CARD_POWER_DOWN && state != CARD_POWER_UP
12475                 && state != CARD_POWER_UP_PASS_THROUGH) {
12476             throw new IllegalArgumentException("requested SIM state is invalid");
12477         }
12478         try {
12479             ITelephony telephony = getITelephony();
12480             if (telephony == null) throw new IllegalStateException("Telephony is null.");
12481 
12482             IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
12483                 @Override
12484                 public void accept(int result) {
12485                     executor.execute(() ->
12486                             Binder.withCleanCallingIdentity(() -> callback.accept(result)));
12487                 }
12488             };
12489             if (telephony == null) {
12490                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
12491                     throw new IllegalStateException("Telephony is null");
12492                 } else {
12493                     return;
12494                 }
12495             }
12496             telephony.setSimPowerStateForSlotWithCallback(slotIndex, state, internalCallback);
12497         } catch (RemoteException e) {
12498             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
12499             runOnBackgroundThread(() -> executor.execute(
12500                     () -> callback.accept(SET_SIM_POWER_STATE_MODEM_ERROR)));
12501         } catch (SecurityException e) {
12502             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot",
12503                     e);
12504         }
12505     }
12506 
12507     /**
12508      * Set baseband version by phone id.
12509      *
12510      * @param phoneId for which baseband version is set
12511      * @param version baseband version
12512      * @hide
12513      */
12514     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)12515     public void setBasebandVersionForPhone(int phoneId, String version) {
12516         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12517             List<String> newList = updateTelephonyProperty(
12518                     TelephonyProperties.baseband_version(), phoneId, version);
12519             TelephonyProperties.baseband_version(newList);
12520         }
12521     }
12522 
12523     /**
12524      * Get baseband version for the default phone.
12525      *
12526      * @return baseband version.
12527      * @hide
12528      */
getBasebandVersion()12529     public String getBasebandVersion() {
12530         int phoneId = getPhoneId();
12531         return getBasebandVersionForPhone(phoneId);
12532     }
12533 
12534     /**
12535      * Get baseband version by phone id.
12536      *
12537      * @return baseband version.
12538      * @hide
12539      */
getBasebandVersionForPhone(int phoneId)12540     public String getBasebandVersionForPhone(int phoneId) {
12541         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
12542     }
12543 
12544     /**
12545      * Set phone type by phone id.
12546      *
12547      * @param phoneId for which phone type is set
12548      * @param type phone type
12549      *
12550      * @hide
12551      */
12552     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)12553     public void setPhoneType(int phoneId, int type) {
12554         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12555             List<Integer> newList = updateTelephonyProperty(
12556                     TelephonyProperties.current_active_phone(), phoneId, type);
12557             TelephonyProperties.current_active_phone(newList);
12558         }
12559     }
12560 
12561     /**
12562      * Get OTASP number schema by phone id.
12563      *
12564      * @param phoneId for which OTA SP number schema is get
12565      * @param defaultValue default value
12566      * @return OTA SP number schema
12567      *
12568      * @hide
12569      */
12570     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)12571     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
12572         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12573             return getTelephonyProperty(
12574                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
12575         }
12576 
12577         return defaultValue;
12578     }
12579 
12580     /**
12581      * Get SMS receive capable from system property by phone id.
12582      *
12583      * @param phoneId for which SMS receive capable is get
12584      * @param defaultValue default value
12585      * @return SMS receive capable
12586      *
12587      * @hide
12588      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)12589     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
12590         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12591             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
12592         }
12593 
12594         return defaultValue;
12595     }
12596 
12597     /**
12598      * Get SMS send capable from system property by phone id.
12599      *
12600      * @param phoneId for which SMS send capable is get
12601      * @param defaultValue default value
12602      * @return SMS send capable
12603      *
12604      * @hide
12605      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)12606     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
12607         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12608             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
12609         }
12610 
12611         return defaultValue;
12612     }
12613 
12614     /**
12615      * Get the component name of the default app to direct respond-via-message intent for the
12616      * user associated with this subscription, update the cache if there is no respond-via-message
12617      * application currently configured for this user.
12618      * @return component name of the app and class to direct Respond Via Message intent to, or
12619      * {@code null} if the functionality is not supported.
12620      *
12621      * @throws UnsupportedOperationException If the device does not have
12622      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
12623      * @hide
12624      */
12625     @SystemApi
12626     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
12627     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getAndUpdateDefaultRespondViaMessageApplication()12628     public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
12629         try {
12630             ITelephony telephony = getITelephony();
12631             if (telephony != null) {
12632                 return telephony.getDefaultRespondViaMessageApplication(getSubId(), true);
12633             }
12634         } catch (RemoteException e) {
12635             Log.e(TAG, "Error in getAndUpdateDefaultRespondViaMessageApplication: " + e);
12636         }
12637         return null;
12638     }
12639 
12640     /**
12641      * Get the component name of the default app to direct respond-via-message intent for the
12642      * user associated with this subscription.
12643      * @return component name of the app and class to direct Respond Via Message intent to, or
12644      * {@code null} if the functionality is not supported.
12645      *
12646      * @throws UnsupportedOperationException If the device does not have
12647      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
12648      * @hide
12649      */
12650     @SystemApi
12651     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
12652     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getDefaultRespondViaMessageApplication()12653     public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
12654         try {
12655             ITelephony telephony = getITelephony();
12656             if (telephony != null) {
12657                 return telephony.getDefaultRespondViaMessageApplication(getSubId(), false);
12658             }
12659         } catch (RemoteException e) {
12660             Log.e(TAG, "Error in getDefaultRespondViaMessageApplication: " + e);
12661         }
12662         return null;
12663     }
12664 
12665     /**
12666      * Set the alphabetic name of current registered operator.
12667      * @param phoneId which phone you want to set
12668      * @param name the alphabetic name of current registered operator.
12669      * @hide
12670      */
12671     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNameForPhone(int phoneId, String name)12672     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
12673         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12674             List<String> newList = updateTelephonyProperty(
12675                     TelephonyProperties.operator_alpha(), phoneId, name);
12676             try {
12677                 TelephonyProperties.operator_alpha(newList);
12678             } catch (IllegalArgumentException e) { //property value is longer than the byte limit
12679                 Log.e(TAG, "setNetworkOperatorNameForPhone: ", e);
12680 
12681                 int numberOfEntries = newList.size();
12682                 int maxOperatorLength = //save 1 byte for joiner " , "
12683                         (SystemProperties.PROP_VALUE_MAX - numberOfEntries) / numberOfEntries;
12684 
12685                 //examine and truncate every operator and retry
12686                 for (int i = 0; i < newList.size(); i++) {
12687                     if (newList.get(i) != null) {
12688                         newList.set(i, TextUtils
12689                                 .truncateStringForUtf8Storage(newList.get(i), maxOperatorLength));
12690                     }
12691                 }
12692                 TelephonyProperties.operator_alpha(newList);
12693                 Log.e(TAG, "successfully truncated operator_alpha: " + newList);
12694             }
12695         }
12696     }
12697 
12698     /**
12699      * Set the numeric name (MCC+MNC) of current registered operator.
12700      * @param phoneId for which phone type is set
12701      * @param operator the numeric name (MCC+MNC) of current registered operator
12702      * @hide
12703      */
12704     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNumericForPhone(int phoneId, String numeric)12705     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
12706         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12707             List<String> newList = updateTelephonyProperty(
12708                     TelephonyProperties.operator_numeric(), phoneId, numeric);
12709             TelephonyProperties.operator_numeric(newList);
12710         }
12711     }
12712 
12713     /**
12714      * Set roaming state of the current network, for GSM purposes.
12715      * @param phoneId which phone you want to set
12716      * @param isRoaming is network in romaing state or not
12717      * @hide
12718      */
12719     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)12720     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
12721         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12722             List<Boolean> newList = updateTelephonyProperty(
12723                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
12724             TelephonyProperties.operator_is_roaming(newList);
12725         }
12726     }
12727 
12728     /**
12729      * Set the network type currently in use on the device for data transmission.
12730      *
12731      * If this object has been created with {@link #createForSubscriptionId}, applies to the
12732      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
12733      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12734      * @param type the network type currently in use on the device for data transmission
12735      * @hide
12736      */
setDataNetworkType(int type)12737     public void setDataNetworkType(int type) {
12738         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
12739         setDataNetworkTypeForPhone(phoneId, type);
12740     }
12741 
12742     /**
12743      * Set the network type currently in use on the device for data transmission.
12744      * @param phoneId which phone you want to set
12745      * @param type the network type currently in use on the device for data transmission
12746      * @hide
12747      */
12748     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setDataNetworkTypeForPhone(int phoneId, int type)12749     public void setDataNetworkTypeForPhone(int phoneId, int type) {
12750         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12751             List<String> newList = updateTelephonyProperty(
12752                     TelephonyProperties.data_network_type(), phoneId,
12753                     ServiceState.rilRadioTechnologyToString(type));
12754             TelephonyProperties.data_network_type(newList);
12755         }
12756     }
12757 
12758     /**
12759      * Returns the subscription ID for the given phone account.
12760      * @hide
12761      */
12762     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)12763     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
12764         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
12765         if (phoneAccount != null
12766                 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
12767             retval = getSubscriptionId(phoneAccount.getAccountHandle());
12768         }
12769         return retval;
12770     }
12771 
12772     /**
12773      * Determines the {@link PhoneAccountHandle} associated with this TelephonyManager.
12774      *
12775      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12776      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12777      *
12778      * <p>Requires Permission android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE or that the
12779      * calling app has carrier privileges (see {@link #hasCarrierPrivileges})
12780      *
12781      * @return The {@link PhoneAccountHandle} associated with the TelphonyManager, or {@code null}
12782      * if there is no associated {@link PhoneAccountHandle}; this can happen if the subscription is
12783      * data-only or an opportunistic subscription.
12784      *
12785      * @throws UnsupportedOperationException If the device does not have
12786      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
12787      */
12788     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
12789     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12790     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getPhoneAccountHandle()12791     public @Nullable PhoneAccountHandle getPhoneAccountHandle() {
12792         return getPhoneAccountHandleForSubscriptionId(getSubId());
12793     }
12794 
12795     /**
12796      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
12797      *
12798      * @param subscriptionId The subscription Id to check.
12799      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
12800      * there is no associated {@link PhoneAccountHandle}.
12801      * @hide
12802      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)12803     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
12804         PhoneAccountHandle returnValue = null;
12805         try {
12806             ITelephony service = getITelephony();
12807             if (service != null) {
12808                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
12809             }
12810         } catch (RemoteException e) {
12811         }
12812 
12813         return returnValue;
12814     }
12815 
12816     /**
12817      * Returns the subscription ID for the given phone account handle.
12818      *
12819      * @param phoneAccountHandle the phone account handle for outgoing calls
12820      * @return subscription ID for the given phone account handle; or
12821      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
12822      *         if not available; or throw a SecurityException if the caller doesn't have the
12823      *         permission.
12824      */
12825     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
12826     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)12827     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
12828         return mPhoneAccountHandleToSubIdCache.query(phoneAccountHandle);
12829     }
12830 
12831     /**
12832      * Resets telephony manager settings back to factory defaults.
12833      *
12834      * @hide
12835      */
factoryReset(int subId)12836     public void factoryReset(int subId) {
12837         try {
12838             Log.d(TAG, "factoryReset: subId=" + subId);
12839             ITelephony telephony = getITelephony();
12840             if (telephony != null) {
12841                 telephony.factoryReset(subId, getOpPackageName());
12842             }
12843         } catch (RemoteException e) {
12844         }
12845     }
12846 
12847 
12848     /**
12849      * Resets Telephony and IMS settings back to factory defaults only for the subscription
12850      * associated with this instance.
12851      * @see #createForSubscriptionId(int)
12852      *
12853      * @throws UnsupportedOperationException If the device does not have
12854      *          {@link PackageManager#FEATURE_TELEPHONY}.
12855      * @hide
12856      */
12857     @SystemApi
12858     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
12859     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
resetSettings()12860     public void resetSettings() {
12861         try {
12862             Log.d(TAG, "resetSettings: subId=" + getSubId());
12863             ITelephony telephony = getITelephony();
12864             if (telephony != null) {
12865                 telephony.factoryReset(getSubId(), getOpPackageName());
12866             }
12867         } catch (RemoteException e) {
12868         }
12869     }
12870 
12871 
12872     /**
12873      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
12874      * no locale could be derived from subscriptions.
12875      *
12876      * <p>Requires Permission:
12877      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12878      *
12879      * @see Locale#toLanguageTag()
12880      *
12881      * @throws UnsupportedOperationException If the device does not have
12882      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12883      * @hide
12884      */
12885     @SystemApi
12886     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12887     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimLocale()12888     @Nullable public Locale getSimLocale() {
12889         try {
12890             final ITelephony telephony = getITelephony();
12891             if (telephony != null) {
12892                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
12893                 if (!TextUtils.isEmpty(languageTag)) {
12894                     return Locale.forLanguageTag(languageTag);
12895                 }
12896             }
12897         } catch (RemoteException ex) {
12898         }
12899         return null;
12900     }
12901 
12902     /**
12903      * Exception that may be supplied to the callback provided in {@link #requestModemActivityInfo}.
12904      * @hide
12905      */
12906     @SystemApi
12907     public static class ModemActivityInfoException extends Exception {
12908         /** Indicates that an unknown error occurred */
12909         public static final int ERROR_UNKNOWN = 0;
12910 
12911         /**
12912          * Indicates that the modem or phone processes are not available (such as when the device
12913          * is in airplane mode).
12914          */
12915         public static final int ERROR_PHONE_NOT_AVAILABLE = 1;
12916 
12917         /**
12918          * Indicates that the modem supplied an invalid instance of {@link ModemActivityInfo}
12919          */
12920         public static final int ERROR_INVALID_INFO_RECEIVED = 2;
12921 
12922         /**
12923          * Indicates that the modem encountered an internal failure when processing the request
12924          * for activity info.
12925          */
12926         public static final int ERROR_MODEM_RESPONSE_ERROR = 3;
12927 
12928         /** @hide */
12929         @Retention(RetentionPolicy.SOURCE)
12930         @IntDef(prefix = {"ERROR_"},
12931                 value = {
12932                         ERROR_UNKNOWN,
12933                         ERROR_PHONE_NOT_AVAILABLE,
12934                         ERROR_INVALID_INFO_RECEIVED,
12935                         ERROR_MODEM_RESPONSE_ERROR,
12936                 })
12937         public @interface ModemActivityInfoError {}
12938 
12939         private final int mErrorCode;
12940 
12941         /**
12942          * An exception with ModemActivityInfo specific error codes.
12943          *
12944          * @param errorCode a ModemActivityInfoError code.
12945          */
ModemActivityInfoException(@odemActivityInfoError int errorCode)12946         public ModemActivityInfoException(@ModemActivityInfoError int errorCode) {
12947             mErrorCode = errorCode;
12948         }
12949 
getErrorCode()12950         public @ModemActivityInfoError int getErrorCode() {
12951             return mErrorCode;
12952         }
12953 
12954         @Override
toString()12955         public String toString() {
12956             switch (mErrorCode) {
12957                 case ERROR_UNKNOWN: return "ERROR_UNKNOWN";
12958                 case ERROR_PHONE_NOT_AVAILABLE: return "ERROR_PHONE_NOT_AVAILABLE";
12959                 case ERROR_INVALID_INFO_RECEIVED: return "ERROR_INVALID_INFO_RECEIVED";
12960                 case ERROR_MODEM_RESPONSE_ERROR: return "ERROR_MODEM_RESPONSE_ERROR";
12961                 default: return "UNDEFINED";
12962             }
12963         }
12964     }
12965 
12966     /**
12967      * Requests the current modem activity info.
12968      *
12969      * The provided instance of {@link ModemActivityInfo} represents the cumulative activity since
12970      * the last restart of the phone process.
12971      *
12972      * @param callback A callback object to which the result will be delivered. If there was an
12973      *                 error processing the request, {@link OutcomeReceiver#onError} will be called
12974      *                 with more details about the error.
12975      *
12976      * @throws UnsupportedOperationException If the device does not have
12977      *          {@link PackageManager#FEATURE_TELEPHONY}.
12978      * @hide
12979      */
12980     @SystemApi
12981     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
12982     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
requestModemActivityInfo(@onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback)12983     public void requestModemActivityInfo(@NonNull @CallbackExecutor Executor executor,
12984             @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback) {
12985         Objects.requireNonNull(executor);
12986         Objects.requireNonNull(callback);
12987 
12988         // Pass no handler into the receiver, since we're going to be trampolining the call to the
12989         // listener onto the provided executor.
12990         ResultReceiver wrapperResultReceiver = new ResultReceiver(null) {
12991             @Override
12992             protected void onReceiveResult(int resultCode, Bundle data) {
12993                 if (data == null) {
12994                     Log.w(TAG, "requestModemActivityInfo: received null bundle");
12995                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
12996                     return;
12997                 }
12998                 data.setDefusable(true);
12999                 if (data.containsKey(EXCEPTION_RESULT_KEY)) {
13000                     int receivedErrorCode = data.getInt(EXCEPTION_RESULT_KEY);
13001                     sendErrorToListener(receivedErrorCode);
13002                     return;
13003                 }
13004 
13005                 if (!data.containsKey(MODEM_ACTIVITY_RESULT_KEY)) {
13006                     Log.w(TAG, "requestModemActivityInfo: Bundle did not contain expected key");
13007                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
13008                     return;
13009                 }
13010                 Parcelable receivedResult = data.getParcelable(MODEM_ACTIVITY_RESULT_KEY);
13011                 if (!(receivedResult instanceof ModemActivityInfo)) {
13012                     Log.w(TAG, "requestModemActivityInfo: Bundle contained something that wasn't "
13013                             + "a ModemActivityInfo.");
13014                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
13015                     return;
13016                 }
13017                 ModemActivityInfo modemActivityInfo = (ModemActivityInfo) receivedResult;
13018                 if (!modemActivityInfo.isValid()) {
13019                     Log.w(TAG, "requestModemActivityInfo: Received an invalid ModemActivityInfo");
13020                     sendErrorToListener(ModemActivityInfoException.ERROR_INVALID_INFO_RECEIVED);
13021                     return;
13022                 }
13023                 Log.d(TAG, "requestModemActivityInfo: Sending result to app: " + modemActivityInfo);
13024                 sendResultToListener(modemActivityInfo);
13025             }
13026 
13027             private void sendResultToListener(ModemActivityInfo info) {
13028                 Binder.withCleanCallingIdentity(() ->
13029                         executor.execute(() ->
13030                                 callback.onResult(info)));
13031             }
13032 
13033             private void sendErrorToListener(int code) {
13034                 ModemActivityInfoException e = new ModemActivityInfoException(code);
13035                 Binder.withCleanCallingIdentity(() ->
13036                         executor.execute(() ->
13037                                 callback.onError(e)));
13038             }
13039         };
13040 
13041         try {
13042             ITelephony service = getITelephony();
13043             if (service != null) {
13044                 service.requestModemActivityInfo(wrapperResultReceiver);
13045                 return;
13046             }
13047         } catch (RemoteException e) {
13048             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
13049         }
13050         executor.execute(() -> callback.onError(
13051                 new ModemActivityInfoException(
13052                         ModemActivityInfoException.ERROR_PHONE_NOT_AVAILABLE)));
13053     }
13054 
13055     /**
13056      * Returns the current {@link ServiceState} information.
13057      *
13058      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13059      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
13060      *
13061      * If you want continuous updates of service state info, register a {@link TelephonyCallback}
13062      * that implements {@link TelephonyCallback.ServiceStateListener} through {@link
13063      * #registerTelephonyCallback}.
13064      *
13065      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
13066      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
13067      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
13068      * May return {@code null} when the subscription is inactive or when there was an error
13069      * communicating with the phone process.
13070      *
13071      * @throws UnsupportedOperationException If the device does not have
13072      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
13073      */
13074     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13075     @RequiresPermission(allOf = {
13076             Manifest.permission.READ_PHONE_STATE,
13077             Manifest.permission.ACCESS_COARSE_LOCATION
13078     })
13079     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceState()13080     public @Nullable ServiceState getServiceState() {
13081         return getServiceState(getLocationData());
13082     }
13083 
13084     /**
13085      * Returns the current {@link ServiceState} information.
13086      *
13087      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13088      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
13089      *
13090      * If you want continuous updates of service state info, register a {@link TelephonyCallback}
13091      * that implements {@link TelephonyCallback.ServiceStateListener} through {@link
13092      * #registerTelephonyCallback}.
13093      *
13094      * There's another way to renounce permissions with a custom context
13095      * {@code AttributionSource.Builder#setRenouncedPermissions(Set<String>)} but only for system
13096      * apps. To avoid confusion, calling this method supersede renouncing permissions with a
13097      * custom context.
13098      *
13099      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
13100      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
13101      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
13102      * @param includeLocationData Specifies if the caller would like to receive
13103      * location related information.
13104      * May return {@code null} when the subscription is inactive or when there was an error
13105      * communicating with the phone process.
13106      *
13107      * @throws UnsupportedOperationException If the device does not have
13108      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
13109      */
13110     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13111     @RequiresPermission(allOf = {
13112             Manifest.permission.READ_PHONE_STATE,
13113             Manifest.permission.ACCESS_COARSE_LOCATION
13114     })
13115     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceState(@ncludeLocationData int includeLocationData)13116     public @Nullable ServiceState getServiceState(@IncludeLocationData int includeLocationData) {
13117         return getServiceStateForSlot(SubscriptionManager.getSlotIndex(getSubId()),
13118                 includeLocationData != INCLUDE_LOCATION_DATA_FINE,
13119                 includeLocationData == INCLUDE_LOCATION_DATA_NONE);
13120     }
13121 
13122     /**
13123      * Returns the service state information on specified SIM slot.
13124      *
13125      * May return {@code null} when the {@code slotIndex} is invalid or when there was an error
13126      * communicating with the phone process.
13127      *
13128      * @param slotIndex of phone whose service state is returned
13129      * @param renounceFineLocationAccess Set this to true if the caller would not like to receive
13130      * location related information which will be sent if the caller already possess
13131      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and do not renounce the permission
13132      * @param renounceCoarseLocationAccess Set this to true if the caller would not like to
13133      * receive location related information which will be sent if the caller already possess
13134      * {@link Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the permissions.
13135      * @return Service state on specified SIM slot.
13136      */
getServiceStateForSlot(int slotIndex, boolean renounceFineLocationAccess, boolean renounceCoarseLocationAccess)13137     private ServiceState getServiceStateForSlot(int slotIndex, boolean renounceFineLocationAccess,
13138             boolean renounceCoarseLocationAccess) {
13139         try {
13140             ITelephony service = getITelephony();
13141             if (service != null) {
13142                 return service.getServiceStateForSlot(slotIndex,
13143                         renounceFineLocationAccess, renounceCoarseLocationAccess,
13144                         getOpPackageName(), getAttributionTag());
13145             }
13146         } catch (RemoteException e) {
13147             Log.e(TAG, "Error calling ITelephony#getServiceStateForSlot", e);
13148         } catch (NullPointerException e) {
13149             AnomalyReporter.reportAnomaly(
13150                     UUID.fromString("e2bed88e-def9-476e-bd71-3e572a8de6d1"),
13151                     "getServiceStateForSlot " + slotIndex + " NPE");
13152         }
13153         return null;
13154     }
13155 
13156     /**
13157      * Returns the service state information on specified subscription. Callers require
13158      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
13159      *
13160      * May return {@code null} when the subscription is inactive or when there was an error
13161      * communicating with the phone process.
13162      * @hide
13163      */
13164     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)13165     public ServiceState getServiceStateForSubscriber(int subId) {
13166         return getServiceStateForSlot(
13167                 SubscriptionManager.getSlotIndex(subId), false, false);
13168     }
13169 
13170     /**
13171      * Returns the service state information on specified SIM slot.
13172      *
13173      * If you want continuous updates of service state info, register a {@link TelephonyCallback}
13174      * that implements {@link TelephonyCallback.ServiceStateListener} through
13175      * {@link #registerTelephonyCallback}.
13176      *
13177      * May return {@code null} when the {@code slotIndex} is invalid or when there was an error
13178      * communicating with the phone process
13179      *
13180      * See {@link #getActiveModemCount()} to get the total number of slots
13181      * that are active on the device.
13182      *
13183      * @param slotIndex of phone whose service state is returned
13184      * @return ServiceState on specified SIM slot.
13185      *
13186      * @hide
13187      */
13188     @RequiresPermission(allOf = {
13189             Manifest.permission.READ_PHONE_STATE,
13190             Manifest.permission.ACCESS_COARSE_LOCATION
13191     })
13192     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceStateForSlot(int slotIndex)13193     public @Nullable ServiceState getServiceStateForSlot(int slotIndex) {
13194         return getServiceStateForSlot(slotIndex, false, false);
13195     }
13196 
13197     /**
13198      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
13199      *
13200      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
13201      * voicemail ringtone.
13202      * @return The URI for the ringtone to play when receiving a voicemail from a specific
13203      * PhoneAccount. May be {@code null} if no ringtone is set.
13204      *
13205      * @throws UnsupportedOperationException If the device does not have
13206      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13207      */
13208     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)13209     public @Nullable Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
13210         try {
13211             ITelephony service = getITelephony();
13212             if (service != null) {
13213                 return service.getVoicemailRingtoneUri(accountHandle);
13214             }
13215         } catch (RemoteException e) {
13216             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
13217         }
13218         return null;
13219     }
13220 
13221     /**
13222      * Sets the per-account voicemail ringtone.
13223      *
13224      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
13225      * {@link #hasCarrierPrivileges}, or has permission
13226      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13227      *
13228      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
13229      * voicemail ringtone.
13230      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
13231      * PhoneAccount.
13232      *
13233      * @throws UnsupportedOperationException If the device does not have
13234      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13235      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
13236      * instead.
13237      */
13238     @Deprecated
13239     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)13240     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
13241         try {
13242             ITelephony service = getITelephony();
13243             if (service != null) {
13244                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
13245             }
13246         } catch (RemoteException e) {
13247             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
13248         }
13249     }
13250 
13251     /**
13252      * Returns whether vibration is set for voicemail notification in Phone settings.
13253      *
13254      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
13255      * voicemail vibration setting.
13256      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
13257      *
13258      * @throws UnsupportedOperationException If the device does not have
13259      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13260      */
13261     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)13262     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
13263         try {
13264             ITelephony service = getITelephony();
13265             if (service != null) {
13266                 return service.isVoicemailVibrationEnabled(accountHandle);
13267             }
13268         } catch (RemoteException e) {
13269             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
13270         }
13271         return false;
13272     }
13273 
13274     /**
13275      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
13276      *
13277      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
13278      * {@link #hasCarrierPrivileges}, or has permission
13279      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13280      *
13281      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
13282      * voicemail vibration setting.
13283      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
13284      * specific PhoneAccount.
13285      *
13286      * @throws UnsupportedOperationException If the device does not have
13287      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13288      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
13289      * instead.
13290      */
13291     @Deprecated
13292     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)13293     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
13294             boolean enabled) {
13295         try {
13296             ITelephony service = getITelephony();
13297             if (service != null) {
13298                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
13299                         enabled);
13300             }
13301         } catch (RemoteException e) {
13302             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
13303         }
13304     }
13305 
13306     /**
13307      * Returns carrier id of the current subscription.
13308      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
13309      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
13310      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
13311      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13312      *
13313      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
13314      * as an Android platform-wide identifier for carriers.
13315      *
13316      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
13317      * subscription is unavailable or the carrier cannot be identified.
13318      *
13319      * @throws UnsupportedOperationException If the device does not have
13320      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13321      */
13322     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCarrierId()13323     public int getSimCarrierId() {
13324         try {
13325             ITelephony service = getITelephony();
13326             if (service != null) {
13327                 return service.getSubscriptionCarrierId(getSubId());
13328             }
13329         } catch (RemoteException ex) {
13330             // This could happen if binder process crashes.
13331         }
13332         return UNKNOWN_CARRIER_ID;
13333     }
13334 
13335     /**
13336      * Returns carrier id name of the current subscription.
13337      * <p>Carrier id name is a user-facing name of carrier id returned by
13338      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
13339      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
13340      * should have a single carrier name. Carrier name is not a canonical identity,
13341      * use {@link #getSimCarrierId()} instead.
13342      * <p>The returned carrier name is unlocalized.
13343      *
13344      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
13345      * unavailable or the carrier cannot be identified.
13346      *
13347      * @throws UnsupportedOperationException If the device does not have
13348      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13349      */
13350     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCarrierIdName()13351     public @Nullable CharSequence getSimCarrierIdName() {
13352         try {
13353             ITelephony service = getITelephony();
13354             if (service != null) {
13355                 return service.getSubscriptionCarrierName(getSubId());
13356             }
13357         } catch (RemoteException ex) {
13358             // This could happen if binder process crashes.
13359         }
13360         return null;
13361     }
13362 
13363     /**
13364      * Returns fine-grained carrier ID of the current subscription.
13365      *
13366      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
13367      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
13368      * are used to make up the actual carrier service may have different carrier configurations.
13369      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
13370      * different carrier configuration for different service offering such as a prepaid plan.
13371      *
13372      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
13373      * about the carrier itself should use the regular carrier ID returned by
13374      * {@link #getSimCarrierId()}.
13375      *
13376      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
13377      * subscription while carrier ID remains the same.
13378      *
13379      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
13380      * <p>Specific carrier ids are defined in the same way as carrier id
13381      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13382      * except each with a "parent" id linking to its top-level carrier id.
13383      *
13384      * @return Returns fine-grained carrier id of the current subscription.
13385      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
13386      * be identified.
13387      *
13388      * @throws UnsupportedOperationException If the device does not have
13389      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13390      */
13391     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSpecificCarrierId()13392     public int getSimSpecificCarrierId() {
13393         try {
13394             ITelephony service = getITelephony();
13395             if (service != null) {
13396                 return service.getSubscriptionSpecificCarrierId(getSubId());
13397             }
13398         } catch (RemoteException ex) {
13399             // This could happen if binder process crashes.
13400         }
13401         return UNKNOWN_CARRIER_ID;
13402     }
13403 
13404     /**
13405      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
13406      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
13407      *
13408      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
13409      * about the carrier itself should use the regular carrier ID returned by
13410      * {@link #getSimCarrierIdName()}.
13411      *
13412      * <p>The returned name is unlocalized.
13413      *
13414      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
13415      * subscription is unavailable or the carrier cannot be identified.
13416      *
13417      * @throws UnsupportedOperationException If the device does not have
13418      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13419      */
13420     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSpecificCarrierIdName()13421     public @Nullable CharSequence getSimSpecificCarrierIdName() {
13422         try {
13423             ITelephony service = getITelephony();
13424             if (service != null) {
13425                 return service.getSubscriptionSpecificCarrierName(getSubId());
13426             }
13427         } catch (RemoteException ex) {
13428             // This could happen if binder process crashes.
13429         }
13430         return null;
13431     }
13432 
13433     /**
13434      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
13435      * This is used for fallback when configurations/logic for exact carrier id
13436      * {@link #getSimCarrierId()} are not found.
13437      *
13438      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13439      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
13440      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
13441      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
13442      * take the update with the new id, it might be helpful to always fallback by using carrier
13443      * id based on MCCMNC if there is no match.
13444      *
13445      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
13446      * subscription is unavailable or the carrier cannot be identified.
13447      *
13448      * @throws UnsupportedOperationException If the device does not have
13449      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13450      */
13451     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierIdFromSimMccMnc()13452     public int getCarrierIdFromSimMccMnc() {
13453         try {
13454             ITelephony service = getITelephony();
13455             if (service != null) {
13456                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
13457             }
13458         } catch (RemoteException ex) {
13459             // This could happen if binder process crashes.
13460         }
13461         return UNKNOWN_CARRIER_ID;
13462     }
13463 
13464      /**
13465       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
13466       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
13467       * are not found.
13468       *
13469       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13470       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
13471       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
13472       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
13473       * take the update with the new id, it might be helpful to always fallback by using carrier
13474       * id based on MCCMNC if there is no match.
13475       *
13476       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
13477       * subscription is unavailable or the carrier cannot be identified.
13478       * @hide
13479       */
13480      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)13481      public int getCarrierIdFromMccMnc(String mccmnc) {
13482         try {
13483             ITelephony service = getITelephony();
13484             if (service != null) {
13485                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
13486             }
13487         } catch (RemoteException ex) {
13488             // This could happen if binder process crashes.
13489         }
13490         return UNKNOWN_CARRIER_ID;
13491     }
13492 
13493     /**
13494      * Return a list of certs as hex strings from loaded carrier privileges access rules.
13495      *
13496      * @return a list of certificates as hex strings, or an empty list if there are no certs or
13497      *     privilege rules are not loaded yet.
13498      * @hide
13499      */
13500     @TestApi
13501     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13502     @NonNull
getCertsFromCarrierPrivilegeAccessRules()13503     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
13504         List<String> certs = null;
13505         try {
13506             ITelephony service = getITelephony();
13507             if (service != null) {
13508                 certs = service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
13509             }
13510         } catch (RemoteException ex) {
13511             // This could happen if binder process crashes.
13512         }
13513         return certs == null ? Collections.emptyList() : certs;
13514     }
13515 
13516     /**
13517      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
13518      * All uicc applications are uniquely identified by application ID, represented by the hex
13519      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
13520      * <p>Requires Permission:
13521      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
13522      *
13523      * @param appType the uicc app type.
13524      * @return Application ID for specified app type or {@code null} if no uicc or error.
13525      *
13526      * @throws UnsupportedOperationException If the device does not have
13527      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13528      * @hide
13529      */
13530     @Nullable
13531     @SystemApi
13532     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13533     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getAidForAppType(@iccAppType int appType)13534     public String getAidForAppType(@UiccAppType int appType) {
13535         return getAidForAppType(getSubId(), appType);
13536     }
13537 
13538     /**
13539      * same as {@link #getAidForAppType(int)}
13540      * @hide
13541      */
getAidForAppType(int subId, int appType)13542     public String getAidForAppType(int subId, int appType) {
13543         try {
13544             ITelephony service = getITelephony();
13545             if (service != null) {
13546                 return service.getAidForAppType(subId, appType);
13547             }
13548         } catch (RemoteException e) {
13549             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
13550         }
13551         return null;
13552     }
13553 
13554     /**
13555      * Return the Electronic Serial Number.
13556      *
13557      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13558      *
13559      * @return ESN or null if error.
13560      * @hide
13561      */
getEsn()13562     public String getEsn() {
13563         return getEsn(getSubId());
13564     }
13565 
13566     /**
13567      * Return the Electronic Serial Number.
13568      *
13569      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13570      *
13571      * @param subId the subscription ID that this request applies to.
13572      * @return ESN or null if error.
13573      * @hide
13574      */
getEsn(int subId)13575     public String getEsn(int subId) {
13576         try {
13577             ITelephony service = getITelephony();
13578             if (service != null) {
13579                 return service.getEsn(subId);
13580             }
13581         } catch (RemoteException e) {
13582             Log.e(TAG, "Error calling ITelephony#getEsn", e);
13583         }
13584         return null;
13585     }
13586 
13587     /**
13588      * Return the Preferred Roaming List Version
13589      *
13590      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13591      *
13592      * @return PRLVersion or null if error.
13593      *
13594      * @throws UnsupportedOperationException If the device does not have
13595      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
13596      * @hide
13597      */
13598     @SystemApi
13599     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaPrlVersion()13600     public String getCdmaPrlVersion() {
13601         return getCdmaPrlVersion(getSubId());
13602     }
13603 
13604     /**
13605      * Return the Preferred Roaming List Version
13606      *
13607      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13608      *
13609      * @param subId the subscription ID that this request applies to.
13610      * @return PRLVersion or null if error.
13611      * @hide
13612      */
getCdmaPrlVersion(int subId)13613     public String getCdmaPrlVersion(int subId) {
13614         try {
13615             ITelephony service = getITelephony();
13616             if (service != null) {
13617                 return service.getCdmaPrlVersion(subId);
13618             }
13619         } catch (RemoteException e) {
13620             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
13621         }
13622         return null;
13623     }
13624 
13625     /**
13626      * Get snapshot of Telephony histograms
13627      * @return List of Telephony histograms
13628      * Requires Permission:
13629      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
13630      * Or the calling app has carrier privileges.
13631      * @hide
13632      */
13633     @SystemApi
13634     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()13635     public List<TelephonyHistogram> getTelephonyHistograms() {
13636         try {
13637             ITelephony service = getITelephony();
13638             if (service != null) {
13639                 return service.getTelephonyHistograms();
13640             }
13641         } catch (RemoteException e) {
13642             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
13643         }
13644         return null;
13645     }
13646 
13647     /**
13648      * Set the allowed carrier list for slotIndex
13649      * Require system privileges. In the future we may add this to carrier APIs.
13650      *
13651      * <p>Requires Permission:
13652      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
13653      *
13654      * <p>This method works only on devices with {@link
13655      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13656      *
13657      * @deprecated use setCarrierRestrictionRules instead
13658      *
13659      * @return The number of carriers set successfully. Should be length of
13660      * carrierList on success; -1 if carrierList null or on error.
13661      *
13662      * @throws UnsupportedOperationException If the device does not have
13663      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
13664      * @hide
13665      */
13666     @SystemApi
13667     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13668     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)13669     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
13670         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
13671             return -1;
13672         }
13673         // Execute the method setCarrierRestrictionRules with an empty excluded list.
13674         // If the allowed list is empty, it means that all carriers are allowed (default allowed),
13675         // otherwise it means that only specified carriers are allowed (default not allowed).
13676         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
13677                 .setAllowedCarriers(carriers)
13678                 .setDefaultCarrierRestriction(
13679                     carriers.isEmpty()
13680                         ? CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_ALLOWED
13681                         : CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
13682                 .build();
13683 
13684         int result = setCarrierRestrictionRules(carrierRestrictionRules);
13685 
13686         // Convert result into int, as required by this method.
13687         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
13688             return carriers.size();
13689         } else {
13690             return -1;
13691         }
13692     }
13693 
13694     /**
13695      * The carrier restrictions were successfully set.
13696      * @hide
13697      */
13698     @SystemApi
13699     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
13700 
13701     /**
13702      * The carrier restrictions were not set due to lack of support in the modem. This can happen
13703      * if the modem does not support setting the carrier restrictions or if the configuration
13704      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
13705      * @hide
13706      */
13707     @SystemApi
13708     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
13709 
13710     /**
13711      * The setting of carrier restrictions failed.
13712      * @hide
13713      */
13714     @SystemApi
13715     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
13716 
13717     /** @hide */
13718     @Retention(RetentionPolicy.SOURCE)
13719     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
13720             value = {
13721                     SET_CARRIER_RESTRICTION_SUCCESS,
13722                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
13723                     SET_CARRIER_RESTRICTION_ERROR
13724             })
13725     public @interface SetCarrierRestrictionResult {}
13726 
13727     /**
13728      * The SIM power state was successfully set.
13729      * @hide
13730      */
13731     @SystemApi
13732     public static final int SET_SIM_POWER_STATE_SUCCESS = 0;
13733 
13734     /**
13735      * The SIM is already in the requested power state.
13736      * @hide
13737      */
13738     @SystemApi
13739     public static final int SET_SIM_POWER_STATE_ALREADY_IN_STATE = 1;
13740 
13741     /**
13742      * Failed to connect to the modem to make the power state request. This may happen if the
13743      * modem has an error. The user may want to make the request again later.
13744      * @hide
13745      */
13746     @SystemApi
13747     public static final int SET_SIM_POWER_STATE_MODEM_ERROR = 2;
13748 
13749     /**
13750      * Failed to connect to the SIM to make the power state request. This may happen if the
13751      * SIM has been removed. The user may want to make the request again later.
13752      * @hide
13753      */
13754     @SystemApi
13755     public static final int SET_SIM_POWER_STATE_SIM_ERROR = 3;
13756 
13757     /**
13758      * The modem version does not support synchronous power.
13759      * @hide
13760      */
13761     @SystemApi
13762     public static final int SET_SIM_POWER_STATE_NOT_SUPPORTED = 4;
13763 
13764     /** @hide */
13765     @Retention(RetentionPolicy.SOURCE)
13766     @IntDef(prefix = {"SET_SIM_POWER_STATE_"},
13767             value = {
13768                     SET_SIM_POWER_STATE_SUCCESS,
13769                     SET_SIM_POWER_STATE_ALREADY_IN_STATE,
13770                     SET_SIM_POWER_STATE_MODEM_ERROR,
13771                     SET_SIM_POWER_STATE_SIM_ERROR,
13772                     SET_SIM_POWER_STATE_NOT_SUPPORTED
13773             })
13774     public @interface SetSimPowerStateResult {}
13775 
13776     /**
13777      * Set the allowed carrier list and the excluded carrier list indicating the priority between
13778      * the two lists.
13779      * Requires system privileges.
13780      *
13781      * <p>Requires Permission:
13782      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
13783      *
13784      * <p>This method works only on devices with {@link
13785      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13786      *
13787      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
13788      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
13789      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
13790      *
13791      * @throws UnsupportedOperationException If the device does not have
13792      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
13793      * @hide
13794      */
13795     @SystemApi
13796     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
13797     @SetCarrierRestrictionResult
13798     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)13799     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
13800         try {
13801             ITelephony service = getITelephony();
13802             if (service != null) {
13803                 return service.setAllowedCarriers(rules);
13804             }
13805         } catch (RemoteException e) {
13806             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
13807         } catch (NullPointerException e) {
13808             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
13809         }
13810         return SET_CARRIER_RESTRICTION_ERROR;
13811     }
13812 
13813     /**
13814      * Get the allowed carrier list for slotIndex.
13815      * Requires system privileges.
13816      *
13817      * <p>This method returns valid data on devices with {@link
13818      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13819      *
13820      * @deprecated Apps should use {@link #getCarrierRestrictionRules} to retrieve the list of
13821      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
13822      * list is empty. This API could return an empty list, even if some restrictions are present.
13823      *
13824      * @return List of {@link android.service.carrier.CarrierIdentifier}; empty list
13825      * means all carriers are allowed.
13826      *
13827      * @throws UnsupportedOperationException If the device does not have
13828      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
13829      * @hide
13830      */
13831     @Deprecated
13832     @SystemApi
13833     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13834     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
getAllowedCarriers(int slotIndex)13835     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
13836         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
13837             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
13838             if (carrierRestrictionRule != null) {
13839                 return carrierRestrictionRule.getAllowedCarriers();
13840             }
13841         }
13842         return new ArrayList<CarrierIdentifier>(0);
13843     }
13844 
13845     /**
13846      * Get the allowed carrier list and the excluded carrier list indicating the priority between
13847      * the two lists.
13848      * Require system privileges. In the future we may add this to carrier APIs.
13849      *
13850      * <p>This method returns valid data on devices with {@link
13851      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
13852      *
13853      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
13854      * excluded carrier list with the priority between the two lists. Returns {@code null}
13855      * in case of error.
13856      *
13857      * @throws UnsupportedOperationException If the device does not have
13858      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
13859      * @hide
13860      */
13861     @SystemApi
13862     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13863     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
13864     @Nullable
getCarrierRestrictionRules()13865     public CarrierRestrictionRules getCarrierRestrictionRules() {
13866         try {
13867             ITelephony service = getITelephony();
13868             if (service != null) {
13869                 return service.getAllowedCarriers();
13870             }
13871         } catch (RemoteException e) {
13872             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
13873         } catch (NullPointerException e) {
13874             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
13875         }
13876         return null;
13877     }
13878 
13879     /**
13880      * Carrier restriction status value is unknown, in case modem did not provide any
13881      * information about carrier restriction status.
13882      */
13883     public static final int CARRIER_RESTRICTION_STATUS_UNKNOWN = 0;
13884 
13885     /** The device is not restricted to a carrier */
13886     public static final int CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED = 1;
13887 
13888     /** The device is restricted to a carrier. */
13889     public static final int CARRIER_RESTRICTION_STATUS_RESTRICTED = 2;
13890 
13891     /** The device is restricted to the carrier of the calling application. */
13892     public static final int CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER = 3;
13893 
13894     /** @hide */
13895     @IntDef(prefix = {"CARRIER_RESTRICTION_STATUS_"}, value = {
13896             CARRIER_RESTRICTION_STATUS_UNKNOWN,
13897             CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED,
13898             CARRIER_RESTRICTION_STATUS_RESTRICTED,
13899             CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER
13900     })
13901     @Retention(RetentionPolicy.SOURCE)
13902     public @interface CarrierRestrictionStatus {
13903     }
13904 
13905     /**
13906      * Get the carrier restriction status of the device.
13907      * <p>To fetch the carrier restriction status of the device the calling application needs to be
13908      * allowlisted to Android at <a href="https://android.googlesource.com/platform/packages/services/Telephony/+/master/assets/CarrierRestrictionOperatorDetails.json">here</a>.
13909      * The calling application also needs the READ_PHONE_STATE permission.
13910      * The return value of the API is as follows.
13911      * <ul>
13912      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER} if the caller
13913      *      and the device locked by the network are same</li>
13914      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_RESTRICTED} if the caller and the
13915      *      device locked by the network are different</li>
13916      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED} if the device is
13917      *      not locked</li>
13918      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_UNKNOWN} if the device locking
13919      *      state is unavailable or radio does not supports the feature</li>
13920      * </ul>
13921      *
13922      * @param executor The executor on which the result listener will be called.
13923      * @param resultListener {@link Consumer} that will be called with the carrier restriction
13924      *                       status result fetched from the radio
13925      * @throws SecurityException if the caller does not have the required permission/privileges or
13926      *                           if the caller is not pre-registered.
13927      * @throws UnsupportedOperationException If the device does not have
13928      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13929      */
13930     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
13931     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCarrierRestrictionStatus(@onNull Executor executor, @NonNull @CarrierRestrictionStatus Consumer<Integer> resultListener)13932     public void getCarrierRestrictionStatus(@NonNull Executor executor,
13933             @NonNull @CarrierRestrictionStatus
13934                     Consumer<Integer> resultListener) {
13935         Objects.requireNonNull(executor);
13936         Objects.requireNonNull(resultListener);
13937 
13938         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
13939             @Override
13940             public void accept(@CarrierRestrictionStatus int result) {
13941                 executor.execute(() -> Binder.withCleanCallingIdentity(
13942                         () -> resultListener.accept(result)));
13943             }
13944         };
13945         try {
13946             ITelephony service = getITelephony();
13947             if (service != null) {
13948                 service.getCarrierRestrictionStatus(internalCallback, getOpPackageName());
13949             }
13950         } catch (RemoteException ex) {
13951             Rlog.e(TAG, "getCarrierRestrictionStatus: RemoteException = " + ex);
13952             throw ex.rethrowAsRuntimeException();
13953         }
13954     }
13955 
13956     /**
13957      * Test API to verify carrier restriction status allow list i.e.
13958      * packages/services/Telephony/assets/CarrierRestrictionOperatorDetails.json.
13959      *
13960      * @param pkgName : packaga name of the entry to verify
13961      * @param carrierId : carrier Id of the entry
13962      * @return {@code List<String>} : list of registered shaIds
13963      * @hide
13964      */
13965     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getShaIdFromAllowList(String pkgName, int carrierId)13966     public List<String> getShaIdFromAllowList(String pkgName, int carrierId) {
13967         try {
13968             ITelephony service = getITelephony();
13969             if (service != null) {
13970                 return service.getShaIdFromAllowList(pkgName, carrierId);
13971             }
13972         } catch (RemoteException ex) {
13973             Rlog.e(TAG, "getShaIdFromAllowList: RemoteException = " + ex);
13974             throw ex.rethrowAsRuntimeException();
13975         }
13976         return Collections.EMPTY_LIST;
13977     }
13978 
13979     /**
13980      * Used to enable or disable carrier data by the system based on carrier signalling or
13981      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
13982      * user settings, carrier data on/off won't affect user settings but will bypass the
13983      * settings and turns off data internally if set to {@code false}.
13984      *
13985      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13986      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13987      *
13988      * <p>Requires Permission:
13989      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13990      *
13991      * @param enabled control enable or disable carrier data.
13992      * @see #resetAllCarrierActions()
13993      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
13994      * reason {@link #DATA_ENABLED_REASON_CARRIER}} instead.
13995      *
13996      * @throws UnsupportedOperationException If the device does not have
13997      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
13998      * @hide
13999      */
14000     @Deprecated
14001     @SystemApi
14002     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14003     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setCarrierDataEnabled(boolean enabled)14004     public void setCarrierDataEnabled(boolean enabled) {
14005         try {
14006             setDataEnabledForReason(DATA_ENABLED_REASON_CARRIER, enabled);
14007         } catch (RuntimeException e) {
14008             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
14009         }
14010     }
14011 
14012     /**
14013      * Carrier action to enable or disable the radio.
14014      *
14015      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14016      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14017      *
14018      * <p>Requires Permission:
14019      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14020      *
14021      * @param enabled control enable or disable radio.
14022      * @see #resetAllCarrierActions()
14023      *
14024      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
14025      * {@link clearRadioPowerOffForReason}.
14026      *
14027      * @throws UnsupportedOperationException If the device does not have
14028      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14029      * @hide
14030      */
14031     @Deprecated
14032     @SystemApi
14033     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14034     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadioEnabled(boolean enabled)14035     public void setRadioEnabled(boolean enabled) {
14036         if (enabled) {
14037             clearRadioPowerOffForReason(RADIO_POWER_REASON_CARRIER);
14038         } else {
14039             requestRadioPowerOffForReason(RADIO_POWER_REASON_CARRIER);
14040         }
14041     }
14042 
14043     /**
14044      * No error. Operation succeeded.
14045      * @hide
14046      */
14047     public static final int ENABLE_VONR_SUCCESS = 0;
14048 
14049     /**
14050      * Radio is not available.
14051      * @hide
14052      */
14053     public static final int ENABLE_VONR_RADIO_NOT_AVAILABLE = 2;
14054 
14055     /**
14056      * Internal Radio error.
14057      * @hide
14058      */
14059     public static final int ENABLE_VONR_RADIO_ERROR = 3;
14060 
14061     /**
14062      * Voice over NR enable/disable request is received when system is in invalid state.
14063      * @hide
14064      */
14065     public static final int ENABLE_VONR_RADIO_INVALID_STATE = 4;
14066 
14067     /**
14068      * Voice over NR enable/disable request is not supported.
14069      * @hide
14070      */
14071     public static final int ENABLE_VONR_REQUEST_NOT_SUPPORTED = 5;
14072 
14073     /** @hide */
14074     @Retention(RetentionPolicy.SOURCE)
14075     @IntDef(prefix = {"EnableVoNrResult"}, value = {
14076             ENABLE_VONR_SUCCESS,
14077             ENABLE_VONR_RADIO_NOT_AVAILABLE,
14078             ENABLE_VONR_RADIO_ERROR,
14079             ENABLE_VONR_RADIO_INVALID_STATE,
14080             ENABLE_VONR_REQUEST_NOT_SUPPORTED})
14081     public @interface EnableVoNrResult {}
14082 
14083     /**
14084      * Enable or disable Voice over NR (VoNR)
14085      *
14086      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14087      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14088      *
14089      * <p>Requires Permission:
14090      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14091      *
14092      * @param enabled  enable or disable VoNR.
14093      * @throws IllegalStateException if the Telephony process is not currently available.
14094      * @hide
14095      */
14096     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoNrEnabled(boolean enabled)14097     public @EnableVoNrResult int setVoNrEnabled(boolean enabled) {
14098         try {
14099             ITelephony service = getITelephony();
14100             if (service != null) {
14101                 return service.setVoNrEnabled(
14102                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
14103             } else {
14104                 throw new IllegalStateException("telephony service is null.");
14105             }
14106         } catch (RemoteException e) {
14107             Log.e(TAG, "Error calling ITelephony#setVoNrEnabled", e);
14108         }
14109 
14110         return ENABLE_VONR_RADIO_INVALID_STATE;
14111     }
14112 
14113     /**
14114      * Is Voice over NR (VoNR) enabled.
14115      * @return true if Voice over NR (VoNR) is enabled else false. Enabled state does not mean
14116      *  voice call over NR is active or voice ove NR is available. It means the device is allowed to
14117      *  register IMS over NR.
14118      * @throws IllegalStateException if the Telephony process is not currently available.
14119      * @hide
14120      */
14121     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isVoNrEnabled()14122     public boolean isVoNrEnabled() {
14123         try {
14124             ITelephony telephony = getITelephony();
14125             if (telephony != null) {
14126                 return telephony.isVoNrEnabled(getSubId());
14127             } else {
14128                 throw new IllegalStateException("telephony service is null.");
14129             }
14130         } catch (RemoteException ex) {
14131             Rlog.e(TAG, "isVoNrEnabled RemoteException", ex);
14132             ex.rethrowFromSystemServer();
14133         }
14134         return false;
14135     }
14136 
14137     /**
14138      * Carrier action to start or stop reporting default network available events.
14139      *
14140      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14141      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14142      *
14143      * <p>Requires Permission:
14144      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14145      *
14146      * @param report control start/stop reporting network status.
14147      * @see #resetAllCarrierActions()
14148      *
14149      * @throws UnsupportedOperationException If the device does not have
14150      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14151      * @hide
14152      */
14153     @SystemApi
14154     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14155     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
reportDefaultNetworkStatus(boolean report)14156     public void reportDefaultNetworkStatus(boolean report) {
14157         try {
14158             ITelephony service = getITelephony();
14159             if (service != null) {
14160                 service.carrierActionReportDefaultNetworkStatus(
14161                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
14162             }
14163         } catch (RemoteException e) {
14164             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
14165         }
14166     }
14167 
14168     /**
14169      * Reset all carrier actions previously set by {@link #setRadioEnabled},
14170      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
14171      *
14172      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14173      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14174      *
14175      * <p>Requires Permission:
14176      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14177      * @throws UnsupportedOperationException If the device does not have
14178      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
14179      * @hide
14180      */
14181     @SystemApi
14182     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14183     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
resetAllCarrierActions()14184     public void resetAllCarrierActions() {
14185         try {
14186             ITelephony service = getITelephony();
14187             if (service != null) {
14188                 service.carrierActionResetAll(
14189                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
14190             }
14191         } catch (RemoteException e) {
14192             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
14193         }
14194     }
14195 
14196     /**
14197      * Policy control of data connection. Usually used when data limit is passed.
14198      * @param enabled True if enabling the data, otherwise disabling.
14199      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
14200      * reason {@link #DATA_ENABLED_REASON_POLICY}} instead.
14201      * @hide
14202      */
14203     @Deprecated
14204     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setPolicyDataEnabled(boolean enabled)14205     public void setPolicyDataEnabled(boolean enabled) {
14206         try {
14207             setDataEnabledForReason(DATA_ENABLED_REASON_POLICY, enabled);
14208         } catch (RuntimeException e) {
14209             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
14210         }
14211     }
14212 
14213     /** @hide */
14214     @IntDef({
14215             DATA_ENABLED_REASON_USER,
14216             DATA_ENABLED_REASON_POLICY,
14217             DATA_ENABLED_REASON_CARRIER,
14218             DATA_ENABLED_REASON_THERMAL
14219     })
14220     @Retention(RetentionPolicy.SOURCE)
14221     public @interface DataEnabledReason{}
14222 
14223     /** @hide */
14224     @IntDef({
14225             DATA_ENABLED_REASON_UNKNOWN,
14226             DATA_ENABLED_REASON_USER,
14227             DATA_ENABLED_REASON_POLICY,
14228             DATA_ENABLED_REASON_CARRIER,
14229             DATA_ENABLED_REASON_THERMAL,
14230             DATA_ENABLED_REASON_OVERRIDE
14231     })
14232     @Retention(RetentionPolicy.SOURCE)
14233     public @interface DataEnabledChangedReason{}
14234 
14235     /**
14236      * To indicate that data was enabled or disabled due to an unknown reason.
14237      * Note that this is not a valid reason for {@link #setDataEnabledForReason(int, boolean)} and
14238      * is only used to indicate that data enabled was changed.
14239      */
14240     public static final int DATA_ENABLED_REASON_UNKNOWN = -1;
14241 
14242     /**
14243      * To indicate that user enabled or disabled data.
14244      */
14245     public static final int DATA_ENABLED_REASON_USER = 0;
14246 
14247     /**
14248      * To indicate that data control due to policy. Usually used when data limit is passed.
14249      * Policy data on/off won't affect user settings but will bypass the
14250      * settings and turns off data internally if set to {@code false}.
14251      */
14252     public static final int DATA_ENABLED_REASON_POLICY = 1;
14253 
14254     /**
14255      * To indicate enable or disable carrier data by the system based on carrier signalling or
14256      * carrier privileged apps. Carrier data on/off won't affect user settings but will bypass the
14257      * settings and turns off data internally if set to {@code false}.
14258      */
14259     public static final int DATA_ENABLED_REASON_CARRIER = 2;
14260 
14261     /**
14262      * To indicate enable or disable data by thermal service.
14263      * Thermal data on/off won't affect user settings but will bypass the
14264      * settings and turns off data internally if set to {@code false}.
14265      */
14266     public static final int DATA_ENABLED_REASON_THERMAL = 3;
14267 
14268     /**
14269      * To indicate data was enabled or disabled due to mobile data policy overrides.
14270      * Note that this is not a valid reason for {@link #setDataEnabledForReason(int, boolean)} and
14271      * is only used to indicate that data enabled was changed due to an override.
14272      */
14273     public static final int DATA_ENABLED_REASON_OVERRIDE = 4;
14274 
14275     /**
14276      * Control of data connection and provide the reason triggering the data connection control.
14277      * This can be called for following reasons
14278      * <ol>
14279      * <li>data limit is passed {@link #DATA_ENABLED_REASON_POLICY}
14280      * <li>data disabled by carrier {@link #DATA_ENABLED_REASON_CARRIER}
14281      * <li>data disabled by user {@link #DATA_ENABLED_REASON_USER}
14282      * <li>data disabled due to thermal {@link #DATA_ENABLED_REASON_THERMAL}
14283      * </ol>
14284      * If any of the reason is off, then it will result in
14285      * bypassing user preference and result in data to be turned off.
14286      *
14287      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
14288      *      to the given subId. Otherwise, applies to
14289      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14290      *
14291      *
14292      * @param reason the reason the data enable change is taking place
14293      * @param enabled True if enabling the data, otherwise disabling.
14294      *
14295      * <p>Requires Permission:
14296      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) if the reason is
14297      * {@link #DATA_ENABLED_REASON_USER} or {@link #DATA_ENABLED_REASON_CARRIER} or the call app
14298      * has {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} irrespective of
14299      * the reason.
14300      * @throws IllegalStateException if the Telephony process is not currently available.
14301      * @throws UnsupportedOperationException If the device does not have
14302      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14303      */
14304     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
14305     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabledForReason(@ataEnabledReason int reason, boolean enabled)14306     public void setDataEnabledForReason(@DataEnabledReason int reason, boolean enabled) {
14307         setDataEnabledForReason(getSubId(), reason, enabled);
14308     }
14309 
setDataEnabledForReason(int subId, @DataEnabledReason int reason, boolean enabled)14310     private void setDataEnabledForReason(int subId, @DataEnabledReason int reason,
14311             boolean enabled) {
14312         try {
14313             ITelephony service = getITelephony();
14314             if (service != null) {
14315                 service.setDataEnabledForReason(subId, reason, enabled, getOpPackageName());
14316             } else {
14317                 throw new IllegalStateException("telephony service is null.");
14318             }
14319         } catch (RemoteException ex) {
14320             Log.e(TAG, "Telephony#setDataEnabledForReason RemoteException", ex);
14321             ex.rethrowFromSystemServer();
14322         }
14323     }
14324 
14325     /**
14326      * Return whether data is enabled for certain reason .
14327      *
14328      * If {@link #isDataEnabledForReason} returns false, it means in data enablement for a
14329      * specific reason is turned off. If any of the reason is off, then it will result in
14330      * bypassing user preference and result in data to be turned off. Call
14331      * {@link #isDataConnectionAllowed} in order to know whether
14332      * data connection is allowed on the device.
14333      *
14334      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
14335      *      to the given subId. Otherwise, applies to
14336      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14337      * @param reason the reason the data enable change is taking place
14338      * @return whether data is enabled for a reason.
14339      * <p>Requires Permission:
14340      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) or
14341      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or
14342      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE} or
14343      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}
14344      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE}
14345      * @throws IllegalStateException if the Telephony process is not currently available.
14346      * @throws UnsupportedOperationException If the device does not have
14347      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14348      */
14349     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
14350             android.Manifest.permission.READ_PHONE_STATE,
14351             android.Manifest.permission.MODIFY_PHONE_STATE,
14352             android.Manifest.permission.READ_BASIC_PHONE_STATE
14353     })
14354     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabledForReason(@ataEnabledReason int reason)14355     public boolean isDataEnabledForReason(@DataEnabledReason int reason) {
14356         return isDataEnabledForReason(getSubId(), reason);
14357     }
14358 
isDataEnabledForReason(int subId, @DataEnabledReason int reason)14359     private boolean isDataEnabledForReason(int subId, @DataEnabledReason int reason) {
14360         try {
14361             ITelephony service = getITelephony();
14362             if (service != null) {
14363                 return service.isDataEnabledForReason(subId, reason);
14364             } else {
14365                 throw new IllegalStateException("telephony service is null.");
14366             }
14367         } catch (RemoteException ex) {
14368             Log.e(TAG, "Telephony#isDataEnabledForReason RemoteException", ex);
14369             ex.rethrowFromSystemServer();
14370         }
14371         return false;
14372     }
14373 
14374     /**
14375      * Get Client request stats which will contain statistical information
14376      * on each request made by client.
14377      * Callers require either READ_PRIVILEGED_PHONE_STATE or
14378      * READ_PHONE_STATE to retrieve the information.
14379      * @param subId sub id
14380      * @return List of Client Request Stats
14381      * @hide
14382      */
getClientRequestStats(int subId)14383     public List<ClientRequestStats> getClientRequestStats(int subId) {
14384         try {
14385             ITelephony service = getITelephony();
14386             if (service != null) {
14387                 return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
14388                         subId);
14389             }
14390         } catch (RemoteException e) {
14391             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
14392         }
14393 
14394         return null;
14395     }
14396 
14397     /**
14398      * Checks if phone is in emergency callback mode.
14399      *
14400      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14401      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
14402      *
14403      * @return true if phone is in emergency callback mode.
14404      *
14405      * @throws UnsupportedOperationException If the device does not have
14406      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
14407      * @hide
14408      */
14409     @SystemApi
14410     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14411     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyCallbackMode()14412     public boolean getEmergencyCallbackMode() {
14413         return getEmergencyCallbackMode(getSubId());
14414     }
14415 
14416     /**
14417      * Check if phone is in emergency callback mode
14418      * @return true if phone is in emergency callback mode
14419      * @param subId the subscription ID that this action applies to.
14420      * @hide
14421      */
getEmergencyCallbackMode(int subId)14422     public boolean getEmergencyCallbackMode(int subId) {
14423         try {
14424             ITelephony telephony = getITelephony();
14425             if (telephony == null) {
14426                 return false;
14427             }
14428             return telephony.getEmergencyCallbackMode(subId);
14429         } catch (RemoteException e) {
14430             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
14431         }
14432         return false;
14433     }
14434 
14435     /**
14436      * Checks if manual network selection is allowed.
14437      *
14438      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
14439      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
14440      * (see {@link #hasCarrierPrivileges})
14441      *
14442      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14443      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
14444      *
14445      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
14446      *
14447      * @throws UnsupportedOperationException If the device does not have
14448      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14449      */
14450     @SuppressAutoDoc // No support carrier privileges (b/72967236).
14451     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRECISE_PHONE_STATE,
14452             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
14453     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isManualNetworkSelectionAllowed()14454     public boolean isManualNetworkSelectionAllowed() {
14455         try {
14456             ITelephony telephony = getITelephony();
14457             if (telephony != null) {
14458                 return telephony.isManualNetworkSelectionAllowed(getSubId());
14459             }
14460         } catch (RemoteException e) {
14461             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
14462         }
14463         return true;
14464     }
14465 
14466     /**
14467      * Get the most recently available signal strength information.
14468      *
14469      * Get the most recent SignalStrength information reported by the modem. Due
14470      * to power saving this information may not always be current.
14471      * @return the most recent cached signal strength info from the modem
14472      *
14473      * @throws UnsupportedOperationException If the device does not have
14474      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14475      */
14476     @Nullable
14477     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSignalStrength()14478     public SignalStrength getSignalStrength() {
14479         try {
14480             ITelephony service = getITelephony();
14481             if (service != null) {
14482                 return service.getSignalStrength(getSubId());
14483             }
14484         } catch (RemoteException e) {
14485             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
14486         }
14487         return null;
14488     }
14489 
14490     /**
14491      * Checks whether cellular data connection is allowed in the device.
14492      *
14493      * <p>Whether cellular data connection is allowed considers all factors below:
14494      * <UL>
14495      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
14496      *   <LI>Carrier allows data to be on.</LI>
14497      *   <LI>Network policy.</LI>
14498      *   <LI>And possibly others.</LI>
14499      * </UL>
14500      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
14501      *
14502      * @throws UnsupportedOperationException If the device does not have
14503      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14504      */
14505     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
14506             android.Manifest.permission.READ_PHONE_STATE,
14507             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
14508             android.Manifest.permission.READ_BASIC_PHONE_STATE})
14509     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataConnectionAllowed()14510     public boolean isDataConnectionAllowed() {
14511         boolean retVal = false;
14512         try {
14513             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
14514             ITelephony telephony = getITelephony();
14515             if (telephony != null)
14516                 retVal = telephony.isDataEnabled(subId);
14517         } catch (RemoteException e) {
14518             Log.e(TAG, "Error isDataConnectionAllowed", e);
14519         }
14520         return retVal;
14521     }
14522 
14523     /**
14524      * @return true if the current device is "data capable" over a radio on the device.
14525      * <p>
14526      * "Data capable" means that this device supports packet-switched
14527      * data connections over the telephony network.
14528      * <p>
14529      */
14530     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataCapable()14531     public boolean isDataCapable() {
14532         if (mContext == null) return true;
14533         return mContext.getResources().getBoolean(
14534                 com.android.internal.R.bool.config_mobile_data_capable);
14535     }
14536 
14537     /**
14538      * The indication for signal strength update.
14539      * @hide
14540      */
14541     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
14542 
14543     /**
14544      * The indication for full network state update.
14545      * @hide
14546      */
14547     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
14548 
14549     /**
14550      * The indication for data call dormancy changed update.
14551      * @hide
14552      */
14553     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
14554 
14555     /**
14556      * The indication for link capacity estimate update.
14557      * @hide
14558      */
14559     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
14560 
14561     /**
14562      * The indication for physical channel config update.
14563      * @hide
14564      */
14565     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
14566 
14567     /**
14568      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
14569      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
14570      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
14571      *
14572      * <p>Requires Permission:
14573      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14574      *
14575      *
14576      * @deprecated
14577      * @hide
14578      */
14579     @Deprecated
14580     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)14581     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
14582             String gid2, String plmn, String spn) {
14583         try {
14584             ITelephony telephony = getITelephony();
14585             if (telephony != null) {
14586                 telephony.setCarrierTestOverride(
14587                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
14588                         null, null);
14589             }
14590         } catch (RemoteException ex) {
14591             // This could happen if binder process crashes.
14592         }
14593     }
14594 
14595     /**
14596      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
14597      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
14598      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
14599      * a test SIM with a call box.
14600      *
14601      * <p>Requires Permission:
14602      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14603      *
14604      * @hide
14605      */
14606     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)14607     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
14608                                        String gid2, String plmn, String spn,
14609                                        String carrierPriviledgeRules, String apn) {
14610         try {
14611             ITelephony telephony = getITelephony();
14612             if (telephony != null) {
14613                 telephony.setCarrierTestOverride(
14614                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
14615                         carrierPriviledgeRules, apn);
14616             }
14617         } catch (RemoteException ex) {
14618             // This could happen if binder process crashes.
14619         }
14620     }
14621 
14622     /**
14623      * A test API to return installed carrier id list version
14624      *
14625      * <p>Requires Permission:
14626      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
14627      *
14628      * @hide
14629      */
14630     @UnsupportedAppUsage
14631     @TestApi
getCarrierIdListVersion()14632     public int getCarrierIdListVersion() {
14633         try {
14634             ITelephony telephony = getITelephony();
14635             if (telephony != null) {
14636                 return telephony.getCarrierIdListVersion(getSubId());
14637             }
14638         } catch (RemoteException ex) {
14639             // This could happen if binder process crashes.
14640         }
14641         return UNKNOWN_CARRIER_ID_LIST_VERSION;
14642     }
14643 
14644     /**
14645      * How many modems can have simultaneous data connections.
14646      * @hide
14647      */
14648     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()14649     public int getNumberOfModemsWithSimultaneousDataConnections() {
14650         try {
14651             ITelephony telephony = getITelephony();
14652             if (telephony != null) {
14653                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
14654                         getSubId(), getOpPackageName(), getAttributionTag());
14655             }
14656         } catch (RemoteException ex) {
14657             // This could happen if binder process crashes.
14658         }
14659         return 0;
14660     }
14661 
14662     /**
14663      * Enable or disable OpportunisticNetworkService.
14664      *
14665      * This method should be called to enable or disable
14666      * OpportunisticNetwork service on the device.
14667      *
14668      * <p>
14669      * Requires Permission:
14670      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14671      *
14672      * @param enable enable(True) or disable(False)
14673      * @return returns true if successfully set.
14674      *
14675      * @throws UnsupportedOperationException If the device does not have
14676      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14677      * @hide
14678      */
14679     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14680     @SystemApi
14681     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setOpportunisticNetworkState(boolean enable)14682     public boolean setOpportunisticNetworkState(boolean enable) {
14683         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
14684         boolean ret = false;
14685         try {
14686             IOns iOpportunisticNetworkService = getIOns();
14687             if (iOpportunisticNetworkService != null) {
14688                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
14689             }
14690         } catch (RemoteException ex) {
14691             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
14692         }
14693 
14694         return ret;
14695     }
14696 
14697     /**
14698      * is OpportunisticNetworkService enabled
14699      *
14700      * This method should be called to determine if the OpportunisticNetworkService is
14701      * enabled
14702      *
14703      * <p>
14704      * Requires Permission:
14705      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
14706      *
14707      * @throws UnsupportedOperationException If the device does not have
14708      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14709      * @hide
14710      */
14711     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14712     @SystemApi
14713     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isOpportunisticNetworkEnabled()14714     public boolean isOpportunisticNetworkEnabled() {
14715         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
14716         boolean isEnabled = false;
14717 
14718         try {
14719             IOns iOpportunisticNetworkService = getIOns();
14720             if (iOpportunisticNetworkService != null) {
14721                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
14722             }
14723         } catch (RemoteException ex) {
14724             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
14725         }
14726 
14727         return isEnabled;
14728     }
14729 
14730     /** @hide */
14731     @Retention(RetentionPolicy.SOURCE)
14732     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
14733             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
14734                     NETWORK_TYPE_BITMASK_GSM,
14735                     NETWORK_TYPE_BITMASK_GPRS,
14736                     NETWORK_TYPE_BITMASK_EDGE,
14737                     NETWORK_TYPE_BITMASK_CDMA,
14738                     NETWORK_TYPE_BITMASK_1xRTT,
14739                     NETWORK_TYPE_BITMASK_EVDO_0,
14740                     NETWORK_TYPE_BITMASK_EVDO_A,
14741                     NETWORK_TYPE_BITMASK_EVDO_B,
14742                     NETWORK_TYPE_BITMASK_EHRPD,
14743                     NETWORK_TYPE_BITMASK_HSUPA,
14744                     NETWORK_TYPE_BITMASK_HSDPA,
14745                     NETWORK_TYPE_BITMASK_HSPA,
14746                     NETWORK_TYPE_BITMASK_HSPAP,
14747                     NETWORK_TYPE_BITMASK_UMTS,
14748                     NETWORK_TYPE_BITMASK_TD_SCDMA,
14749                     NETWORK_TYPE_BITMASK_LTE,
14750                     NETWORK_TYPE_BITMASK_LTE_CA,
14751                     NETWORK_TYPE_BITMASK_NR,
14752                     NETWORK_TYPE_BITMASK_IWLAN,
14753                     NETWORK_TYPE_BITMASK_IDEN
14754             })
14755     public @interface NetworkTypeBitMask {}
14756 
14757     // 2G
14758     /**
14759      * network type bitmask unknown.
14760      */
14761     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
14762     /**
14763      * network type bitmask indicating the support of radio tech GSM.
14764      */
14765     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
14766     /**
14767      * network type bitmask indicating the support of radio tech GPRS.
14768      */
14769     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
14770     /**
14771      * network type bitmask indicating the support of radio tech EDGE.
14772      */
14773     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
14774     /**
14775      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
14776      */
14777     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
14778     /**
14779      * network type bitmask indicating the support of radio tech 1xRTT.
14780      */
14781     @SuppressLint("AllUpper")
14782     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
14783     // 3G
14784     /**
14785      * network type bitmask indicating the support of radio tech EVDO 0.
14786      */
14787     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
14788     /**
14789      * network type bitmask indicating the support of radio tech EVDO A.
14790      */
14791     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
14792     /**
14793      * network type bitmask indicating the support of radio tech EVDO B.
14794      */
14795     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
14796     /**
14797      * network type bitmask indicating the support of radio tech EHRPD.
14798      */
14799     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
14800     /**
14801      * network type bitmask indicating the support of radio tech HSUPA.
14802      */
14803     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
14804     /**
14805      * network type bitmask indicating the support of radio tech HSDPA.
14806      */
14807     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
14808     /**
14809      * network type bitmask indicating the support of radio tech HSPA.
14810      */
14811     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
14812     /**
14813      * network type bitmask indicating the support of radio tech iDen.
14814      * @hide
14815      */
14816     public static final long NETWORK_TYPE_BITMASK_IDEN = (1 << (NETWORK_TYPE_IDEN - 1));
14817     /**
14818      * network type bitmask indicating the support of radio tech HSPAP.
14819      */
14820     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
14821     /**
14822      * network type bitmask indicating the support of radio tech UMTS.
14823      */
14824     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
14825     /**
14826      * network type bitmask indicating the support of radio tech TD_SCDMA.
14827      */
14828     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
14829     // 4G
14830     /**
14831      * network type bitmask indicating the support of radio tech LTE.
14832      */
14833     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
14834     /**
14835      * NOT USED; this bitmask is exposed accidentally.
14836      * If used, will be converted to {@link #NETWORK_TYPE_BITMASK_LTE}.
14837      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
14838      *
14839      * @deprecated Please use {@link #NETWORK_TYPE_BITMASK_LTE} instead. Deprecated in Android U.
14840      */
14841     @Deprecated
14842     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
14843 
14844     /**
14845      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
14846      */
14847     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
14848 
14849     /**
14850      * network type bitmask indicating the support of radio tech IWLAN.
14851      */
14852     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
14853 
14854     /** @hide */
14855     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
14856                 | NETWORK_TYPE_BITMASK_GPRS
14857                 | NETWORK_TYPE_BITMASK_EDGE
14858                 | NETWORK_TYPE_BITMASK_CDMA
14859                 | NETWORK_TYPE_BITMASK_1xRTT;
14860 
14861     /** @hide */
14862     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
14863             | NETWORK_TYPE_BITMASK_EVDO_A
14864             | NETWORK_TYPE_BITMASK_EVDO_B
14865             | NETWORK_TYPE_BITMASK_EHRPD
14866             | NETWORK_TYPE_BITMASK_HSUPA
14867             | NETWORK_TYPE_BITMASK_HSDPA
14868             | NETWORK_TYPE_BITMASK_HSPA
14869             | NETWORK_TYPE_BITMASK_HSPAP
14870             | NETWORK_TYPE_BITMASK_UMTS
14871             | NETWORK_TYPE_BITMASK_TD_SCDMA;
14872 
14873     /** @hide */
14874     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
14875             | NETWORK_TYPE_BITMASK_LTE_CA
14876             | NETWORK_TYPE_BITMASK_IWLAN;
14877 
14878     /** @hide */
14879     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
14880 
14881     /** @hide */
14882     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
14883             | NETWORK_TYPE_BITMASK_GPRS
14884             | NETWORK_TYPE_BITMASK_EDGE
14885             | NETWORK_TYPE_BITMASK_HSUPA
14886             | NETWORK_TYPE_BITMASK_HSDPA
14887             | NETWORK_TYPE_BITMASK_HSPA
14888             | NETWORK_TYPE_BITMASK_HSPAP
14889             | NETWORK_TYPE_BITMASK_UMTS
14890             | NETWORK_TYPE_BITMASK_TD_SCDMA
14891             | NETWORK_TYPE_BITMASK_LTE
14892             | NETWORK_TYPE_BITMASK_LTE_CA
14893             | NETWORK_TYPE_BITMASK_NR;
14894 
14895     /** @hide */
14896     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
14897             | NETWORK_TYPE_BITMASK_1xRTT
14898             | NETWORK_TYPE_BITMASK_EVDO_0
14899             | NETWORK_TYPE_BITMASK_EVDO_A
14900             | NETWORK_TYPE_BITMASK_EVDO_B
14901             | NETWORK_TYPE_BITMASK_EHRPD;
14902 
14903     /**
14904      * @return Modem supported radio access family bitmask
14905      *
14906      * <p>Requires permission: android.Manifest.READ_PRIVILEGED_PHONE_STATE or
14907      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
14908      *
14909      * @throws SecurityException if the caller does not have the required permission
14910      * @throws UnsupportedOperationException If the device does not have
14911      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14912      */
14913     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14914     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSupportedRadioAccessFamily()14915     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
14916         try {
14917             ITelephony telephony = getITelephony();
14918             if (telephony != null) {
14919                 return telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
14920             } else {
14921                 // This can happen when the ITelephony interface is not up yet.
14922                 return NETWORK_TYPE_BITMASK_UNKNOWN;
14923             }
14924         } catch (RemoteException ex) {
14925             // This shouldn't happen in the normal case
14926             return NETWORK_TYPE_BITMASK_UNKNOWN;
14927         } catch (NullPointerException ex) {
14928             // This could happen before phone restarts due to crashing
14929             return NETWORK_TYPE_BITMASK_UNKNOWN;
14930         }
14931     }
14932 
14933     /**
14934      * Indicates Emergency number database version is invalid.
14935      *
14936      * @hide
14937      */
14938     @SystemApi
14939     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
14940 
14941     /**
14942      * Notify Telephony for OTA emergency number database installation complete.
14943      *
14944      * <p> Requires permission:
14945      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14946      *
14947      * @throws UnsupportedOperationException If the device does not have
14948      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
14949      * @hide
14950      */
14951     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14952     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
14953     @SystemApi
notifyOtaEmergencyNumberDbInstalled()14954     public void notifyOtaEmergencyNumberDbInstalled() {
14955         try {
14956             ITelephony telephony = getITelephony();
14957             if (telephony != null) {
14958                 telephony.notifyOtaEmergencyNumberDbInstalled();
14959             } else {
14960                 throw new IllegalStateException("telephony service is null.");
14961             }
14962         } catch (RemoteException ex) {
14963             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
14964             ex.rethrowAsRuntimeException();
14965         }
14966     }
14967 
14968     /**
14969      * Override the file path for OTA emergency number database in a file partition.
14970      *
14971      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
14972      *
14973      * <p> Requires permission:
14974      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
14975      *
14976      * @throws UnsupportedOperationException If the device does not have
14977      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
14978      * @hide
14979      */
14980     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
14981     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
14982     @SystemApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)14983     public void updateOtaEmergencyNumberDbFilePath(
14984             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
14985         try {
14986             ITelephony telephony = getITelephony();
14987             if (telephony != null) {
14988                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
14989             } else {
14990                 throw new IllegalStateException("telephony service is null.");
14991             }
14992         } catch (RemoteException ex) {
14993             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
14994             ex.rethrowAsRuntimeException();
14995         }
14996     }
14997 
14998     /**
14999      * Reset the file path to default for OTA emergency number database in a file partition.
15000      *
15001      * <p> Requires permission:
15002      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
15003      *
15004      * @throws UnsupportedOperationException If the device does not have
15005      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
15006      * @hide
15007      */
15008     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
15009     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
15010     @SystemApi
resetOtaEmergencyNumberDbFilePath()15011     public void resetOtaEmergencyNumberDbFilePath() {
15012         try {
15013             ITelephony telephony = getITelephony();
15014             if (telephony != null) {
15015                 telephony.resetOtaEmergencyNumberDbFilePath();
15016             } else {
15017                 throw new IllegalStateException("telephony service is null.");
15018             }
15019         } catch (RemoteException ex) {
15020             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
15021             ex.rethrowAsRuntimeException();
15022         }
15023     }
15024 
15025     /**
15026      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
15027      * available on the device.
15028      * <p>
15029      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
15030      *
15031      * @return {@code true} if emergency assistance is available, {@code false} otherwise
15032      *
15033      * @hide
15034      */
15035     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15036     @SuppressWarnings("AndroidFrameworkClientSidePermissionCheck")
15037     @SystemApi
isEmergencyAssistanceEnabled()15038     public boolean isEmergencyAssistanceEnabled() {
15039         mContext.enforceCallingOrSelfPermission(
15040                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
15041                 "isEmergencyAssistanceEnabled");
15042         return EMERGENCY_ASSISTANCE_ENABLED;
15043     }
15044 
15045     /**
15046      * Get the emergency assistance package name.
15047      *
15048      * @return the package name of the emergency assistance app, or {@code null} if no app
15049      * supports emergency assistance.
15050      * @throws IllegalStateException if emergency assistance is not enabled or the device is
15051      * not voice capable.
15052      *
15053      * @hide
15054      */
15055     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15056     @FlaggedApi(android.permission.flags.Flags.FLAG_GET_EMERGENCY_ROLE_HOLDER_API_ENABLED)
15057     @Nullable
15058     @SystemApi
getEmergencyAssistancePackageName()15059     public String getEmergencyAssistancePackageName() {
15060         if (!isEmergencyAssistanceEnabled() || !isVoiceCapable()) {
15061             throw new IllegalStateException("isEmergencyAssistanceEnabled() is false or device"
15062                 + " not voice capable.");
15063         }
15064         return mContext.getSystemService(RoleManager.class)
15065                 .getEmergencyRoleHolder(mContext.getUserId());
15066     }
15067 
15068     /**
15069      * Get the emergency number list based on current locale, sim, default, modem and network.
15070      *
15071      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
15072      * priority sources will be located at the smaller index; the priority order of sources are:
15073      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
15074      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
15075      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
15076      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
15077      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
15078      *
15079      * <p>The subscriptions which the returned list would be based on, are all the active
15080      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15081      *
15082      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
15083      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
15084      *
15085      * @return Map including the keys as the active subscription IDs (Note: if there is no active
15086      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
15087      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
15088      * or throw a SecurityException if the caller does not have the permission.
15089      *
15090      * @throws UnsupportedOperationException If the device does not have
15091      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
15092      */
15093     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
15094     @NonNull
15095     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyNumberList()15096     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
15097         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
15098         try {
15099             ITelephony telephony = getITelephony();
15100             if (telephony != null) {
15101                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
15102                         mContext.getAttributionTag());
15103             } else {
15104                 throw new IllegalStateException("telephony service is null.");
15105             }
15106         } catch (RemoteException ex) {
15107             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
15108             ex.rethrowAsRuntimeException();
15109         }
15110         return emergencyNumberList;
15111     }
15112 
15113     /**
15114      * Get the per-category emergency number list based on current locale, sim, default, modem
15115      * and network.
15116      *
15117      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
15118      * priority sources will be located at the smaller index; the priority order of sources are:
15119      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
15120      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
15121      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
15122      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
15123      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
15124      *
15125      * <p>The subscriptions which the returned list would be based on, are all the active
15126      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15127      *
15128      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
15129      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
15130      *
15131      * @param categories the emergency service categories which are the bitwise-OR combination of
15132      * the following constants:
15133      * <ol>
15134      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
15135      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
15136      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
15137      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
15138      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
15139      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
15140      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
15141      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
15142      * </ol>
15143      * @return Map including the keys as the active subscription IDs (Note: if there is no active
15144      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
15145      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
15146      * or throw a SecurityException if the caller does not have the permission.
15147      * @throws IllegalStateException if the Telephony process is not currently available.
15148      * @throws UnsupportedOperationException If the device does not have
15149      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
15150      */
15151     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
15152     @NonNull
15153     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyNumberList( @mergencyServiceCategories int categories)15154     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
15155             @EmergencyServiceCategories int categories) {
15156         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
15157         try {
15158             ITelephony telephony = getITelephony();
15159             if (telephony != null) {
15160                 Map<Integer, List<EmergencyNumber>> emergencyNumberList =
15161                         telephony.getEmergencyNumberList(mContext.getOpPackageName(),
15162                                 mContext.getAttributionTag());
15163                 emergencyNumberListForCategories =
15164                         filterEmergencyNumbersByCategories(emergencyNumberList, categories);
15165             } else {
15166                 throw new IllegalStateException("telephony service is null.");
15167             }
15168         } catch (RemoteException ex) {
15169             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
15170             ex.rethrowAsRuntimeException();
15171         }
15172         return emergencyNumberListForCategories;
15173     }
15174 
15175     /**
15176      * Filter emergency numbers with categories.
15177      *
15178      * @hide
15179      */
15180     @VisibleForTesting
filterEmergencyNumbersByCategories( Map<Integer, List<EmergencyNumber>> emergencyNumberList, @EmergencyServiceCategories int categories)15181     public Map<Integer, List<EmergencyNumber>> filterEmergencyNumbersByCategories(
15182             Map<Integer, List<EmergencyNumber>> emergencyNumberList,
15183                     @EmergencyServiceCategories int categories) {
15184         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
15185         if (emergencyNumberList != null) {
15186             for (Integer subscriptionId : emergencyNumberList.keySet()) {
15187                 List<EmergencyNumber> allNumbersForSub = emergencyNumberList.get(
15188                         subscriptionId);
15189                 List<EmergencyNumber> numbersForCategoriesPerSub = new ArrayList<>();
15190                 for (EmergencyNumber number : allNumbersForSub) {
15191                     if (number.isInEmergencyServiceCategories(categories)) {
15192                         numbersForCategoriesPerSub.add(number);
15193                     }
15194                 }
15195                 emergencyNumberListForCategories.put(
15196                         subscriptionId, numbersForCategoriesPerSub);
15197             }
15198         }
15199         return emergencyNumberListForCategories;
15200     }
15201 
15202     /**
15203      * Identifies if the supplied phone number is an emergency number that matches a known
15204      * emergency number based on current locale, SIM card(s), Android database, modem, network,
15205      * or defaults.
15206      *
15207      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
15208      * numbers are not considered emergency numbers. A dialable phone number consists only
15209      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
15210      *
15211      * <p>The subscriptions which the identification would be based on, are all the active
15212      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15213      *
15214      * @param number - the number to look up
15215      * @return {@code true} if the given number is an emergency number based on current locale,
15216      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
15217      * @throws IllegalStateException if the Telephony process is not currently available.
15218      * @throws UnsupportedOperationException If the device does not have
15219      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
15220      */
15221     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isEmergencyNumber(@onNull String number)15222     public boolean isEmergencyNumber(@NonNull String number) {
15223         try {
15224             ITelephony telephony = getITelephony();
15225             if (telephony != null) {
15226                 return telephony.isEmergencyNumber(number, true);
15227             } else {
15228                 throw new IllegalStateException("telephony service is null.");
15229             }
15230         } catch (RemoteException ex) {
15231             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
15232             ex.rethrowAsRuntimeException();
15233         }
15234         return false;
15235     }
15236 
15237     /**
15238      * Checks if the supplied number is an emergency number based on current locale, sim, default,
15239      * modem and network.
15240      *
15241      * <p> Specifically, this method will return {@code true} if the specified number is an
15242      * emergency number, *or* if the number simply starts with the same digits as any current
15243      * emergency number.
15244      *
15245      * <p>The subscriptions which the identification would be based on, are all the active
15246      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15247      *
15248      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
15249      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15250      *
15251      * @param number - the number to look up
15252      * @return {@code true} if the given number is an emergency number or it simply starts with
15253      * the same digits of any current emergency number based on current locale, sim, modem and
15254      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
15255      * have the required permission/privileges
15256      * @throws IllegalStateException if the Telephony process is not currently available.
15257      * @throws UnsupportedOperationException If the device does not have
15258      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
15259      *
15260      * @deprecated Please use {@link TelephonyManager#isEmergencyNumber(String)} instead.
15261      * @hide
15262      */
15263     @Deprecated
15264     @SystemApi
15265     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15266     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isPotentialEmergencyNumber(@onNull String number)15267     public boolean isPotentialEmergencyNumber(@NonNull String number) {
15268         try {
15269             ITelephony telephony = getITelephony();
15270             if (telephony != null) {
15271                 return telephony.isEmergencyNumber(number, false);
15272             } else {
15273                 throw new IllegalStateException("telephony service is null.");
15274             }
15275         } catch (RemoteException ex) {
15276             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
15277             ex.rethrowAsRuntimeException();
15278         }
15279         return false;
15280     }
15281 
15282     /**
15283      * Returns the emergency number database version.
15284      *
15285      * <p>Requires Permission:
15286      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
15287      *
15288      * @throws UnsupportedOperationException If the device does not have
15289      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
15290      * @hide
15291      */
15292     @SystemApi
15293     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15294     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyNumberDbVersion()15295     public int getEmergencyNumberDbVersion() {
15296         try {
15297             ITelephony telephony = getITelephony();
15298             if (telephony != null) {
15299                 return telephony.getEmergencyNumberDbVersion(getSubId());
15300             }
15301         } catch (RemoteException ex) {
15302             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
15303             ex.rethrowAsRuntimeException();
15304         }
15305         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
15306     }
15307 
15308     /** @hide */
15309     @Retention(RetentionPolicy.SOURCE)
15310     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
15311             SET_OPPORTUNISTIC_SUB_SUCCESS,
15312             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
15313             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
15314             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
15315             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
15316     public @interface SetOpportunisticSubscriptionResult {}
15317 
15318     /**
15319      * No error. Operation succeeded.
15320      */
15321     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
15322 
15323     /**
15324      * Validation failed when trying to switch to preferred subscription.
15325      */
15326     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
15327 
15328     /**
15329      * The subscription is not valid. It must be an active opportunistic subscription.
15330      */
15331     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
15332 
15333     /**
15334      * The subscription is not valid. It must be an opportunistic subscription.
15335      */
15336     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
15337 
15338     /**
15339      * Subscription service happened remote exception.
15340      */
15341     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
15342 
15343 
15344     /** @hide */
15345     @Retention(RetentionPolicy.SOURCE)
15346     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
15347             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
15348             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
15349             UPDATE_AVAILABLE_NETWORKS_ABORTED,
15350             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
15351             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
15352             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
15353             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
15354             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
15355             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
15356             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
15357             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED,
15358             UPDATE_AVAILABLE_NETWORKS_SIM_PORT_NOT_AVAILABLE})
15359     public @interface UpdateAvailableNetworksResult {}
15360 
15361     /**
15362      * No error. Operation succeeded.
15363      */
15364     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
15365 
15366     /**
15367      * There is a unknown failure happened.
15368      */
15369     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
15370 
15371     /**
15372      * The request is aborted.
15373      */
15374     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
15375 
15376     /**
15377      * The parameter passed in is invalid.
15378      */
15379     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
15380 
15381     /**
15382      * No carrier privilege.
15383      */
15384     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
15385 
15386     /**
15387      * Disable modem fail.
15388      */
15389     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
15390 
15391     /**
15392      * Enable modem fail.
15393      */
15394     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
15395 
15396     /**
15397      * Carrier app does not support multiple available networks.
15398      */
15399     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
15400 
15401     /**
15402      * The subscription is not valid. It must be an opportunistic subscription.
15403      */
15404     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
15405 
15406     /**
15407      * There is no OpportunisticNetworkService.
15408      */
15409     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
15410 
15411     /**
15412      * OpportunisticNetworkService is disabled.
15413      */
15414     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
15415 
15416     /**
15417      * SIM port is not available to switch to opportunistic subscription.
15418      * @hide
15419      */
15420     public static final int UPDATE_AVAILABLE_NETWORKS_SIM_PORT_NOT_AVAILABLE = 11;
15421 
15422     /**
15423      * Set preferred opportunistic data subscription id.
15424      *
15425      * Switch internet data to preferred opportunistic data subscription id. This api
15426      * can result in lose of internet connectivity for short period of time while internet data
15427      * is handed over.
15428      * <p>Requires that the calling app has carrier privileges on both primary and
15429      * secondary subscriptions (see
15430      * {@link #hasCarrierPrivileges}), or has permission
15431      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
15432      *
15433      * @param subId which opportunistic subscription
15434      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
15435      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
15436      * @param needValidation whether validation is needed before switch happens.
15437      * @param executor The executor of where the callback will execute.
15438      * @param callback Callback will be triggered once it succeeds or failed.
15439      *                 See the {@code SET_OPPORTUNISTIC_SUB_*} constants
15440      *                 for more details. Pass null if don't care about the result.
15441      *
15442      * @throws UnsupportedOperationException If the device does not have
15443      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
15444      */
15445     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)15446     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
15447             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
15448         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15449         try {
15450             IOns iOpportunisticNetworkService = getIOns();
15451             if (iOpportunisticNetworkService == null) {
15452                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
15453                     throw new IllegalStateException("Opportunistic Network Service is null");
15454                 } else {
15455                     // Let the general remote exception handling catch this.
15456                     throw new RemoteException("Null Opportunistic Network Service!");
15457                 }
15458             }
15459             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
15460                 @Override
15461                 public void onComplete(int result) {
15462                     if (executor == null || callback == null) {
15463                         return;
15464                     }
15465                     final long identity = Binder.clearCallingIdentity();
15466                     try {
15467                         executor.execute(() -> {
15468                             callback.accept(result);
15469                         });
15470                     } finally {
15471                         Binder.restoreCallingIdentity(identity);
15472                     }
15473                 }
15474             };
15475 
15476             iOpportunisticNetworkService
15477                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
15478                             pkgForDebug);
15479         } catch (RemoteException ex) {
15480             Rlog.e(TAG, "setPreferredOpportunisticDataSubscription RemoteException", ex);
15481             if (executor == null || callback == null) {
15482                 return;
15483             }
15484             runOnBackgroundThread(() -> executor.execute(() -> {
15485                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
15486                     callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
15487                 } else {
15488                     callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
15489                 }
15490             }));
15491         }
15492     }
15493 
15494     /**
15495      * Get preferred opportunistic data subscription Id
15496      *
15497      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
15498      * or has either READ_PRIVILEGED_PHONE_STATE
15499      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
15500      * @return subId preferred opportunistic subscription id or
15501      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
15502      * subscription id
15503      *
15504      * @throws UnsupportedOperationException If the device does not have
15505      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
15506      */
15507     @RequiresPermission(anyOf = {
15508             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
15509             android.Manifest.permission.READ_PHONE_STATE
15510     })
15511     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getPreferredOpportunisticDataSubscription()15512     public int getPreferredOpportunisticDataSubscription() {
15513         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15514         String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
15515         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
15516         try {
15517             IOns iOpportunisticNetworkService = getIOns();
15518             if (iOpportunisticNetworkService != null) {
15519                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
15520                         packageName, attributionTag);
15521             }
15522         } catch (RemoteException ex) {
15523             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
15524         }
15525         return subId;
15526     }
15527 
15528     /**
15529      * Update availability of a list of networks in the current location.
15530      *
15531      * This api should be called to inform OpportunisticNetwork Service about the availability
15532      * of a network at the current location. This information will be used by OpportunisticNetwork
15533      * service to enable modem stack and to attach to the network. If an empty list is passed,
15534      * it is assumed that no network is available and will result in disabling the modem stack
15535      * to save power. This api do not switch internet data once network attach is completed.
15536      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
15537      * to switch internet data after network attach is complete.
15538      * Requires that the calling app has carrier privileges on both primary and
15539      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
15540      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
15541      * @param availableNetworks is a list of available network information.
15542      * @param executor The executor of where the callback will execute.
15543      * @param callback Callback will be triggered once it succeeds or failed.
15544      *
15545      * @throws UnsupportedOperationException If the device does not have
15546      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
15547      */
15548     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15549     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)15550     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
15551             @Nullable @CallbackExecutor Executor executor,
15552             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
15553         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15554         Objects.requireNonNull(availableNetworks, "availableNetworks must not be null.");
15555         try {
15556             IOns iOpportunisticNetworkService = getIOns();
15557             if (iOpportunisticNetworkService == null) {
15558                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
15559                     throw new IllegalStateException("Opportunistic Network Service is null");
15560                 } else {
15561                     // Let the general remote exception handling catch this.
15562                     throw new RemoteException("Null Opportunistic Network Service!");
15563                 }
15564             }
15565 
15566             IUpdateAvailableNetworksCallback callbackStub =
15567                     new IUpdateAvailableNetworksCallback.Stub() {
15568                         @Override
15569                         public void onComplete(int result) {
15570                             if (executor == null || callback == null) {
15571                                 return;
15572                             }
15573                             Binder.withCleanCallingIdentity(() -> {
15574                                 executor.execute(() -> callback.accept(result));
15575                             });
15576                         }
15577                     };
15578             iOpportunisticNetworkService
15579                     .updateAvailableNetworks(availableNetworks, callbackStub, pkgForDebug);
15580         } catch (RemoteException ex) {
15581             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
15582             if (executor == null || callback == null) {
15583                 return;
15584             }
15585             runOnBackgroundThread(() -> executor.execute(() -> {
15586                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
15587                     callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
15588                 } else {
15589                     callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
15590                 }
15591             }));
15592         }
15593     }
15594 
15595     /**
15596      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
15597      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
15598      * For example, we will disable a modem when user or system believes the corresponding SIM
15599      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
15600      *
15601      * Requires that the calling app has permission
15602      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
15603      * @param slotIndex which corresponding modem will operate on.
15604      * @param enable whether to enable or disable the modem stack.
15605      * @return whether the operation is successful.
15606      *
15607      * @throws UnsupportedOperationException If the device does not have
15608      *          {@link PackageManager#FEATURE_TELEPHONY}.
15609      * @hide
15610      */
15611     @SystemApi
15612     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15613     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
enableModemForSlot(int slotIndex, boolean enable)15614     public boolean enableModemForSlot(int slotIndex, boolean enable) {
15615         boolean ret = false;
15616         try {
15617             ITelephony telephony = getITelephony();
15618             if (telephony != null) {
15619                 ret = telephony.enableModemForSlot(slotIndex, enable);
15620             }
15621         } catch (RemoteException ex) {
15622             Log.e(TAG, "enableModem RemoteException", ex);
15623         }
15624         return ret;
15625     }
15626 
15627     /**
15628      * Indicates whether or not there is a modem stack enabled for the given SIM slot.
15629      *
15630      * <p>Requires Permission:
15631      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE},
15632      * READ_PRIVILEGED_PHONE_STATE or that the calling app has carrier privileges (see
15633      * {@link #hasCarrierPrivileges()}).
15634      *
15635      * @param slotIndex which slot it's checking.
15636      *
15637      * @throws UnsupportedOperationException If the device does not have
15638      *          {@link PackageManager#FEATURE_TELEPHONY}.
15639      */
15640     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15641     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PHONE_STATE,
15642             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
15643     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
isModemEnabledForSlot(int slotIndex)15644     public boolean isModemEnabledForSlot(int slotIndex) {
15645         try {
15646             ITelephony telephony = getITelephony();
15647             if (telephony != null) {
15648                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
15649                         mContext.getAttributionTag());
15650             }
15651         } catch (RemoteException ex) {
15652             Log.e(TAG, "enableModem RemoteException", ex);
15653         }
15654         return false;
15655     }
15656 
15657     /**
15658      * Broadcast intent action for network country code changes.
15659      *
15660      * <p>
15661      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
15662      * network returned by {@link #getNetworkCountryIso()}.
15663      *
15664      * <p>There may be a delay of several minutes before reporting that no country is detected.
15665      *
15666      * @see #EXTRA_NETWORK_COUNTRY
15667      * @see #getNetworkCountryIso()
15668      */
15669     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
15670             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
15671 
15672     /**
15673      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
15674      * the country code in ISO-3166-1 alpha-2 format. This is the same country code returned by
15675      * {@link #getNetworkCountryIso()}. This might be an empty string when the country code is not
15676      * available.
15677      *
15678      * <p class="note">
15679      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
15680      */
15681     public static final String EXTRA_NETWORK_COUNTRY =
15682             "android.telephony.extra.NETWORK_COUNTRY";
15683 
15684     /**
15685      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
15686      * last known the country code in ISO-3166-1 alpha-2 format. This might be an empty string when
15687      * the country code was never available. The last known country code persists across reboot.
15688      *
15689      * <p class="note">
15690      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
15691      */
15692     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
15693             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
15694 
15695     /**
15696      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
15697      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
15698      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
15699      * policies of the carrier.
15700      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
15701      * access to the network.
15702      *
15703      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
15704      * otherwise.
15705      *
15706      * @throws UnsupportedOperationException If the device does not have
15707      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
15708      * @hide
15709      */
15710     @SystemApi
15711     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15712     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)15713     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
15714         try {
15715             ITelephony service = getITelephony();
15716             if (service != null) {
15717                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
15718             }
15719         } catch (RemoteException e) {
15720             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
15721         }
15722     }
15723 
15724     /**
15725      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
15726      * Standby or Dual Active) is supported.
15727      */
15728     public static final int MULTISIM_ALLOWED = 0;
15729 
15730     /**
15731      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
15732      * Standby or Dual Active) is not supported by the hardware.
15733      */
15734     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
15735 
15736     /**
15737      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
15738      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
15739      */
15740     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
15741 
15742     /** @hide */
15743     @Retention(RetentionPolicy.SOURCE)
15744     @IntDef(prefix = {"MULTISIM_"},
15745             value = {
15746                     MULTISIM_ALLOWED,
15747                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
15748                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
15749             })
15750     public @interface IsMultiSimSupportedResult {}
15751 
15752     /**
15753      * Returns if the usage of multiple SIM cards at the same time to register on the network
15754      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
15755      *
15756      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
15757      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15758      *
15759      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
15760      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
15761      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
15762      * functionality is restricted by the carrier.
15763      *
15764      * @throws UnsupportedOperationException If the device does not have
15765      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
15766      */
15767     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15768     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
15769     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
15770     @IsMultiSimSupportedResult
isMultiSimSupported()15771     public int isMultiSimSupported() {
15772         if (getSupportedModemCount() < 2) {
15773             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
15774         }
15775         try {
15776             ITelephony service = getITelephony();
15777             if (service != null) {
15778                 return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
15779             }
15780         } catch (RemoteException e) {
15781             Log.e(TAG, "isMultiSimSupported RemoteException", e);
15782         }
15783         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
15784     }
15785 
15786     /**
15787      * Switch configs to enable multi-sim or switch back to single-sim
15788      * <p>Requires Permission:
15789      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
15790      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15791      *
15792      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
15793      * to single-sim
15794      *
15795      * @param numOfSims number of live SIMs we want to switch to
15796      * @throws android.os.RemoteException
15797      * @throws UnsupportedOperationException If the device does not have
15798      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
15799      */
15800     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15801     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15802     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
switchMultiSimConfig(int numOfSims)15803     public void switchMultiSimConfig(int numOfSims) {
15804         try {
15805             ITelephony telephony = getITelephony();
15806             if (telephony != null) {
15807                 telephony.switchMultiSimConfig(numOfSims);
15808             }
15809         } catch (RemoteException ex) {
15810             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
15811         }
15812     }
15813 
15814     /**
15815      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
15816      * trigger device reboot.
15817      * The modem configuration change refers to switching from single SIM configuration to DSDS
15818      * or the other way around.
15819      *
15820      *  <p>Requires Permission:
15821      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
15822      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15823      *
15824      * @return {@code true} if reboot will be triggered after making changes to modem
15825      * configurations, otherwise return {@code false}.
15826      *
15827      * @throws UnsupportedOperationException If the device does not have
15828      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
15829      */
15830     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
15831     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
doesSwitchMultiSimConfigTriggerReboot()15832     public boolean doesSwitchMultiSimConfigTriggerReboot() {
15833         try {
15834             ITelephony service = getITelephony();
15835             if (service != null) {
15836                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
15837                         getOpPackageName(), getAttributionTag());
15838             }
15839         } catch (RemoteException e) {
15840             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
15841         }
15842         return false;
15843     }
15844 
15845     /**
15846      * Retrieve the Radio HAL Version for this device.
15847      *
15848      * Get the HAL version for the IRadio interface for test purposes.
15849      *
15850      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
15851      *
15852      * @hide
15853      *
15854      * @deprecated Use {@link #getHalVersion} instead.
15855      */
15856     @Deprecated
15857     @UnsupportedAppUsage
15858     @TestApi
getRadioHalVersion()15859     public Pair<Integer, Integer> getRadioHalVersion() {
15860         return getHalVersion(HAL_SERVICE_RADIO);
15861     }
15862 
15863     /** @hide */
15864     public static final int HAL_SERVICE_RADIO = 0;
15865 
15866     /**
15867      * HAL service type that supports the HAL APIs implementation of IRadioData
15868      * {@link RadioDataProxy}
15869      * @hide
15870      */
15871     @TestApi
15872     public static final int HAL_SERVICE_DATA = 1;
15873 
15874     /**
15875      * HAL service type that supports the HAL APIs implementation of IRadioMessaging
15876      * {@link RadioMessagingProxy}
15877      * @hide
15878      */
15879     @TestApi
15880     public static final int HAL_SERVICE_MESSAGING = 2;
15881 
15882     /**
15883      * HAL service type that supports the HAL APIs implementation of IRadioModem
15884      * {@link RadioModemProxy}
15885      * @hide
15886      */
15887     @TestApi
15888     public static final int HAL_SERVICE_MODEM = 3;
15889 
15890     /**
15891      * HAL service type that supports the HAL APIs implementation of IRadioNetwork
15892      * {@link RadioNetworkProxy}
15893      * @hide
15894      */
15895     @TestApi
15896     public static final int HAL_SERVICE_NETWORK = 4;
15897 
15898     /**
15899      * HAL service type that supports the HAL APIs implementation of IRadioSim
15900      * {@link RadioSimProxy}
15901      * @hide
15902      */
15903     @TestApi
15904     public static final int HAL_SERVICE_SIM = 5;
15905 
15906     /**
15907      * HAL service type that supports the HAL APIs implementation of IRadioVoice
15908      * {@link RadioVoiceProxy}
15909      * @hide
15910      */
15911     @TestApi
15912     public static final int HAL_SERVICE_VOICE = 6;
15913 
15914     /**
15915      * HAL service type that supports the HAL APIs implementation of IRadioIms
15916      * {@link RadioImsProxy}
15917      * @hide
15918      */
15919     @TestApi
15920     public static final int HAL_SERVICE_IMS = 7;
15921 
15922     /** @hide */
15923     @Retention(RetentionPolicy.SOURCE)
15924     @IntDef(prefix = {"HAL_SERVICE_"},
15925             value = {
15926                     HAL_SERVICE_RADIO,
15927                     HAL_SERVICE_DATA,
15928                     HAL_SERVICE_MESSAGING,
15929                     HAL_SERVICE_MODEM,
15930                     HAL_SERVICE_NETWORK,
15931                     HAL_SERVICE_SIM,
15932                     HAL_SERVICE_VOICE,
15933                     HAL_SERVICE_IMS,
15934             })
15935     public @interface HalService {}
15936 
15937     /**
15938      * The HAL Version indicating that the version is unknown or invalid.
15939      * @hide
15940      */
15941     @TestApi
15942     public static final Pair HAL_VERSION_UNKNOWN = new Pair(-1, -1);
15943 
15944     /**
15945      * The HAL Version indicating that the version is unsupported.
15946      * @hide
15947      */
15948     @TestApi
15949     public static final Pair HAL_VERSION_UNSUPPORTED = new Pair(-2, -2);
15950 
15951     /**
15952      * Retrieve the HAL Version of a specific service for this device.
15953      *
15954      * Get the HAL version for a specific HAL interface for test purposes.
15955      *
15956      * @param halService the service id to query.
15957      * @return a Pair of (major version, minor version), HAL_VERSION_UNKNOWN if unknown
15958      * or HAL_VERSION_UNSUPPORTED if unsupported.
15959      *
15960      * @hide
15961      */
15962     @TestApi
getHalVersion(@alService int halService)15963     public @NonNull Pair<Integer, Integer> getHalVersion(@HalService int halService) {
15964         try {
15965             ITelephony service = getITelephony();
15966             if (service != null) {
15967                 int version = service.getHalVersion(halService);
15968                 if (version != -1) {
15969                     return new Pair<Integer, Integer>(version / 100, version % 100);
15970                 }
15971             } else {
15972                 throw new IllegalStateException("telephony service is null.");
15973             }
15974         } catch (RemoteException e) {
15975             Log.e(TAG, "getHalVersion() RemoteException", e);
15976             e.rethrowAsRuntimeException();
15977         }
15978         return HAL_VERSION_UNKNOWN;
15979     }
15980 
15981     /**
15982      * Get the calling application status about carrier privileges for the subscription created
15983      * in TelephonyManager. Used by Telephony Module for permission checking.
15984      *
15985      * @param uid Uid to check.
15986      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
15987      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
15988      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
15989      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
15990      *
15991      * @throws UnsupportedOperationException If the device does not have
15992      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
15993      * @hide
15994      */
15995     @SystemApi
15996     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15997     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPrivilegeStatus(int uid)15998     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
15999         try {
16000             ITelephony telephony = getITelephony();
16001             if (telephony != null) {
16002                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
16003             }
16004         } catch (RemoteException ex) {
16005             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
16006         }
16007         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
16008     }
16009 
16010     /**
16011      * Returns a list of APNs set as overrides by the device policy manager via
16012      * {@link #addDevicePolicyOverrideApn}.
16013      * This method must only be called from the system or phone processes.
16014      *
16015      * @param context Context to use.
16016      * @return {@link List} of APNs that have been set as overrides.
16017      * @throws {@link SecurityException} if the caller is not the system or phone process.
16018      * @hide
16019      */
16020     @TestApi
16021     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)16022     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
16023         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
16024             if (cursor == null) {
16025                 return Collections.emptyList();
16026             }
16027             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
16028             cursor.moveToPosition(-1);
16029             while (cursor.moveToNext()) {
16030                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
16031                 apnList.add(apn);
16032             }
16033             return apnList;
16034         }
16035     }
16036 
16037     /**
16038      * Used by the device policy manager to add a new override APN.
16039      * This method must only be called from the system or phone processes.
16040      *
16041      * @param context Context to use.
16042      * @param apnSetting The {@link ApnSetting} describing the new APN.
16043      * @return An integer, corresponding to a primary key in a database, that allows the caller to
16044      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
16045      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
16046      *         failed.
16047      * @throws {@link SecurityException} if the caller is not the system or phone process.
16048      * @hide
16049      */
16050     @TestApi
16051     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)16052     public int addDevicePolicyOverrideApn(@NonNull Context context,
16053             @NonNull ApnSetting apnSetting) {
16054         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
16055 
16056         int resultId = INVALID_APN_ID;
16057         if (resultUri != null) {
16058             try {
16059                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
16060             } catch (NumberFormatException e) {
16061                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
16062                         + resultUri.getLastPathSegment());
16063             }
16064         }
16065         return resultId;
16066     }
16067 
16068     /**
16069      * Used by the device policy manager to modify an override APN.
16070      * This method must only be called from the system or phone processes.
16071      *
16072      * @param context Context to use.
16073      * @param apnId The integer key of the APN to modify, as returned by
16074      *              {@link #addDevicePolicyOverrideApn}
16075      * @param apnSetting The {@link ApnSetting} describing the updated APN.
16076      * @return {@code true} if successful, {@code false} otherwise.
16077      * @throws {@link SecurityException} if the caller is not the system or phone process.
16078      * @hide
16079      */
16080     @TestApi
16081     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)16082     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
16083             @NonNull ApnSetting apnSetting) {
16084         return context.getContentResolver().update(
16085                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
16086                 apnSetting.toContentValues(), null, null) > 0;
16087     }
16088 
16089     /**
16090      * Return whether data is enabled for certain APN type. This will tell if framework will accept
16091      * corresponding network requests on a subId.
16092      *
16093      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
16094      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
16095      *
16096      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
16097      * It will return true if:
16098      *
16099      *  1) User data is turned on, or
16100      *  2) APN is un-metered for this subscription, or
16101      *  3) APN type is allowlisted. E.g. MMS is allowlisted if
16102      *  {@link #MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED} is enabled.
16103      *
16104      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
16105      * @return whether data is enabled for a apn type.
16106      *
16107      * @throws UnsupportedOperationException If the device does not have
16108      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
16109      * @hide
16110      */
16111     @SystemApi
16112     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16113     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabledForApn(@pnType int apnType)16114     public boolean isDataEnabledForApn(@ApnType int apnType) {
16115         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
16116         try {
16117             ITelephony service = getITelephony();
16118             if (service != null) {
16119                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
16120             }
16121         } catch (RemoteException ex) {
16122             Rlog.e(TAG, "Telephony#isDataEnabledForApn RemoteException" + ex);
16123         }
16124         return false;
16125     }
16126 
16127     /**
16128      * Whether an APN type is metered or not. It will be evaluated with the subId associated
16129      * with the TelephonyManager instance.
16130      *
16131      * @throws UnsupportedOperationException If the device does not have
16132      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
16133      * @hide
16134      */
16135     @SystemApi
16136     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16137     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isApnMetered(@pnType int apnType)16138     public boolean isApnMetered(@ApnType int apnType) {
16139         try {
16140             ITelephony service = getITelephony();
16141             if (service != null) {
16142                 return service.isApnMetered(apnType, getSubId());
16143             }
16144         } catch (RemoteException ex) {
16145             Rlog.e(TAG, "Telephony#isApnMetered RemoteException" + ex);
16146         }
16147         return true;
16148     }
16149 
16150     /**
16151      * Specify which bands modem's background scan must act on.
16152      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
16153      * Otherwise, it scans all bands.
16154      *
16155      * For example, CBRS is only on LTE band 48. By specifying this band,
16156      * modem saves more power.
16157      *
16158      * @param specifiers which bands to scan.
16159      * @param executor The executor to execute the callback on
16160      * @param callback The callback that gets invoked when the radio responds to the request. Called
16161      *                 with {@code true} if the request succeeded, {@code false} otherwise.
16162      *
16163      * @throws UnsupportedOperationException If the device does not have
16164      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
16165      * @hide
16166      */
16167     @SystemApi
16168     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16169     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)16170     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
16171             @NonNull @CallbackExecutor Executor executor,
16172             @NonNull Consumer<Boolean> callback) {
16173         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
16174         Objects.requireNonNull(executor, "Executor must not be null.");
16175         Objects.requireNonNull(callback, "Callback must not be null.");
16176         setSystemSelectionChannelsInternal(specifiers, executor, callback);
16177     }
16178 
16179     /**
16180      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
16181      * used when the caller does not need feedback on the results of the operation.
16182      * @param specifiers which bands to scan.
16183      *
16184      * @throws UnsupportedOperationException If the device does not have
16185      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
16186      * @hide
16187      */
16188     @SystemApi
16189     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16190     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)16191     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
16192         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
16193         setSystemSelectionChannelsInternal(specifiers, null, null);
16194     }
16195 
16196 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)16197     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
16198             @Nullable @CallbackExecutor Executor executor,
16199             @Nullable Consumer<Boolean> callback) {
16200         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
16201             @Override
16202             public void accept(boolean result) {
16203                 final long identity = Binder.clearCallingIdentity();
16204                 try {
16205                     executor.execute(() -> callback.accept(result));
16206                 } finally {
16207                     Binder.restoreCallingIdentity(identity);
16208                 }
16209             }
16210         };
16211 
16212         try {
16213             ITelephony service = getITelephony();
16214             if (service != null) {
16215                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
16216             }
16217         } catch (RemoteException ex) {
16218             Rlog.e(TAG, "Telephony#setSystemSelectionChannels RemoteException" + ex);
16219         }
16220     }
16221 
16222     /**
16223      * Get which bands the modem's background scan is acting on, specified by
16224      * {@link #setSystemSelectionChannels}.
16225      *
16226      * <p>Requires Permission:
16227      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
16228      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16229      *
16230      * @return a list of {@link RadioAccessSpecifier}, or an empty list if no bands are specified.
16231      * @throws IllegalStateException if the Telephony process is not currently available.
16232      *
16233      * @throws UnsupportedOperationException If the device does not have
16234      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
16235      * @hide
16236      */
16237     @SystemApi
16238     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16239     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSystemSelectionChannels()16240     public @NonNull List<RadioAccessSpecifier> getSystemSelectionChannels() {
16241         try {
16242             ITelephony service = getITelephony();
16243             if (service != null) {
16244                 return service.getSystemSelectionChannels(getSubId());
16245             } else {
16246                 throw new IllegalStateException("telephony service is null.");
16247             }
16248         } catch (RemoteException ex) {
16249             Rlog.e(TAG, "Telephony#getSystemSelectionChannels RemoteException" + ex);
16250         }
16251         return new ArrayList<>();
16252     }
16253 
16254     /**
16255      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
16256      *
16257      * @param mccmnc the carrier's mccmnc that you want to match
16258      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
16259      * @param mvnoMatchData the MVNO match data
16260      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
16261      * {@code false} otherwise.
16262      *
16263      * @throws UnsupportedOperationException If the device does not have
16264      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16265      * {@hide}
16266      */
16267     @SystemApi
16268     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16269     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
matchesCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)16270     public boolean matchesCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
16271             @Nullable String mvnoMatchData) {
16272         try {
16273             if (!mccmnc.equals(getSimOperator())) {
16274                 return false;
16275             }
16276             ITelephony service = getITelephony();
16277             if (service != null) {
16278                 return service.isMvnoMatched(getSlotIndex(), mvnoType, mvnoMatchData);
16279             }
16280         } catch (RemoteException ex) {
16281             Rlog.e(TAG, "Telephony#matchesCurrentSimOperator RemoteException" + ex);
16282         }
16283         return false;
16284     }
16285 
16286     /**
16287      * Callback to be used with {@link #getCallForwarding}
16288      * @hide
16289      */
16290     @SystemApi
16291     public interface CallForwardingInfoCallback {
16292         /**
16293          * Indicates that the operation was successful.
16294          */
16295         int RESULT_SUCCESS = 0;
16296 
16297         /**
16298          * Indicates that setting or retrieving the call forwarding info failed with an unknown
16299          * error.
16300          */
16301         int RESULT_ERROR_UNKNOWN = 1;
16302 
16303         /**
16304          * Indicates that call forwarding is not enabled because the recipient is not on a
16305          * Fixed Dialing Number (FDN) list.
16306          */
16307         int RESULT_ERROR_FDN_CHECK_FAILURE = 2;
16308 
16309         /**
16310          * Indicates that call forwarding is not supported on the network at this time.
16311          */
16312         int RESULT_ERROR_NOT_SUPPORTED = 3;
16313 
16314         /**
16315          * Call forwarding errors
16316          * @hide
16317          */
16318         @IntDef(prefix = { "RESULT_ERROR_" }, value = {
16319                 RESULT_ERROR_UNKNOWN,
16320                 RESULT_ERROR_NOT_SUPPORTED,
16321                 RESULT_ERROR_FDN_CHECK_FAILURE
16322         })
16323         @Retention(RetentionPolicy.SOURCE)
16324         @interface CallForwardingError{
16325         }
16326         /**
16327          * Called when the call forwarding info is successfully retrieved from the network.
16328          * @param info information about how calls are forwarded
16329          */
onCallForwardingInfoAvailable(@onNull CallForwardingInfo info)16330         void onCallForwardingInfoAvailable(@NonNull CallForwardingInfo info);
16331 
16332         /**
16333          * Called when there was an error retrieving the call forwarding information.
16334          * @param error
16335          */
onError(@allForwardingError int error)16336         void onError(@CallForwardingError int error);
16337     }
16338 
16339     /**
16340      * Gets the voice call forwarding info for a given call forwarding reason.
16341      *
16342      * This method queries the network for the currently set call forwarding configuration for the
16343      * provided call forwarding reason. When the network has provided its response, the result will
16344      * be supplied via the provided {@link Executor} on the provided
16345      * {@link CallForwardingInfoCallback}.
16346      *
16347      * @param callForwardingReason the call forwarding reason to query.
16348      * @param executor The executor on which to execute the callback once the result is ready.
16349      * @param callback The callback the results should be delivered on.
16350      *
16351      * @throws IllegalArgumentException if callForwardingReason is not any of
16352      * {@link CallForwardingInfo#REASON_UNCONDITIONAL}, {@link CallForwardingInfo#REASON_BUSY},
16353      * {@link CallForwardingInfo#REASON_NO_REPLY}, {@link CallForwardingInfo#REASON_NOT_REACHABLE},
16354      * {@link CallForwardingInfo#REASON_ALL}, or {@link CallForwardingInfo#REASON_ALL_CONDITIONAL}
16355      * @throws UnsupportedOperationException If the device does not have
16356      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16357      *
16358      * @hide
16359      */
16360     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16361     @SystemApi
16362     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallForwarding(@allForwardingReason int callForwardingReason, @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback)16363     public void getCallForwarding(@CallForwardingReason int callForwardingReason,
16364             @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback) {
16365         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
16366                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
16367             throw new IllegalArgumentException("callForwardingReason is out of range");
16368         }
16369 
16370         ICallForwardingInfoCallback internalCallback = new ICallForwardingInfoCallback.Stub() {
16371             @Override
16372             public void onCallForwardingInfoAvailable(CallForwardingInfo info) {
16373                 executor.execute(() ->
16374                         Binder.withCleanCallingIdentity(() ->
16375                                 callback.onCallForwardingInfoAvailable(info)));
16376             }
16377 
16378             @Override
16379             public void onError(int error) {
16380                 executor.execute(() ->
16381                         Binder.withCleanCallingIdentity(() ->
16382                                 callback.onError(error)));
16383             }
16384         };
16385 
16386         try {
16387             ITelephony telephony = getITelephony();
16388             if (telephony != null) {
16389                 telephony.getCallForwarding(getSubId(), callForwardingReason, internalCallback);
16390             }
16391         } catch (RemoteException ex) {
16392             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
16393             ex.rethrowAsRuntimeException();
16394         }
16395     }
16396 
16397     /**
16398      * Sets voice call forwarding behavior as described by the provided {@link CallForwardingInfo}.
16399      *
16400      * This method will enable call forwarding if the provided {@link CallForwardingInfo} returns
16401      * {@code true} from its {@link CallForwardingInfo#isEnabled()} method, and disables call
16402      * forwarding otherwise.
16403      *
16404      * If you wish to be notified about the results of this operation, provide an {@link Executor}
16405      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
16406      *
16407      * @param callForwardingInfo Info about whether calls should be forwarded and where they
16408      *                           should be forwarded to.
16409      * @param executor The executor on which the listener will be called. Must be non-null if
16410      *                 {@code listener} is non-null.
16411      * @param resultListener Asynchronous listener that'll be called when the operation completes.
16412      *                      Called with {@link CallForwardingInfoCallback#RESULT_SUCCESS} if the
16413      *                      operation succeeded and an error code from
16414      *                      {@link CallForwardingInfoCallback} it failed.
16415      *
16416      * @throws IllegalArgumentException if any of the following are true for the parameter
16417      * callForwardingInfo:
16418      * <ul>
16419      * <li>it is {@code null}.</li>
16420      * <li>{@link CallForwardingInfo#getReason()} is not any of:
16421      *     <ul>
16422      *         <li>{@link CallForwardingInfo#REASON_UNCONDITIONAL}</li>
16423      *         <li>{@link CallForwardingInfo#REASON_BUSY}</li>
16424      *         <li>{@link CallForwardingInfo#REASON_NO_REPLY}</li>
16425      *         <li>{@link CallForwardingInfo#REASON_NOT_REACHABLE}</li>
16426      *         <li>{@link CallForwardingInfo#REASON_ALL}</li>
16427      *         <li>{@link CallForwardingInfo#REASON_ALL_CONDITIONAL}</li>
16428      *     </ul>
16429      * <li>{@link CallForwardingInfo#getNumber()} returns {@code null} when enabling call
16430      * forwarding</li>
16431      * <li>{@link CallForwardingInfo#getTimeoutSeconds()} returns a non-positive value when
16432      * enabling call forwarding</li>
16433      * </ul>
16434      * @throws UnsupportedOperationException If the device does not have
16435      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16436      * @hide
16437      */
16438     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16439     @SystemApi
16440     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo, @Nullable @CallbackExecutor Executor executor, @Nullable @CallForwardingInfoCallback.CallForwardingError Consumer<Integer> resultListener)16441     public void setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo,
16442             @Nullable @CallbackExecutor Executor executor,
16443             @Nullable @CallForwardingInfoCallback.CallForwardingError
16444                     Consumer<Integer> resultListener) {
16445         if (callForwardingInfo == null) {
16446             throw new IllegalArgumentException("callForwardingInfo is null");
16447         }
16448         int callForwardingReason = callForwardingInfo.getReason();
16449         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
16450                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
16451             throw new IllegalArgumentException("callForwardingReason is out of range");
16452         }
16453         if (callForwardingInfo.isEnabled()) {
16454             if (callForwardingInfo.getNumber() == null) {
16455                 throw new IllegalArgumentException("callForwarding number is null");
16456             }
16457             if (callForwardingReason == CallForwardingInfo.REASON_NO_REPLY
16458                         && callForwardingInfo.getTimeoutSeconds() <= 0) {
16459                 throw new IllegalArgumentException("callForwarding timeout isn't positive");
16460             }
16461         }
16462         if (resultListener != null) {
16463             Objects.requireNonNull(executor);
16464         }
16465 
16466         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
16467             @Override
16468             public void accept(int result) {
16469                 executor.execute(() ->
16470                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
16471             }
16472         };
16473 
16474         try {
16475             ITelephony telephony = getITelephony();
16476             if (telephony != null) {
16477                 telephony.setCallForwarding(getSubId(), callForwardingInfo, internalCallback);
16478             }
16479         } catch (RemoteException ex) {
16480             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
16481             ex.rethrowAsRuntimeException();
16482         } catch (NullPointerException ex) {
16483             Rlog.e(TAG, "setCallForwarding NPE", ex);
16484             throw ex;
16485         }
16486     }
16487 
16488     /**
16489      * Indicates that call waiting is enabled.
16490      *
16491      * @hide
16492      */
16493     @SystemApi
16494     public static final int CALL_WAITING_STATUS_ENABLED = 1;
16495 
16496     /**
16497      * Indicates that call waiting is disabled.
16498      *
16499      * @hide
16500      */
16501     @SystemApi
16502     public static final int CALL_WAITING_STATUS_DISABLED = 2;
16503 
16504     /**
16505      * Indicates there was an unknown error retrieving the call waiting status.
16506      *
16507      * @hide
16508      */
16509     @SystemApi
16510     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
16511 
16512     /**
16513      * Indicates the call waiting is not supported on the current network.
16514      *
16515      * @hide
16516      */
16517     @SystemApi
16518     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
16519 
16520     /**
16521      * Indicates the call waiting status could not be set or queried because the Fixed Dialing
16522      * Numbers (FDN) feature is enabled.
16523      *
16524      * @hide
16525      */
16526     @SystemApi
16527     public static final int CALL_WAITING_STATUS_FDN_CHECK_FAILURE = 5;
16528 
16529     /**
16530      * @hide
16531      */
16532     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
16533             CALL_WAITING_STATUS_ENABLED,
16534             CALL_WAITING_STATUS_DISABLED,
16535             CALL_WAITING_STATUS_UNKNOWN_ERROR,
16536             CALL_WAITING_STATUS_NOT_SUPPORTED,
16537             CALL_WAITING_STATUS_FDN_CHECK_FAILURE,
16538     })
16539     @Retention(RetentionPolicy.SOURCE)
16540     public @interface CallWaitingStatus {
16541     }
16542 
16543     /**
16544      * Retrieves the call waiting status of this device from the network.
16545      *
16546      * When call waiting is enabled, an incoming call that arrives when the user is already on
16547      * an active call will be held in a waiting state while the user is notified instead of being
16548      * rejected with a busy signal.
16549      *
16550      * @param executor The executor on which the result listener will be called.
16551      * @param resultListener A {@link Consumer} that will be called with the result fetched
16552      *                       from the network. The result will be one of:
16553      *                       <ul>
16554      *                          <li>{@link #CALL_WAITING_STATUS_ENABLED}}</li>
16555      *                          <li>{@link #CALL_WAITING_STATUS_DISABLED}}</li>
16556      *                          <li>{@link #CALL_WAITING_STATUS_UNKNOWN_ERROR}}</li>
16557      *                          <li>{@link #CALL_WAITING_STATUS_NOT_SUPPORTED}}</li>
16558      *                          <li>{@link #CALL_WAITING_STATUS_FDN_CHECK_FAILURE}}</li>
16559      *                       </ul>
16560      *
16561      * @throws UnsupportedOperationException If the device does not have
16562      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16563      * @hide
16564      */
16565     @SystemApi
16566     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16567     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallWaitingStatus(@onNull Executor executor, @NonNull @CallWaitingStatus Consumer<Integer> resultListener)16568     public void getCallWaitingStatus(@NonNull Executor executor,
16569             @NonNull @CallWaitingStatus Consumer<Integer> resultListener) {
16570         Objects.requireNonNull(executor);
16571         Objects.requireNonNull(resultListener);
16572 
16573         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
16574             @Override
16575             public void accept(int result) {
16576                 executor.execute(() -> Binder.withCleanCallingIdentity(
16577                         () -> resultListener.accept(result)));
16578             }
16579         };
16580 
16581         try {
16582             ITelephony telephony = getITelephony();
16583             if (telephony != null) {
16584                 telephony.getCallWaitingStatus(getSubId(), internalCallback);
16585             }
16586         } catch (RemoteException ex) {
16587             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
16588             ex.rethrowAsRuntimeException();
16589         } catch (NullPointerException ex) {
16590             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
16591             throw ex;
16592         }
16593     }
16594 
16595     /**
16596      * Sets the call waiting status of this device with the network.
16597      *
16598      * If you wish to be notified about the results of this operation, provide an {@link Executor}
16599      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
16600      *
16601      * @see #getCallWaitingStatus for a description of the call waiting functionality.
16602      *
16603      * @param enabled {@code true} to enable; {@code false} to disable.
16604      * @param executor The executor on which the listener will be called. Must be non-null if
16605      *                 {@code listener} is non-null.
16606      * @param resultListener Asynchronous listener that'll be called when the operation completes.
16607      *                       Called with the new call waiting status (either
16608      *                       {@link #CALL_WAITING_STATUS_ENABLED} or
16609      *                       {@link #CALL_WAITING_STATUS_DISABLED} if the operation succeeded and
16610      *                       {@link #CALL_WAITING_STATUS_NOT_SUPPORTED} or
16611      *                       {@link #CALL_WAITING_STATUS_UNKNOWN_ERROR} or
16612      *                       {@link #CALL_WAITING_STATUS_FDN_CHECK_FAILURE} if it failed.
16613      *
16614      * @throws UnsupportedOperationException If the device does not have
16615      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16616      * @hide
16617      */
16618     @SystemApi
16619     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16620     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallWaitingEnabled(boolean enabled, @Nullable Executor executor, @Nullable Consumer<Integer> resultListener)16621     public void setCallWaitingEnabled(boolean enabled, @Nullable Executor executor,
16622             @Nullable Consumer<Integer> resultListener) {
16623         if (resultListener != null) {
16624             Objects.requireNonNull(executor);
16625         }
16626 
16627         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
16628             @Override
16629             public void accept(int result) {
16630                 executor.execute(() ->
16631                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
16632             }
16633         };
16634 
16635         try {
16636             ITelephony telephony = getITelephony();
16637             if (telephony != null) {
16638                 telephony.setCallWaitingStatus(getSubId(), enabled, internalCallback);
16639             }
16640         } catch (RemoteException ex) {
16641             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
16642             ex.rethrowAsRuntimeException();
16643         } catch (NullPointerException ex) {
16644             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
16645             throw ex;
16646         }
16647     }
16648 
16649     /**
16650      * Controls whether mobile data  on the non-default SIM is allowed during a voice call.
16651      *
16652      * This is used for allowing data on the non-default data SIM when a voice call is placed on
16653      * the non-default data SIM on DSDS devices. If this policy is disabled, users will not be able
16654      * to use mobile data via the non-default data SIM during the call, which may mean no mobile
16655      * data at all since some modem implementations disallow mobile data via the default data SIM
16656      * during voice calls.
16657      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM
16658      * during any voice calls.
16659      *
16660      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
16661      * @hide
16662      */
16663     @SystemApi
16664     public static final int MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL = 1;
16665 
16666     /**
16667      * Controls whether MMS messages bypass the user-specified "mobile data" toggle.
16668      *
16669      * When enabled, requests for connections to the MMS APN will be accepted by telephony even if
16670      * the user has turned "mobile data" off on this specific sim card. {@link #isDataEnabledForApn}
16671      * will also return true for {@link ApnSetting#TYPE_MMS}.
16672      * When disabled, the MMS APN will be governed by the same rules as all other APNs.
16673      *
16674      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
16675      * @hide
16676      */
16677     @SystemApi
16678     public static final int MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED = 2;
16679 
16680     /**
16681      * Allow switching mobile data to the non-default SIM if the non-default SIM has better
16682      * availability.
16683      *
16684      * This is used for temporarily allowing data on the non-default data SIM when on-default SIM
16685      * has better availability on DSDS devices, where better availability means strong
16686      * signal/connectivity.
16687      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM,
16688      * including during any voice calls(equivalent to enabling
16689      * {@link #MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL}).
16690      *
16691      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
16692      * @hide
16693      */
16694     @SystemApi
16695     public static final int MOBILE_DATA_POLICY_AUTO_DATA_SWITCH = 3;
16696 
16697     /**
16698      * @hide
16699      */
16700     @IntDef(prefix = { "MOBILE_DATA_POLICY_" }, value = {
16701             MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL,
16702             MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED,
16703             MOBILE_DATA_POLICY_AUTO_DATA_SWITCH,
16704     })
16705     @Retention(RetentionPolicy.SOURCE)
16706     public @interface MobileDataPolicy { }
16707 
16708     /**
16709      * Enables or disables a piece of mobile data policy.
16710      *
16711      * Enables or disables the mobile data policy specified in {@code policy}. See the detailed
16712      * description of each policy constant for what they do.
16713      *
16714      * @param policy The data policy to enable.
16715      * @param enabled Whether to enable or disable the policy.
16716      *
16717      * @throws UnsupportedOperationException If the device does not have
16718      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
16719      * @hide
16720      */
16721     @SystemApi
16722     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16723     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setMobileDataPolicyEnabled(@obileDataPolicy int policy, boolean enabled)16724     public void setMobileDataPolicyEnabled(@MobileDataPolicy int policy, boolean enabled) {
16725         try {
16726             ITelephony service = getITelephony();
16727             if (service != null) {
16728                 service.setMobileDataPolicyEnabled(getSubId(), policy, enabled);
16729             }
16730         } catch (RemoteException ex) {
16731             Rlog.e(TAG, "Telephony#setMobileDataPolicyEnabled RemoteException" + ex);
16732         }
16733     }
16734 
16735     /**
16736      * Fetches the status of a piece of mobile data policy.
16737      *
16738      * @param policy The data policy that you want the status for.
16739      * @return {@code true} if enabled, {@code false} otherwise.
16740      *
16741      * @throws UnsupportedOperationException If the device does not have
16742      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
16743      * @hide
16744      */
16745     @SystemApi
16746     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16747     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isMobileDataPolicyEnabled(@obileDataPolicy int policy)16748     public boolean isMobileDataPolicyEnabled(@MobileDataPolicy int policy) {
16749         try {
16750             ITelephony service = getITelephony();
16751             if (service != null) {
16752                 return service.isMobileDataPolicyEnabled(getSubId(), policy);
16753             }
16754         } catch (RemoteException ex) {
16755             Rlog.e(TAG, "Telephony#isMobileDataPolicyEnabled RemoteException" + ex);
16756         }
16757         return false;
16758     }
16759 
16760     /**
16761      * Indicates that the ICC PIN lock state or PIN was changed successfully.
16762      * @hide
16763      */
16764     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
16765 
16766     /**
16767      * Check whether ICC PIN lock is enabled.
16768      * This is a sync call which returns the cached PIN enabled state.
16769      *
16770      * @return {@code true} if ICC PIN lock enabled, {@code false} if disabled.
16771      * @throws SecurityException if the caller doesn't have the permission.
16772      * @throws IllegalStateException if the Telephony process is not currently available.
16773      *
16774      * <p>Requires Permission:
16775      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
16776      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16777      *
16778      * @throws UnsupportedOperationException If the device does not have
16779      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16780      * @hide
16781      */
16782     @WorkerThread
16783     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16784     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
16785     @SystemApi
isIccLockEnabled()16786     public boolean isIccLockEnabled() {
16787         try {
16788             ITelephony telephony = getITelephony();
16789             if (telephony != null) {
16790                 return telephony.isIccLockEnabled(getSubId());
16791             } else {
16792                 throw new IllegalStateException("telephony service is null.");
16793             }
16794         } catch (RemoteException e) {
16795             Log.e(TAG, "isIccLockEnabled RemoteException", e);
16796             e.rethrowFromSystemServer();
16797         }
16798         return false;
16799     }
16800 
16801     /**
16802      * Enable or disable the ICC PIN lock.
16803      *
16804      * @param enabled "true" for locked, "false" for unlocked.
16805      * @param pin needed to change the ICC PIN lock, aka. Pin1.
16806      * @return the result of enabling or disabling the ICC PIN lock.
16807      * @throws SecurityException if the caller doesn't have the permission.
16808      * @throws IllegalStateException if the Telephony process is not currently available.
16809      *
16810      * <p>Requires Permission:
16811      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
16812      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
16813      *
16814      * @throws UnsupportedOperationException If the device does not have
16815      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16816      * @hide
16817      */
16818     @SystemApi
16819     @NonNull
16820     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16821     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setIccLockEnabled(boolean enabled, @NonNull String pin)16822     public PinResult setIccLockEnabled(boolean enabled, @NonNull String pin) {
16823         checkNotNull(pin, "setIccLockEnabled pin can't be null.");
16824         try {
16825             ITelephony telephony = getITelephony();
16826             if (telephony != null) {
16827                 int result = telephony.setIccLockEnabled(getSubId(), enabled, pin);
16828                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
16829                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
16830                 } else if (result < 0) {
16831                     return PinResult.getDefaultFailedResult();
16832                 } else {
16833                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
16834                 }
16835             } else {
16836                 throw new IllegalStateException("telephony service is null.");
16837             }
16838         } catch (RemoteException e) {
16839             Log.e(TAG, "setIccLockEnabled RemoteException", e);
16840             e.rethrowFromSystemServer();
16841         }
16842         return PinResult.getDefaultFailedResult();
16843     }
16844 
16845     /**
16846      * Change the ICC lock PIN.
16847      *
16848      * @param oldPin is the old PIN
16849      * @param newPin is the new PIN
16850      * @return The result of changing the ICC lock PIN.
16851      * @throws SecurityException if the caller doesn't have the permission.
16852      * @throws IllegalStateException if the Telephony process is not currently available.
16853      *
16854      * <p>Requires Permission:
16855      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
16856      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
16857      *
16858      * @throws UnsupportedOperationException If the device does not have
16859      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16860      * @hide
16861      */
16862     @SystemApi
16863     @NonNull
16864     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16865     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
changeIccLockPin(@onNull String oldPin, @NonNull String newPin)16866     public PinResult changeIccLockPin(@NonNull String oldPin, @NonNull String newPin) {
16867         checkNotNull(oldPin, "changeIccLockPin oldPin can't be null.");
16868         checkNotNull(newPin, "changeIccLockPin newPin can't be null.");
16869         try {
16870             ITelephony telephony = getITelephony();
16871             if (telephony != null) {
16872                 int result = telephony.changeIccLockPassword(getSubId(), oldPin, newPin);
16873                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
16874                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
16875                 } else if (result < 0) {
16876                     return PinResult.getDefaultFailedResult();
16877                 } else {
16878                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
16879                 }
16880             } else {
16881                 throw new IllegalStateException("telephony service is null.");
16882             }
16883         } catch (RemoteException e) {
16884             Log.e(TAG, "changeIccLockPin RemoteException", e);
16885             e.rethrowFromSystemServer();
16886         }
16887         return PinResult.getDefaultFailedResult();
16888     }
16889 
16890     /**
16891      * Called when userActivity is signalled in the power manager.
16892      * This should only be called from system Uid.
16893      * @hide
16894      */
16895     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
notifyUserActivity()16896     public void notifyUserActivity() {
16897         try {
16898             ITelephony service = getITelephony();
16899             if (service != null) {
16900                 service.userActivity();
16901             }
16902         } catch (RemoteException e) {
16903             // one-way notification, if telephony is not available, it is okay to not throw
16904             // exception here.
16905             Log.w(TAG, "notifyUserActivity exception: " + e.getMessage());
16906         }
16907     }
16908 
16909     /**
16910      * No error. Operation succeeded.
16911      * @hide
16912      */
16913     @SystemApi
16914     public static final int ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS = 0;
16915 
16916     /**
16917      * NR Dual connectivity enablement is not supported.
16918      * @hide
16919      */
16920     @SystemApi
16921     public static final int ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED = 1;
16922 
16923     /**
16924      * Radio is not available.
16925      * @hide
16926      */
16927     @SystemApi
16928     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE = 2;
16929 
16930     /**
16931      * Internal Radio error.
16932      * @hide
16933      */
16934     @SystemApi
16935     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR = 3;
16936 
16937     /**
16938      * Currently in invalid state. Not able to process the request.
16939      * @hide
16940      */
16941     @SystemApi
16942     public static final int ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE = 4;
16943 
16944     /** @hide */
16945     @Retention(RetentionPolicy.SOURCE)
16946     @IntDef(prefix = {"ENABLE_NR_DUAL_CONNECTIVITY"}, value = {
16947             ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS,
16948             ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED,
16949             ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE,
16950             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE,
16951             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR})
16952     public @interface EnableNrDualConnectivityResult {}
16953 
16954     /**
16955      * Enable NR dual connectivity. Enabled state does not mean dual connectivity
16956      * is active. It means device is allowed to connect to both primary and secondary.
16957      *
16958      * @hide
16959      */
16960     @SystemApi
16961     public static final int NR_DUAL_CONNECTIVITY_ENABLE = 1;
16962 
16963     /**
16964      * Disable NR dual connectivity. Disabled state does not mean the secondary cell is released.
16965      * Modem will release it only if the current bearer is released to avoid radio link failure.
16966      * @hide
16967      */
16968     @SystemApi
16969     public static final int NR_DUAL_CONNECTIVITY_DISABLE = 2;
16970 
16971     /**
16972      * Disable NR dual connectivity and force the secondary cell to be released if dual connectivity
16973      * was active. This will result in radio link failure.
16974      * @hide
16975      */
16976     @SystemApi
16977     public static final int NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE = 3;
16978 
16979     /**
16980      * @hide
16981      */
16982     @IntDef(prefix = { "NR_DUAL_CONNECTIVITY_" }, value = {
16983             NR_DUAL_CONNECTIVITY_ENABLE,
16984             NR_DUAL_CONNECTIVITY_DISABLE,
16985             NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE,
16986     })
16987     @Retention(RetentionPolicy.SOURCE)
16988     public @interface NrDualConnectivityState {
16989     }
16990 
16991     /**
16992      * Enable/Disable E-UTRA-NR Dual Connectivity.
16993      *
16994      * This api is supported only if
16995      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
16996      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
16997      * returns true.
16998      * @param nrDualConnectivityState expected NR dual connectivity state
16999      * This can be passed following states
17000      * <ol>
17001      * <li>Enable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_ENABLE}
17002      * <li>Disable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_DISABLE}
17003      * <li>Disable NR dual connectivity and force secondary cell to be released
17004      * {@link #NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE}
17005      * </ol>
17006      * @return operation result.
17007      * @throws IllegalStateException if the Telephony process is not currently available.
17008      * @throws UnsupportedOperationException If the device does not have
17009      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17010      * @hide
17011      */
17012     @SystemApi
17013     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17014     @RequiresFeature(
17015             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
17016             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
setNrDualConnectivityState( @rDualConnectivityState int nrDualConnectivityState)17017     public @EnableNrDualConnectivityResult int setNrDualConnectivityState(
17018             @NrDualConnectivityState int nrDualConnectivityState) {
17019         try {
17020             ITelephony telephony = getITelephony();
17021             if (telephony != null) {
17022                 return telephony.setNrDualConnectivityState(getSubId(), nrDualConnectivityState);
17023             } else {
17024                 throw new IllegalStateException("telephony service is null.");
17025             }
17026         } catch (RemoteException ex) {
17027             Rlog.e(TAG, "setNrDualConnectivityState RemoteException", ex);
17028             ex.rethrowFromSystemServer();
17029         }
17030 
17031         return ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE;
17032     }
17033 
17034     /**
17035      * Is E-UTRA-NR Dual Connectivity enabled.
17036      * This api is supported only if
17037      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
17038      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
17039      * returns true.
17040      * @return true if dual connectivity is enabled else false. Enabled state does not mean dual
17041      * connectivity is active. It means the device is allowed to connect to both primary and
17042      * secondary cell.
17043      * @throws IllegalStateException if the Telephony process is not currently available.
17044      * @throws UnsupportedOperationException If the device does not have
17045      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17046      * @hide
17047      */
17048     @SystemApi
17049     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
17050     @RequiresFeature(
17051             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
17052             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
isNrDualConnectivityEnabled()17053     public boolean isNrDualConnectivityEnabled() {
17054         try {
17055             ITelephony telephony = getITelephony();
17056             if (telephony != null) {
17057                 return telephony.isNrDualConnectivityEnabled(getSubId());
17058             } else {
17059                 throw new IllegalStateException("telephony service is null.");
17060             }
17061         } catch (RemoteException ex) {
17062             Rlog.e(TAG, "isNRDualConnectivityEnabled RemoteException", ex);
17063             ex.rethrowFromSystemServer();
17064         }
17065         return false;
17066     }
17067 
17068     private static class DeathRecipient implements IBinder.DeathRecipient {
17069         @Override
binderDied()17070         public void binderDied() {
17071             resetServiceCache();
17072         }
17073     }
17074 
17075    /**
17076     * Reset everything in the service cache; if one handle died then they are
17077     * all probably broken.
17078     * @hide
17079     */
resetServiceCache()17080     private static void resetServiceCache() {
17081         synchronized (sCacheLock) {
17082             if (sITelephony != null) {
17083                 sITelephony.asBinder().unlinkToDeath(sServiceDeath, 0);
17084                 sITelephony = null;
17085             }
17086             if (sISub != null) {
17087                 sISub.asBinder().unlinkToDeath(sServiceDeath, 0);
17088                 sISub = null;
17089                 SubscriptionManager.clearCaches();
17090             }
17091             if (sISms != null) {
17092                 sISms.asBinder().unlinkToDeath(sServiceDeath, 0);
17093                 sISms = null;
17094             }
17095             if (sIPhoneSubInfo != null) {
17096                 sIPhoneSubInfo.asBinder().unlinkToDeath(sServiceDeath, 0);
17097                 sIPhoneSubInfo = null;
17098             }
17099         }
17100     }
17101 
17102     /**
17103      * @hide
17104      */
getSubscriberInfoService()17105     static IPhoneSubInfo getSubscriberInfoService() {
17106         // Keeps cache disabled until test fixes are checked into AOSP.
17107         if (!sServiceHandleCacheEnabled) {
17108             return IPhoneSubInfo.Stub.asInterface(
17109                 TelephonyFrameworkInitializer
17110                         .getTelephonyServiceManager()
17111                         .getPhoneSubServiceRegisterer()
17112                         .get());
17113         }
17114 
17115         if (sIPhoneSubInfo == null) {
17116             IPhoneSubInfo temp = IPhoneSubInfo.Stub.asInterface(
17117                     TelephonyFrameworkInitializer
17118                         .getTelephonyServiceManager()
17119                         .getPhoneSubServiceRegisterer()
17120                         .get());
17121             synchronized (sCacheLock) {
17122                 if (sIPhoneSubInfo == null && temp != null) {
17123                     try {
17124                         sIPhoneSubInfo = temp;
17125                         sIPhoneSubInfo.asBinder().linkToDeath(sServiceDeath, 0);
17126                     } catch (Exception e) {
17127                         // something has gone horribly wrong
17128                         sIPhoneSubInfo = null;
17129                     }
17130                 }
17131             }
17132         }
17133         return sIPhoneSubInfo;
17134     }
17135 
17136    /**
17137     * @hide
17138     */
getSubscriptionService()17139     static ISub getSubscriptionService() {
17140         // Keeps cache disabled until test fixes are checked into AOSP.
17141         if (!sServiceHandleCacheEnabled) {
17142             return ISub.Stub.asInterface(
17143                     TelephonyFrameworkInitializer
17144                             .getTelephonyServiceManager()
17145                             .getSubscriptionServiceRegisterer()
17146                             .get());
17147         }
17148 
17149         if (sISub == null) {
17150             ISub temp = ISub.Stub.asInterface(
17151                     TelephonyFrameworkInitializer
17152                             .getTelephonyServiceManager()
17153                             .getSubscriptionServiceRegisterer()
17154                             .get());
17155             synchronized (sCacheLock) {
17156                 if (sISub == null && temp != null) {
17157                     try {
17158                         sISub = temp;
17159                         sISub.asBinder().linkToDeath(sServiceDeath, 0);
17160                     } catch (Exception e) {
17161                         // something has gone horribly wrong
17162                         sISub = null;
17163                     }
17164                 }
17165             }
17166         }
17167         return sISub;
17168     }
17169 
17170     /**
17171     * @hide
17172     */
getSmsService()17173     static ISms getSmsService() {
17174         // Keeps cache disabled until test fixes are checked into AOSP.
17175         if (!sServiceHandleCacheEnabled) {
17176             return ISms.Stub.asInterface(
17177                     TelephonyFrameworkInitializer
17178                             .getTelephonyServiceManager()
17179                             .getSmsServiceRegisterer()
17180                             .get());
17181         }
17182 
17183         if (sISms == null) {
17184             ISms temp = ISms.Stub.asInterface(
17185                     TelephonyFrameworkInitializer
17186                             .getTelephonyServiceManager()
17187                             .getSmsServiceRegisterer()
17188                             .get());
17189             synchronized (sCacheLock) {
17190                 if (sISms == null && temp != null) {
17191                     try {
17192                         sISms = temp;
17193                         sISms.asBinder().linkToDeath(sServiceDeath, 0);
17194                     } catch (Exception e) {
17195                         // something has gone horribly wrong
17196                         sISms = null;
17197                     }
17198                 }
17199             }
17200         }
17201         return sISms;
17202     }
17203 
17204     /**
17205      * Disables service handle caching for tests that utilize mock services.
17206      * @hide
17207      */
17208     @VisibleForTesting
disableServiceHandleCaching()17209     public static void disableServiceHandleCaching() {
17210         sServiceHandleCacheEnabled = false;
17211     }
17212 
17213     /**
17214      * Reenables service handle caching.
17215      * @hide
17216      */
17217     @VisibleForTesting
enableServiceHandleCaching()17218     public static void enableServiceHandleCaching() {
17219         sServiceHandleCacheEnabled = true;
17220     }
17221 
17222     /**
17223      * Setup sITelephony for testing.
17224      * @hide
17225      */
17226     @VisibleForTesting
setupITelephonyForTest(ITelephony telephony)17227     public static void setupITelephonyForTest(ITelephony telephony) {
17228         sITelephony = telephony;
17229     }
17230 
17231     /**
17232      * Setup sIPhoneSubInfo for testing.
17233      *
17234      * @hide
17235      */
17236     @VisibleForTesting
setupIPhoneSubInfoForTest(IPhoneSubInfo iPhoneSubInfo)17237     public static void setupIPhoneSubInfoForTest(IPhoneSubInfo iPhoneSubInfo) {
17238         synchronized (sCacheLock) {
17239             sIPhoneSubInfo = iPhoneSubInfo;
17240         }
17241     }
17242 
17243     /**
17244      * Setup sISub for testing.
17245      *
17246      * @hide
17247      */
17248     @VisibleForTesting
setupISubForTest(ISub iSub)17249     public static void setupISubForTest(ISub iSub) {
17250         synchronized (sCacheLock) {
17251             sISub = iSub;
17252         }
17253     }
17254 
17255     /**
17256      * Whether device can connect to 5G network when two SIMs are active.
17257      *
17258      * @hide TODO b/153669716: remove or make system API.
17259      */
canConnectTo5GInDsdsMode()17260     public boolean canConnectTo5GInDsdsMode() {
17261         ITelephony telephony = getITelephony();
17262         if (telephony == null) return true;
17263         try {
17264             return telephony.canConnectTo5GInDsdsMode();
17265         } catch (RemoteException ex) {
17266             return true;
17267         } catch (NullPointerException ex) {
17268             return true;
17269         }
17270     }
17271 
17272     /**
17273      * Returns a list of the equivalent home PLMNs (EF_EHPLMN) from the USIM app.
17274      *
17275      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
17276      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
17277      *
17278      * @return A list of equivalent home PLMNs. Returns an empty list if EF_EHPLMN is empty or
17279      * does not exist on the SIM card.
17280      *
17281      * @throws IllegalStateException if the Telephony process is not currently available.
17282      * @throws SecurityException if the caller doesn't have the permission.
17283      * @throws UnsupportedOperationException If the device does not have
17284      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
17285      *
17286      */
17287     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
17288     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getEquivalentHomePlmns()17289     public @NonNull List<String> getEquivalentHomePlmns() {
17290         try {
17291             ITelephony telephony = getITelephony();
17292             if (telephony != null) {
17293                 return telephony.getEquivalentHomePlmns(getSubId(), mContext.getOpPackageName(),
17294                         getAttributionTag());
17295             } else {
17296                 throw new IllegalStateException("telephony service is null.");
17297             }
17298         } catch (RemoteException ex) {
17299             Rlog.e(TAG, "Telephony#getEquivalentHomePlmns RemoteException" + ex);
17300         }
17301 
17302         return Collections.emptyList();
17303     }
17304 
17305     /**
17306      * Indicates whether {@link CarrierBandwidth#getSecondaryDownlinkCapacityKbps()} and
17307      * {@link CarrierBandwidth#getSecondaryUplinkCapacityKbps()} are visible.  See comments
17308      * on respective methods for more information.
17309      *
17310      * @hide
17311      */
17312     @SystemApi
17313     public static final String CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE =
17314             "CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE";
17315 
17316     /**
17317      * Indicates whether {@link #setPreferredNetworkType}, {@link
17318      * #setPreferredNetworkTypeBitmask}, {@link #setAllowedNetworkTypes} and
17319      * {@link #setAllowedNetworkTypesForReason} rely on
17320      * setAllowedNetworkTypesBitmap instead of setPreferredNetworkTypesBitmap on the radio
17321      * interface.
17322      *
17323      * @hide
17324      */
17325     @SystemApi
17326     public static final String CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK =
17327             "CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK";
17328 
17329     /**
17330      * Indicates whether {@link #setNrDualConnectivityState()} and
17331      * {@link #isNrDualConnectivityEnabled()} ()} are available.  See comments
17332      * on respective methods for more information.
17333      *
17334      * @hide
17335      */
17336     @SystemApi
17337     public static final String CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE =
17338             "CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE";
17339 
17340     /**
17341      * Indicates whether a data throttling request sent with {@link #sendThermalMitigationRequest}
17342      * is supported. See comments on {@link #sendThermalMitigationRequest} for more information.
17343      *
17344      * @hide
17345      */
17346     @SystemApi
17347     public static final String CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING =
17348             "CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING";
17349 
17350     /**
17351      * Indicates whether {@link #getNetworkSlicingConfiguration} is supported. See comments on
17352      * respective methods for more information.
17353      */
17354     public static final String CAPABILITY_SLICING_CONFIG_SUPPORTED =
17355             "CAPABILITY_SLICING_CONFIG_SUPPORTED";
17356 
17357     /**
17358      * Indicates whether PHYSICAL_CHANNEL_CONFIG HAL1.6 is supported. See comments on
17359      * respective methods for more information.
17360      *
17361      * @hide
17362      */
17363     public static final String CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED =
17364             "CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED";
17365 
17366     /**
17367      * Indicates whether modem supports handling parsed SIM phonebook records through the RIL,
17368      * both batched reads and individual writes.
17369      *
17370      * @hide
17371      */
17372     public static final String CAPABILITY_SIM_PHONEBOOK_IN_MODEM =
17373             "CAPABILITY_SIM_PHONEBOOK_IN_MODEM";
17374 
17375     /**
17376      * A list of the radio interface capability values with public valid constants.
17377      *
17378      * Here is a related list for the systemapi-only valid constants:
17379      *     CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE
17380      *     CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK
17381      *     CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE
17382      *     CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING
17383      *
17384      * @hide
17385      * TODO(b/185508047): Doc generation for mixed public/systemapi StringDefs formats badly.
17386      */
17387     @Retention(RetentionPolicy.SOURCE)
17388     @StringDef(prefix = "CAPABILITY_", value = {
17389             CAPABILITY_SLICING_CONFIG_SUPPORTED,
17390             CAPABILITY_SIM_PHONEBOOK_IN_MODEM,
17391     })
17392     public @interface RadioInterfaceCapability {}
17393 
17394     /**
17395      * Whether the device supports a given capability on the radio interface.
17396      *
17397      * If the capability is not in the set of radio interface capabilities, false is returned.
17398      *
17399      * @param capability the name of the capability to check for
17400      * @return the availability of the capability
17401      *
17402      * @throws UnsupportedOperationException If the device does not have
17403      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17404      */
17405     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isRadioInterfaceCapabilitySupported( @onNull @adioInterfaceCapability String capability)17406     public boolean isRadioInterfaceCapabilitySupported(
17407             @NonNull @RadioInterfaceCapability String capability) {
17408         try {
17409             if (capability == null) return false;
17410 
17411             ITelephony telephony = getITelephony();
17412             if (telephony != null) {
17413                 return telephony.isRadioInterfaceCapabilitySupported(capability);
17414             } else {
17415                 throw new IllegalStateException("telephony service is null.");
17416             }
17417         } catch (RemoteException ex) {
17418             Rlog.e(TAG, "Telephony#isRadioInterfaceCapabilitySupported RemoteException" + ex);
17419         }
17420         return false;
17421     }
17422 
17423     /**
17424      * Indicates that the thermal mitigation request was completed successfully.
17425      *
17426      * @hide
17427      */
17428     @SystemApi
17429     public static final int THERMAL_MITIGATION_RESULT_SUCCESS = 0;
17430 
17431     /**
17432      * Indicates that the thermal mitigation request was not completed because of a modem error.
17433      *
17434      * @hide
17435      */
17436     @SystemApi
17437     public static final int THERMAL_MITIGATION_RESULT_MODEM_ERROR = 1;
17438 
17439     /**
17440      * Indicates that the thermal mitigation request was not completed because the modem is not
17441      * available.
17442      *
17443      * @hide
17444      */
17445     @SystemApi
17446     public static final int THERMAL_MITIGATION_RESULT_MODEM_NOT_AVAILABLE = 2;
17447 
17448     /**
17449      * Indicates that the thermal mitigation request could not power off the radio due to the device
17450      * either being in an active emergency voice call, device pending an emergency call, or any
17451      * other state that would disallow powering off of radio.
17452      *
17453      * @hide
17454      */
17455     @SystemApi
17456     public static final int THERMAL_MITIGATION_RESULT_INVALID_STATE = 3;
17457 
17458     /**
17459      * Indicates that the thermal mitigation request resulted an unknown error.
17460      *
17461      * @hide
17462      */
17463     @SystemApi
17464     public static final int THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR = 4;
17465 
17466     /**
17467      * Thermal mitigation request to control functionalities at modem. Thermal mitigation is done
17468      * per-subscription. Caller must be sure to bind the TelephonyManager instance to subId by
17469      * calling {@link #createForSubscriptionId(int)} if they want thermal mitigation on a specific
17470      * subscription Id. Otherwise, TelephonyManager will use the default subscription.
17471      *
17472      * Calling this does not guarantee that the thermal mitigation action requested was done to
17473      * completion. A thermal module should actively monitor the temperature levels and request an
17474      * appropriate thermal mitigation action. Every action is assumed to be done 'on top of' the
17475      * previous action, where the order of actions from least thermal mitigation to most is as
17476      * follows:
17477      * <ol>
17478      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_DATA_THROTTLING}</li>
17479      *   <ol>
17480      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING}</li>
17481      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}</li>
17482      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER}</li>
17483      *   </ol>
17484      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY}</li>
17485      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}</li>
17486      * </ol>
17487      *
17488      * So, for example, requesting {@link
17489      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will ensure that the
17490      * data on secondary carrier has been disabled before throttling on primary carrier. {@link
17491      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} will ensure that data on both
17492      * primary and secondary have been disabled. {@link
17493      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF} will ensure that voice is
17494      * disabled and that data on both primary and secondary carriers are disabled before turning
17495      * radio off. {@link DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD} is not part of the order
17496      * and can be used at any time during data throttling to hold onto the current level of data
17497      * throttling.
17498      *
17499      * <p> If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}({@link
17500      * #CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING}) returns false, then sending a {@link
17501      * DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD}, {@link
17502      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}, or {@link
17503      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will result in {@link
17504      * IllegalArgumentException} being thrown. However, on devices that do not
17505      * support data throttling, {@link
17506      * DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING} can still be requested in
17507      * order to undo the mitigations above it (i.e {@link
17508      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} and/or {@link
17509      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}). </p>
17510      *
17511      * <p> In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of
17512      * this API must also be listed in the device configuration as an authorized app in
17513      * {@code packages/services/Telephony/res/values/config.xml} under the
17514      * {@code thermal_mitigation_allowlisted_packages} key. </p>
17515      *
17516      * @param thermalMitigationRequest Thermal mitigation request. See {@link
17517      * ThermalMitigationRequest} for details.
17518      *
17519      * @throws IllegalStateException if the Telephony process is not currently available.
17520      * @throws IllegalArgumentException if the thermalMitigationRequest had invalid parameters or
17521      * if the device's modem does not support data throttling.
17522      *
17523      * @throws UnsupportedOperationException If the device does not have
17524      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17525      * @hide
17526      */
17527     @SystemApi
17528     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17529     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
17530     @ThermalMitigationResult
sendThermalMitigationRequest( @onNull ThermalMitigationRequest thermalMitigationRequest)17531     public int sendThermalMitigationRequest(
17532             @NonNull ThermalMitigationRequest thermalMitigationRequest) {
17533         try {
17534             ITelephony telephony = getITelephony();
17535             if (telephony != null) {
17536                 return telephony.sendThermalMitigationRequest(getSubId(), thermalMitigationRequest,
17537                         getOpPackageName());
17538             }
17539             throw new IllegalStateException("telephony service is null.");
17540         } catch (RemoteException ex) {
17541             Log.e(TAG, "Telephony#thermalMitigationRequest RemoteException", ex);
17542             ex.rethrowFromSystemServer();
17543         }
17544         return THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR;
17545     }
17546 
17547     /**
17548      * Registers a callback object to receive notification of changes in specified telephony states.
17549      * <p>
17550      * To register a callback, pass a {@link TelephonyCallback} which implements
17551      * interfaces of events. For example,
17552      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
17553      * {@link TelephonyCallback.ServiceStateListener}.
17554      *
17555      * At registration, and when a specified telephony state changes, the telephony manager invokes
17556      * the appropriate callback method on the callback object and passes the current (updated)
17557      * values.
17558      * <p>
17559      * Note: Be aware of the permission requirements stated on the {@link TelephonyCallback}
17560      * listeners you implement.  Your application must be granted these permissions in order to
17561      * register a {@link TelephonyCallback} which requires them; a {@link SecurityException} will be
17562      * thrown if you do not hold the required permissions for all {@link TelephonyCallback}
17563      * listeners you implement.
17564      * <p>
17565      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
17566      * applies to the given subId. Otherwise, applies to
17567      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
17568      * subIds, pass a separate callback object to each TelephonyManager object created with
17569      * {@link #createForSubscriptionId}.
17570      *
17571      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
17572      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
17573      * {@link SecurityException} will be thrown otherwise.
17574      *
17575      * This API should be used sparingly -- large numbers of callbacks will cause system
17576      * instability. If a process has registered too many callbacks without unregistering them, it
17577      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
17578      *
17579      * @param executor The executor of where the callback will execute.
17580      * @param callback The {@link TelephonyCallback} object to register. The caller should hold a
17581      * reference to the callback. The framework only holds a weak reference.
17582      */
registerTelephonyCallback(@onNull @allbackExecutor Executor executor, @NonNull TelephonyCallback callback)17583     public void registerTelephonyCallback(@NonNull @CallbackExecutor Executor executor,
17584             @NonNull TelephonyCallback callback) {
17585         registerTelephonyCallback(getLocationData(), executor, callback);
17586     }
17587 
getLocationData()17588     private int getLocationData() {
17589         boolean renounceCoarseLocation =
17590                 getRenouncedPermissions().contains(Manifest.permission.ACCESS_COARSE_LOCATION);
17591         boolean renounceFineLocation =
17592                 getRenouncedPermissions().contains(Manifest.permission.ACCESS_FINE_LOCATION);
17593         if (renounceCoarseLocation) {
17594             return INCLUDE_LOCATION_DATA_NONE;
17595         } else if (renounceFineLocation) {
17596             return INCLUDE_LOCATION_DATA_COARSE;
17597         } else {
17598             return INCLUDE_LOCATION_DATA_FINE;
17599         }
17600     }
17601 
17602     /** @hide */
17603     @Retention(RetentionPolicy.SOURCE)
17604     @IntDef(prefix = {"INCLUDE_LOCATION_DATA_"}, value = {
17605             INCLUDE_LOCATION_DATA_NONE,
17606             INCLUDE_LOCATION_DATA_COARSE,
17607             INCLUDE_LOCATION_DATA_FINE})
17608     public @interface IncludeLocationData {}
17609 
17610     /**
17611      * Specifies to not include any location related data.
17612      *
17613      * Indicates whether the caller would not like to receive
17614      * location related information which will be sent if the caller already possess
17615      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the
17616      * permissions.
17617      */
17618     public static final int INCLUDE_LOCATION_DATA_NONE = 0;
17619 
17620     /**
17621      * Include coarse location data.
17622      *
17623      * Indicates whether the caller would not like to receive
17624      * location related information which will be sent if the caller already possess
17625      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the
17626      * permissions.
17627      */
17628     public static final int INCLUDE_LOCATION_DATA_COARSE = 1;
17629 
17630     /**
17631      * Include fine location data.
17632      *
17633      * Indicates whether the caller would not like to receive
17634      * location related information which will be sent if the caller already possess
17635      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and do not renounce the
17636      * permissions.
17637      */
17638     public static final int INCLUDE_LOCATION_DATA_FINE = 2;
17639 
17640     /**
17641      * Registers a callback object to receive notification of changes in specified telephony states.
17642      * <p>
17643      * To register a callback, pass a {@link TelephonyCallback} which implements
17644      * interfaces of events. For example,
17645      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
17646      * {@link TelephonyCallback.ServiceStateListener}.
17647      *
17648      * At registration, and when a specified telephony state changes, the telephony manager invokes
17649      * the appropriate callback method on the callback object and passes the current (updated)
17650      * values.
17651      * <p>
17652      *
17653      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
17654      * applies to the given subId. Otherwise, applies to
17655      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
17656      * subIds, pass a separate callback object to each TelephonyManager object created with
17657      * {@link #createForSubscriptionId}.
17658      *
17659      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
17660      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
17661      * {@link SecurityException} will be thrown otherwise.
17662      *
17663      * This API should be used sparingly -- large numbers of callbacks will cause system
17664      * instability. If a process has registered too many callbacks without unregistering them, it
17665      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
17666      *
17667      * <p>
17668      * There's another way to renounce permissions with a custom context
17669      * {@code AttributionSource.Builder#setRenouncedPermissions(Set<String>)} but only for system
17670      * apps. To avoid confusion, calling this method supersede renouncing permissions with a
17671      * custom context.
17672      *
17673      * @param includeLocationData Specifies if the caller would like to receive
17674      * location related information.
17675      * @param executor The executor of where the callback will execute.
17676      * @param callback The {@link TelephonyCallback} object to register. The caller should hold a
17677      * reference to the callback. The framework only holds a weak reference.
17678      */
registerTelephonyCallback(@ncludeLocationData int includeLocationData, @NonNull @CallbackExecutor Executor executor, @NonNull TelephonyCallback callback)17679     public void registerTelephonyCallback(@IncludeLocationData int includeLocationData,
17680             @NonNull @CallbackExecutor Executor executor,
17681             @NonNull TelephonyCallback callback) {
17682         if (mContext == null) {
17683             throw new IllegalStateException("telephony service is null.");
17684         }
17685 
17686         if (executor == null || callback == null) {
17687             throw new IllegalArgumentException("TelephonyCallback and executor must be non-null");
17688         }
17689         mTelephonyRegistryMgr = (TelephonyRegistryManager)
17690                 mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
17691         if (mTelephonyRegistryMgr != null) {
17692             mTelephonyRegistryMgr.registerTelephonyCallback(
17693                     includeLocationData != INCLUDE_LOCATION_DATA_FINE,
17694                     includeLocationData == INCLUDE_LOCATION_DATA_NONE,
17695                     executor, mSubId, getOpPackageName(),
17696                     getAttributionTag(), callback, getITelephony() != null);
17697         } else {
17698             throw new IllegalStateException("telephony service is null.");
17699         }
17700     }
17701 
17702     /**
17703      * Unregister an existing {@link TelephonyCallback}.
17704      *
17705      * @param callback The {@link TelephonyCallback} object to unregister.
17706      */
unregisterTelephonyCallback(@onNull TelephonyCallback callback)17707     public void unregisterTelephonyCallback(@NonNull TelephonyCallback callback) {
17708 
17709         if (mContext == null) {
17710             throw new IllegalStateException("telephony service is null.");
17711         }
17712 
17713         if (callback.callback == null) {
17714             return;
17715         }
17716 
17717         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
17718         if (mTelephonyRegistryMgr != null) {
17719             mTelephonyRegistryMgr.unregisterTelephonyCallback(mSubId, getOpPackageName(),
17720                     getAttributionTag(), callback, getITelephony() != null);
17721         } else {
17722             throw new IllegalStateException("telephony service is null.");
17723         }
17724     }
17725 
17726     /** @hide */
17727     @Retention(RetentionPolicy.SOURCE)
17728     @IntDef(prefix = {"GBA_FAILURE_REASON_"}, value = {
17729             GBA_FAILURE_REASON_UNKNOWN,
17730             GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED,
17731             GBA_FAILURE_REASON_FEATURE_NOT_READY,
17732             GBA_FAILURE_REASON_NETWORK_FAILURE,
17733             GBA_FAILURE_REASON_INCORRECT_NAF_ID,
17734             GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED})
17735     public @interface AuthenticationFailureReason {}
17736 
17737     /**
17738      * GBA Authentication has failed for an unknown reason.
17739      *
17740      * <p>The caller should retry a message that failed with this response.
17741      * @hide
17742      */
17743     @SystemApi
17744     public static final int GBA_FAILURE_REASON_UNKNOWN = 0;
17745 
17746     /**
17747      * GBA Authentication is not supported by the carrier, SIM or android.
17748      *
17749      * <p>Application should use other authentication mechanisms if possible.
17750      * @hide
17751      */
17752     @SystemApi
17753     public static final int GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED = 1;
17754 
17755     /**
17756      * GBA Authentication service is not ready for use.
17757      *
17758      * <p>Application could try again at a later time.
17759      * @hide
17760      */
17761     @SystemApi
17762     public static final int GBA_FAILURE_REASON_FEATURE_NOT_READY = 2;
17763 
17764     /**
17765      * GBA Authentication has been failed by the network.
17766      * @hide
17767      */
17768     @SystemApi
17769     public static final int GBA_FAILURE_REASON_NETWORK_FAILURE = 3;
17770 
17771     /**
17772      * GBA Authentication has failed due to incorrect NAF URL.
17773      * @hide
17774      */
17775     @SystemApi
17776     public static final int GBA_FAILURE_REASON_INCORRECT_NAF_ID = 4;
17777 
17778     /**
17779      * GBA Authentication has failed due to unsupported security protocol
17780      * @hide
17781      */
17782     @SystemApi
17783     public static final int GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED = 5;
17784 
17785     /**
17786      * The callback associated with a {@link #bootstrapAuthenticationRequest()}.
17787      * @hide
17788      */
17789     @SystemApi
17790     public static class BootstrapAuthenticationCallback {
17791 
17792         /**
17793          * Invoked when the previously requested GBA keys are available (@see
17794          * bootstrapAuthenticationRequest()).
17795          * @param gbaKey Ks_NAF/Ks_ext_NAF Response
17796          * @param transactionId Bootstrapping Transaction Identifier
17797          */
onKeysAvailable(@onNull byte[] gbaKey, @NonNull String transactionId)17798         public void onKeysAvailable(@NonNull byte[] gbaKey, @NonNull String transactionId) {}
17799 
17800         /**
17801          * @param reason The reason for the authentication failure.
17802          */
onAuthenticationFailure(@uthenticationFailureReason int reason)17803         public void onAuthenticationFailure(@AuthenticationFailureReason int reason) {}
17804     }
17805 
17806     /**
17807      * Used to get the Generic Bootstrapping Architecture authentication keys
17808      * KsNAF/Ks_ext_NAF for a particular NAF as defined in 3GPP spec TS 33.220 for
17809      * the specified sub id.
17810      *
17811      * <p>Application must be prepared to wait for receiving the Gba keys through the
17812      * registered callback and not invoke the API on the main application thread.
17813      * Application also must call the api to get the fresh key every time instead
17814      * of caching the key.
17815      *
17816      * Following steps may be invoked on the API call depending on the state of the
17817      * underlying GBA implementation:
17818      * <ol>
17819      *     <li>Resolve and bind to a Gba implementation.</li>
17820      *     <li>Run bootstrapping if no valid keys are available or bootstrapping is forced.</li>
17821      *     <li>Generate the ks_NAF/ ks_Ext_NAF to be returned via the callback.</li>
17822      * </ol>
17823      *
17824      * <p> Requires Permission:
17825      * <ul>
17826      *     <li>{@link android.Manifest.permission#MODIFY_PHONE_STATE},</li>
17827      *     <li>{@link android.Manifest.permission#PERFORM_IMS_SINGLE_REGISTRATION},</li>
17828      *     <li>or that the caller has carrier privileges (see
17829      *         {@link TelephonyManager#hasCarrierPrivileges()}).</li>
17830      * </ul>
17831      * @param appType icc application type, like {@link #APPTYPE_USIM} or {@link
17832      * #APPTYPE_ISIM} or {@link#APPTYPE_UNKNOWN}
17833      * @param nafId A URI to specify Network Application Function(NAF) fully qualified domain
17834      * name (FQDN) and the selected GBA mode. The authority of the URI must contain two parts
17835      * delimited by "@" sign. The first part is the constant string "3GPP-bootstrapping" (GBA_ME),
17836      * "3GPP-bootstrapping-uicc" (GBA_ U), or "3GPP-bootstrapping-digest" (GBA_Digest).
17837      * The second part shall be the FQDN of the NAF. The scheme of the URI is not actually used
17838      * for the authentication, which may be set the same as the resource that the application is
17839      * going to access. For example, the nafId can be
17840      * "https://3GPP-bootstrapping@naf1.operator.com",
17841      * "https://3GPP-bootstrapping-uicc@naf1.operator.com",
17842      * "https://3GPP-bootstrapping-digest@naf1.operator.com",
17843      * "ftps://3GPP-bootstrapping-digest@naf1.operator.com".
17844      * @param securityProtocol Security protocol identifier between UE and NAF.  See
17845      * 3GPP TS 33.220 Annex H. Application can use
17846      * {@link UaSecurityProtocolIdentifier#createDefaultUaSpId},
17847      * {@link UaSecurityProtocolIdentifier#create3GppUaSpId},
17848      * to create the ua security protocol identifier as needed
17849      * @param forceBootStrapping true=force bootstrapping, false=do not force
17850      * bootstrapping. Bootstrapping shouldn't be forced unless the application sees
17851      * authentication errors from the server.
17852      * @param e The {@link Executor} that will be used to call the Gba callback.
17853      * @param callback A callback called on the supplied {@link Executor} that will
17854      * contain the GBA Ks_NAF/Ks_ext_NAF when available. If the NAF keys are
17855      * available and valid at the time of call and bootstrapping is not requested,
17856      * then the callback shall be invoked with the available keys.
17857      *
17858      * @throws UnsupportedOperationException If the device does not have
17859      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
17860      * @hide
17861      */
17862     @SystemApi
17863     @WorkerThread
17864     @RequiresPermission(anyOf = {android.Manifest.permission.MODIFY_PHONE_STATE,
17865             Manifest.permission.PERFORM_IMS_SINGLE_REGISTRATION})
17866     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
bootstrapAuthenticationRequest( @iccAppTypeExt int appType, @NonNull Uri nafId, @NonNull UaSecurityProtocolIdentifier securityProtocol, boolean forceBootStrapping, @NonNull Executor e, @NonNull BootstrapAuthenticationCallback callback)17867     public void bootstrapAuthenticationRequest(
17868             @UiccAppTypeExt int appType, @NonNull Uri nafId,
17869             @NonNull UaSecurityProtocolIdentifier securityProtocol,
17870             boolean forceBootStrapping, @NonNull Executor e,
17871             @NonNull BootstrapAuthenticationCallback callback) {
17872         try {
17873             ITelephony service = getITelephony();
17874             if (service == null) {
17875                 e.execute(() -> callback.onAuthenticationFailure(
17876                         GBA_FAILURE_REASON_FEATURE_NOT_READY));
17877                 return;
17878             }
17879             service.bootstrapAuthenticationRequest(
17880                     getSubId(), appType, nafId, securityProtocol, forceBootStrapping,
17881                     new IBootstrapAuthenticationCallback.Stub() {
17882                         @Override
17883                         public void onKeysAvailable(int token, byte[] gbaKey,
17884                                 String transactionId) {
17885                             final long identity = Binder.clearCallingIdentity();
17886                             try {
17887                                 e.execute(() -> callback.onKeysAvailable(gbaKey, transactionId));
17888                             } finally {
17889                                 Binder.restoreCallingIdentity(identity);
17890                             }
17891                         }
17892 
17893                         @Override
17894                         public void onAuthenticationFailure(int token, int reason) {
17895                             final long identity = Binder.clearCallingIdentity();
17896                             try {
17897                                 e.execute(() -> callback.onAuthenticationFailure(reason));
17898                             } finally {
17899                                 Binder.restoreCallingIdentity(identity);
17900                             }
17901                         }
17902                     });
17903         } catch (RemoteException exception) {
17904             Log.e(TAG, "Error calling ITelephony#bootstrapAuthenticationRequest", exception);
17905             e.execute(() -> callback.onAuthenticationFailure(GBA_FAILURE_REASON_FEATURE_NOT_READY));
17906         }
17907     }
17908 
17909     /**
17910      * The network type is valid or not.
17911      *
17912      * @param networkType The network type {@link NetworkType}.
17913      * @return {@code true} if valid, {@code false} otherwise.
17914      *
17915      * @hide
17916      */
isNetworkTypeValid(@etworkType int networkType)17917     public static boolean isNetworkTypeValid(@NetworkType int networkType) {
17918         return networkType >= TelephonyManager.NETWORK_TYPE_UNKNOWN &&
17919                 networkType <= TelephonyManager.NETWORK_TYPE_NR;
17920     }
17921 
17922     /**
17923      * Set a {@link SignalStrengthUpdateRequest} to receive notification when signal quality
17924      * measurements breach the specified thresholds.
17925      *
17926      * To be notified, set the signal strength update request and then register
17927      * {@link TelephonyCallback} that implements {@link TelephonyCallback.SignalStrengthsListener}
17928      * through {@link #registerTelephonyCallback}. The notification will arrive through
17929      * {@link TelephonyCallback.SignalStrengthsListener#onSignalStrengthsChanged(SignalStrength)}.
17930      *
17931      * To stop receiving the notification over the specified thresholds, pass the same
17932      * {@link SignalStrengthUpdateRequest} object to
17933      * {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
17934      *
17935      * System will clean up the {@link SignalStrengthUpdateRequest} if the caller process died
17936      * without calling {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
17937      *
17938      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
17939      * applies to the given subId. Otherwise, applies to
17940      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To request for multiple subIds,
17941      * pass a request object to each TelephonyManager object created with
17942      * {@link #createForSubscriptionId}.
17943      *
17944      * <p>Requires Permission:
17945      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
17946      * or that the calling app has carrier privileges (see
17947      * {@link TelephonyManager#hasCarrierPrivileges}).
17948      *
17949      * Note that the thresholds in the request will be used on a best-effort basis; the system may
17950      * modify requests to multiplex various request sources or to optimize power consumption. The
17951      * caller should not expect to be notified with the exactly the same thresholds.
17952      *
17953      * @see #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
17954      *
17955      * @param request the SignalStrengthUpdateRequest to be set into the System
17956      *
17957      * @throws IllegalStateException if a new request is set with same subId from the same caller
17958      * @throws UnsupportedOperationException If the device does not have
17959      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17960      */
17961     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
17962     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17963     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)17964     public void setSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
17965         Objects.requireNonNull(request, "request must not be null");
17966 
17967         try {
17968             ITelephony service = getITelephony();
17969             if (service != null) {
17970                 service.setSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
17971             }
17972         } catch (RemoteException e) {
17973             Log.e(TAG, "Error calling ITelephony#setSignalStrengthUpdateRequest", e);
17974         }
17975     }
17976 
17977     /**
17978      * Clear a {@link SignalStrengthUpdateRequest} from the system.
17979      *
17980      * <p>Requires Permission:
17981      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
17982      * or that the calling app has carrier privileges (see
17983      * {@link TelephonyManager#hasCarrierPrivileges}).
17984      *
17985      * <p>If the given request was not set before, this operation is a no-op.
17986      *
17987      * @see #setSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
17988      *
17989      * @param request the SignalStrengthUpdateRequest to be cleared from the System
17990      *
17991      * @throws UnsupportedOperationException If the device does not have
17992      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17993      */
17994     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
17995     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17996     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
clearSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)17997     public void clearSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
17998         Objects.requireNonNull(request, "request must not be null");
17999 
18000         try {
18001             ITelephony service = getITelephony();
18002             if (service != null) {
18003                 service.clearSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
18004             }
18005         } catch (RemoteException e) {
18006             Log.e(TAG, "Error calling ITelephony#clearSignalStrengthUpdateRequest", e);
18007         }
18008     }
18009 
18010     /**
18011      * Gets the current phone capability.
18012      *
18013      * @return the PhoneCapability which describes the data connection capability of modem.
18014      * It's used to evaluate possible phone config change, for example from single
18015      * SIM device to multi-SIM device.
18016      *
18017      * @throws UnsupportedOperationException If the device does not have
18018      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
18019      * @hide
18020      */
18021     @SystemApi
18022     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
18023     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getPhoneCapability()18024     public @NonNull PhoneCapability getPhoneCapability() {
18025         try {
18026             ITelephony telephony = getITelephony();
18027             if (telephony != null) {
18028                 return telephony.getPhoneCapability();
18029             } else {
18030                 throw new IllegalStateException("telephony service is null.");
18031             }
18032         } catch (RemoteException ex) {
18033             ex.rethrowAsRuntimeException();
18034         }
18035         if (getActiveModemCount() > 1) {
18036             return PhoneCapability.DEFAULT_DSDS_CAPABILITY;
18037         } else {
18038             return PhoneCapability.DEFAULT_SSSS_CAPABILITY;
18039         }
18040     }
18041 
18042     /**
18043      * The unattended reboot was prepared successfully.
18044      * @hide
18045      */
18046     @SystemApi
18047     public static final int PREPARE_UNATTENDED_REBOOT_SUCCESS = 0;
18048 
18049     /**
18050      * The unattended reboot was prepared, but the user will need to manually
18051      * enter the PIN code of at least one SIM card present in the device.
18052      * @hide
18053      */
18054     @SystemApi
18055     public static final int PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED = 1;
18056 
18057     /**
18058      * The unattended reboot was not prepared due to a non-recoverable error. After this error,
18059      * the client that manages the unattended reboot should not try to invoke the API again
18060      * until the next power cycle.
18061      * @hide
18062      */
18063     @SystemApi
18064     public static final int PREPARE_UNATTENDED_REBOOT_ERROR = 2;
18065 
18066     /** @hide */
18067     @Retention(RetentionPolicy.SOURCE)
18068     @IntDef(prefix = {"PREPARE_UNATTENDED_REBOOT_"},
18069             value = {
18070                     PREPARE_UNATTENDED_REBOOT_SUCCESS,
18071                     PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED,
18072                     PREPARE_UNATTENDED_REBOOT_ERROR
18073             })
18074     public @interface PrepareUnattendedRebootResult {}
18075 
18076     /**
18077      * Prepare TelephonyManager for an unattended reboot. The reboot is required to be done
18078      * shortly (e.g. within 15 seconds) after the API is invoked.
18079      *
18080      * <p>Requires Permission:
18081      *   {@link android.Manifest.permission#REBOOT}
18082      *
18083      * @return {@link #PREPARE_UNATTENDED_REBOOT_SUCCESS} in case of success.
18084      * {@link #PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED} if the device contains
18085      * at least one SIM card for which the user needs to manually enter the PIN
18086      * code after the reboot. {@link #PREPARE_UNATTENDED_REBOOT_ERROR} in case
18087      * of error.
18088      *
18089      * @throws UnsupportedOperationException If the device does not have
18090      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
18091      * @hide
18092      */
18093     @SystemApi
18094     @RequiresPermission(android.Manifest.permission.REBOOT)
18095     @PrepareUnattendedRebootResult
18096     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
prepareForUnattendedReboot()18097     public int prepareForUnattendedReboot() {
18098         try {
18099             ITelephony service = getITelephony();
18100             if (service != null) {
18101                 return service.prepareForUnattendedReboot();
18102             }
18103         } catch (RemoteException e) {
18104             Log.e(TAG, "Telephony#prepareForUnattendedReboot RemoteException", e);
18105             e.rethrowFromSystemServer();
18106         }
18107         return PREPARE_UNATTENDED_REBOOT_ERROR;
18108     }
18109 
18110     /**
18111      * Exception that may be supplied to the callback in {@link #getNetworkSlicingConfiguration} if
18112      * something goes awry.
18113      */
18114     public static class NetworkSlicingException extends Exception {
18115         /**
18116          * Getting the current slicing configuration successfully. Used internally only.
18117          * @hide
18118          */
18119         public static final int SUCCESS = 0;
18120 
18121         /**
18122          * The system timed out waiting for a response from the Radio.
18123          * @hide
18124          */
18125         public static final int ERROR_TIMEOUT = 1;
18126 
18127         /**
18128          * The modem returned a failure.
18129          * @hide
18130          */
18131         public static final int ERROR_MODEM_ERROR = 2;
18132 
18133         /** @hide */
18134         @IntDef(prefix = {"ERROR_"}, value = {
18135                 ERROR_TIMEOUT,
18136                 ERROR_MODEM_ERROR,
18137         })
18138         @Retention(RetentionPolicy.SOURCE)
18139         public @interface NetworkSlicingError {}
18140 
18141         private final int mErrorCode;
18142 
18143         /** @hide */
NetworkSlicingException(@etworkSlicingError int errorCode)18144         public NetworkSlicingException(@NetworkSlicingError int errorCode) {
18145             mErrorCode = errorCode;
18146         }
18147 
18148         @Override
toString()18149         public String toString() {
18150             switch (mErrorCode) {
18151                 case ERROR_TIMEOUT: return "ERROR_TIMEOUT";
18152                 case ERROR_MODEM_ERROR: return "ERROR_MODEM_ERROR";
18153                 default: return "UNDEFINED";
18154             }
18155         }
18156     }
18157 
18158     /**
18159      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
18160      * system timed out waiting for a response from the Radio.
18161      */
18162     public class TimeoutException extends NetworkSlicingException {
18163         /** @hide */
TimeoutException(int errorCode)18164         public TimeoutException(int errorCode) {
18165             super(errorCode);
18166         }
18167     }
18168 
18169     /**
18170      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
18171      * modem returned a failure.
18172      */
18173     public class ModemErrorException extends NetworkSlicingException {
18174         /** @hide */
ModemErrorException(int errorCode)18175         public ModemErrorException(int errorCode) {
18176             super(errorCode);
18177         }
18178     }
18179 
18180     /** @hide */
18181     public static final String KEY_SLICING_CONFIG_HANDLE = "slicing_config_handle";
18182 
18183     /**
18184      * Request to get the current slicing configuration including URSP rules and
18185      * NSSAIs (configured, allowed and rejected).
18186      *
18187      * This method can be invoked if one of the following requirements is met:
18188      * <ul>
18189      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
18190      *     is a privileged permission that can only be granted to apps preloaded on the device.
18191      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
18192      * </ul>
18193      *
18194      * This will be invalid if the device does not support
18195      * android.telephony.TelephonyManager#CAPABILITY_SLICING_CONFIG_SUPPORTED.
18196      *
18197      * @param executor the executor on which callback will be invoked.
18198      * @param callback a callback to receive the current slicing configuration.
18199      *
18200      * @throws UnsupportedOperationException If the device does not have
18201      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
18202      */
18203     @RequiresFeature(
18204             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
18205             value = TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED)
18206     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
18207     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNetworkSlicingConfiguration( @onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback)18208     public void getNetworkSlicingConfiguration(
18209             @NonNull @CallbackExecutor Executor executor,
18210             @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback) {
18211         Objects.requireNonNull(executor);
18212         Objects.requireNonNull(callback);
18213 
18214         try {
18215             ITelephony telephony = getITelephony();
18216             if (telephony == null) {
18217                 throw new IllegalStateException("telephony service is null.");
18218             }
18219             telephony.getSlicingConfig(new ResultReceiver(null) {
18220                     @Override
18221                     protected void onReceiveResult(int resultCode, Bundle result) {
18222                         if (resultCode == NetworkSlicingException.ERROR_TIMEOUT) {
18223                             executor.execute(() -> callback.onError(
18224                                     new TimeoutException(resultCode)));
18225                             return;
18226                         } else if (resultCode == NetworkSlicingException.ERROR_MODEM_ERROR) {
18227                             executor.execute(() -> callback.onError(
18228                                     new ModemErrorException(resultCode)));
18229                             return;
18230                         }
18231 
18232                         NetworkSlicingConfig slicingConfig =
18233                                 result.getParcelable(KEY_SLICING_CONFIG_HANDLE, android.telephony.data.NetworkSlicingConfig.class);
18234                         executor.execute(() -> callback.onResult(slicingConfig));
18235                     }
18236             });
18237         } catch (RemoteException ex) {
18238             ex.rethrowAsRuntimeException();
18239         }
18240     }
18241 
18242     /**
18243      * A premium capability that boosts the network to allow for real-time interactive traffic
18244      * by prioritizing low latency communication.
18245      * Corresponds to {@link NetworkCapabilities#NET_CAPABILITY_PRIORITIZE_LATENCY}.
18246      */
18247     public static final int PREMIUM_CAPABILITY_PRIORITIZE_LATENCY =
18248             NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY;
18249 
18250     /**
18251      * Purchasable premium capabilities.
18252      * @hide
18253      */
18254     @Retention(RetentionPolicy.SOURCE)
18255     @IntDef(prefix = { "PREMIUM_CAPABILITY_" }, value = {
18256             PREMIUM_CAPABILITY_PRIORITIZE_LATENCY})
18257     public @interface PremiumCapability {}
18258 
18259     /**
18260      * Returns the premium capability {@link PremiumCapability} as a String.
18261      *
18262      * @param capability The premium capability.
18263      * @return The premium capability as a String.
18264      * @hide
18265      */
convertPremiumCapabilityToString(@remiumCapability int capability)18266     public static String convertPremiumCapabilityToString(@PremiumCapability int capability) {
18267         switch (capability) {
18268             case PREMIUM_CAPABILITY_PRIORITIZE_LATENCY:
18269                 return "PRIORITIZE_LATENCY";
18270             default:
18271                 return "UNKNOWN (" + capability + ")";
18272         }
18273     }
18274 
18275     /**
18276      * Check whether the given premium capability is available for purchase from the carrier.
18277      * If this is {@code true}, the capability can be purchased from the carrier using
18278      * {@link #purchasePremiumCapability(int, Executor, Consumer)}.
18279      *
18280      * @param capability The premium capability to check.
18281      * @return Whether the given premium capability is available to purchase.
18282      * @throws SecurityException if the caller does not hold permission READ_BASIC_PHONE_STATE.
18283      * @throws UnsupportedOperationException If the device does not have
18284      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
18285      */
18286     @RequiresPermission(android.Manifest.permission.READ_BASIC_PHONE_STATE)
18287     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isPremiumCapabilityAvailableForPurchase(@remiumCapability int capability)18288     public boolean isPremiumCapabilityAvailableForPurchase(@PremiumCapability int capability) {
18289         try {
18290             ITelephony telephony = getITelephony();
18291             if (telephony == null) {
18292                 throw new IllegalStateException("telephony service is null.");
18293             }
18294             return telephony.isPremiumCapabilityAvailableForPurchase(capability, getSubId());
18295         } catch (RemoteException ex) {
18296             ex.rethrowAsRuntimeException();
18297         }
18298         return false;
18299     }
18300 
18301     /**
18302      * Purchase premium capability request was successful.
18303      * Once the purchase result is successful, the network must set up a slicing configuration
18304      * for the purchased premium capability within the timeout specified by
18305      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NETWORK_SETUP_TIME_MILLIS_LONG}.
18306      * During the setup time, subsequent attempts will return
18307      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP}.
18308      * After setup is complete, subsequent attempts will return
18309      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED} until the boost expires.
18310      * The expiry time is determined by the type or duration of boost purchased from the carrier,
18311      * provided at {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_PURCHASE_URL_STRING}.
18312      */
18313     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS = 1;
18314 
18315     /**
18316      * Purchase premium capability failed because the request is throttled.
18317      * If purchasing premium capabilities is throttled, it will be for the amount of time
18318      * specified by {@link CarrierConfigManager
18319      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}.
18320      * If displaying the performance boost notification is throttled, it will be for the amount of
18321      * time specified by {@link CarrierConfigManager
18322      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}.
18323      * We will show the performance boost notification to the user up to the daily and monthly
18324      * maximum number of times specified by
18325      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_MAXIMUM_DAILY_NOTIFICATION_COUNT_INT} and
18326      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_MAXIMUM_MONTHLY_NOTIFICATION_COUNT_INT}.
18327      * Subsequent attempts will return the same error until the request is no longer throttled
18328      * or throttling conditions change.
18329      */
18330     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED = 2;
18331 
18332     /**
18333      * Purchase premium capability failed because it is already purchased and available.
18334      * Subsequent attempts will return the same error until the performance boost expires.
18335      */
18336     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED = 3;
18337 
18338     /**
18339      * Purchase premium capability failed because a request was already made and is in progress.
18340      * This may have been requested by either the same app or another app.
18341      * Subsequent attempts will return the same error until the previous request completes.
18342      */
18343     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS = 4;
18344 
18345     /**
18346      * Purchase premium capability failed because the requesting application is not in the
18347      * foreground. Subsequent attempts will return the same error until the requesting application
18348      * moves to the foreground.
18349      */
18350     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND = 5;
18351 
18352     /**
18353      * Purchase premium capability failed because the user canceled the operation.
18354      * Subsequent attempts will be throttled for the amount of time specified by
18355      * {@link CarrierConfigManager
18356      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18357      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18358      */
18359     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED = 6;
18360 
18361     /**
18362      * Purchase premium capability failed because the carrier disabled or does not support
18363      * the capability, as specified in
18364      * {@link CarrierConfigManager#KEY_SUPPORTED_PREMIUM_CAPABILITIES_INT_ARRAY}.
18365      * Subsequent attempts will return the same error until the carrier enables the feature.
18366      */
18367     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED = 7;
18368 
18369     /**
18370      * Purchase premium capability failed because the carrier app did not indicate success.
18371      * Subsequent attempts will be throttled for the amount of time specified by
18372      * {@link CarrierConfigManager
18373      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18374      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18375      */
18376     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR = 8;
18377 
18378     /**
18379      * Purchase premium capability failed because we did not receive a response from the user
18380      * for the performance boost notification within the time specified by
18381      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NOTIFICATION_DISPLAY_TIMEOUT_MILLIS_LONG}.
18382      * The performance boost notification will be automatically dismissed and subsequent attempts
18383      * will be throttled for the amount of time specified by
18384      * {@link CarrierConfigManager
18385      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18386      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18387      */
18388     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT = 9;
18389 
18390     /**
18391      * Purchase premium capability failed because the device does not support the feature.
18392      * Subsequent attempts will return the same error.
18393      */
18394     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED = 10;
18395 
18396     /**
18397      * Purchase premium capability failed because the telephony service is unavailable
18398      * or there was an error in the phone process.
18399      * Subsequent attempts will return the same error until request conditions are satisfied.
18400      */
18401     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED = 11;
18402 
18403     /**
18404      * Purchase premium capability failed because the network is not available.
18405      * Subsequent attempts will return the same error until network conditions change.
18406      */
18407     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE = 12;
18408 
18409     /**
18410      * Purchase premium capability failed because the entitlement check failed.
18411      * Subsequent attempts will be throttled for the amount of time specified by
18412      * {@link CarrierConfigManager
18413      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18414      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18415      * Throttling will be reevaluated when the network is no longer congested.
18416      */
18417     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED = 13;
18418 
18419     /**
18420      * Purchase premium capability failed because the request was not made on the default data
18421      * subscription, indicated by {@link SubscriptionManager#getDefaultDataSubscriptionId()}.
18422      * Subsequent attempts will return the same error until the request is made on the default
18423      * data subscription.
18424      */
18425     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION = 14;
18426 
18427     /**
18428      * Purchase premium capability was successful and is waiting for the network to setup the
18429      * slicing configuration. If the setup is complete within the time specified by
18430      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NETWORK_SETUP_TIME_MILLIS_LONG},
18431      * subsequent requests will return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED}
18432      * until the purchase expires. If the setup is not complete within the time specified above,
18433      * applications can request the premium capability again.
18434      */
18435     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP = 15;
18436 
18437     /**
18438      * Purchase premium capability failed because the user disabled the feature.
18439      * Subsequent attempts will be throttled for the amount of time specified by
18440      * {@link CarrierConfigManager
18441      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18442      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18443      */
18444     @FlaggedApi(Flags.FLAG_SLICING_ADDITIONAL_ERROR_CODES)
18445     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_DISABLED = 16;
18446 
18447     /**
18448      * Results of the purchase premium capability request.
18449      * @hide
18450      */
18451     @Retention(RetentionPolicy.SOURCE)
18452     @IntDef(prefix = { "PURCHASE_PREMIUM_CAPABILITY_RESULT_" }, value = {
18453             PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS,
18454             PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED,
18455             PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED,
18456             PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS,
18457             PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND,
18458             PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED,
18459             PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED,
18460             PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR,
18461             PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT,
18462             PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED,
18463             PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE,
18464             PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED,
18465             PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION,
18466             PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP,
18467             PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_DISABLED})
18468     public @interface PurchasePremiumCapabilityResult {}
18469 
18470     /**
18471      * Returns the purchase result as a String.
18472      *
18473      * @param result The purchase premium capability result.
18474      * @return The purchase result as a String.
18475      * @hide
18476      */
convertPurchaseResultToString( @urchasePremiumCapabilityResult int result)18477     public static String convertPurchaseResultToString(
18478             @PurchasePremiumCapabilityResult int result) {
18479         switch (result) {
18480             case PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS:
18481                 return "SUCCESS";
18482             case PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED:
18483                 return "THROTTLED";
18484             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED:
18485                 return "ALREADY_PURCHASED";
18486             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS:
18487                 return "ALREADY_IN_PROGRESS";
18488             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND:
18489                 return "NOT_FOREGROUND";
18490             case PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED:
18491                 return "USER_CANCELED";
18492             case PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED:
18493                 return "CARRIER_DISABLED";
18494             case PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR:
18495                 return "CARRIER_ERROR";
18496             case PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT:
18497                 return "TIMEOUT";
18498             case PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED:
18499                 return "FEATURE_NOT_SUPPORTED";
18500             case PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED:
18501                 return "REQUEST_FAILED";
18502             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE:
18503                 return "NETWORK_NOT_AVAILABLE";
18504             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED:
18505                 return "ENTITLEMENT_CHECK_FAILED";
18506             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION:
18507                 return "NOT_DEFAULT_DATA_SUBSCRIPTION";
18508             case PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP:
18509                 return "PENDING_NETWORK_SETUP";
18510             default:
18511                 return "UNKNOWN (" + result + ")";
18512         }
18513     }
18514 
18515     /**
18516      * Purchase the given premium capability from the carrier.
18517      * This requires user action to purchase the boost from the carrier.
18518      * If this returns {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS} or
18519      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED}, applications can request
18520      * the premium capability via {@link ConnectivityManager#requestNetwork}.
18521      *
18522      * @param capability The premium capability to purchase.
18523      * @param executor The callback executor for the response.
18524      * @param callback The result of the purchase request.
18525      * @throws SecurityException if the caller does not hold permissions
18526      *         READ_BASIC_PHONE_STATE or INTERNET.
18527      * @throws UnsupportedOperationException If the device does not have
18528      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
18529      * @see #isPremiumCapabilityAvailableForPurchase(int) to check whether the capability is valid.
18530      */
18531     @RequiresPermission(allOf = {android.Manifest.permission.READ_BASIC_PHONE_STATE,
18532             android.Manifest.permission.INTERNET})
18533     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
purchasePremiumCapability(@remiumCapability int capability, @NonNull @CallbackExecutor Executor executor, @NonNull @PurchasePremiumCapabilityResult Consumer<Integer> callback)18534     public void purchasePremiumCapability(@PremiumCapability int capability,
18535             @NonNull @CallbackExecutor Executor executor,
18536             @NonNull @PurchasePremiumCapabilityResult Consumer<Integer> callback) {
18537         Objects.requireNonNull(executor);
18538         Objects.requireNonNull(callback);
18539 
18540         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
18541             @Override
18542             public void accept(int result) {
18543                 executor.execute(() -> callback.accept(result));
18544             }
18545         };
18546 
18547         try {
18548             ITelephony telephony = getITelephony();
18549             if (telephony == null) {
18550                 callback.accept(PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED);
18551                 return;
18552             }
18553             telephony.purchasePremiumCapability(capability, internalCallback, getSubId());
18554         } catch (RemoteException ex) {
18555             callback.accept(PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED);
18556         }
18557     }
18558 
18559     /**
18560      * Get last known cell identity.
18561      *
18562      * If there is current registered network this value will be same as the registered cell
18563      * identity. If the device goes out of service the previous cell identity is cached and
18564      * will be returned. If the cache age of the Cell identity is more than 24 hours
18565      * it will be cleared and null will be returned.
18566      * @return last known cell identity {@CellIdentity}.
18567      * @hide
18568      */
18569     @SystemApi
18570     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_GET_LAST_KNOWN_CELL_IDENTITY)
18571     @RequiresPermission(allOf = {Manifest.permission.ACCESS_FINE_LOCATION,
18572             Manifest.permission.ACCESS_LAST_KNOWN_CELL_ID})
getLastKnownCellIdentity()18573     public @Nullable CellIdentity getLastKnownCellIdentity() {
18574         try {
18575             ITelephony telephony = getITelephony();
18576             if (telephony == null) {
18577                 throw new IllegalStateException("telephony service is null.");
18578             }
18579             return telephony.getLastKnownCellIdentity(getSubId(), getOpPackageName(),
18580                     getAttributionTag());
18581         } catch (RemoteException ex) {
18582             ex.rethrowAsRuntimeException();
18583         }
18584         return null;
18585     }
18586 
18587     /**
18588      * Callbacks to listen for when the set of packages with carrier privileges for a SIM changes.
18589      *
18590      * <p>Of note, when multiple callbacks are registered, they may be triggered one after another.
18591      * The ordering of them is not guaranteed and thus should not be depend on.
18592      *
18593      * @hide
18594      */
18595     @SystemApi
18596     public interface CarrierPrivilegesCallback {
18597         /**
18598          * Called when the set of packages with carrier privileges has changed.
18599          *
18600          * <p>Of note, this callback will <b>not</b> be fired if a carrier triggers a SIM profile
18601          * switch and the same set of packages remains privileged after the switch.
18602          *
18603          * <p>At registration, the callback will receive the current set of privileged packages.
18604          *
18605          * @param privilegedPackageNames The updated set of package names that have carrier
18606          *                               privileges
18607          * @param privilegedUids         The updated set of UIDs that have carrier privileges
18608          */
onCarrierPrivilegesChanged( @onNull Set<String> privilegedPackageNames, @NonNull Set<Integer> privilegedUids)18609         void onCarrierPrivilegesChanged(
18610                 @NonNull Set<String> privilegedPackageNames, @NonNull Set<Integer> privilegedUids);
18611 
18612         /**
18613          * Called when the {@link CarrierService} for the current user profile has changed.
18614          *
18615          * <p>This method does nothing by default. Clients that are interested in the carrier
18616          * service change should override this method to get package name and UID info.
18617          *
18618          * <p>At registration, the callback will receive the current carrier service info.
18619          *
18620          * <p>Of note, this callback will <b>not</b> be fired if a carrier triggers a SIM profile
18621          * switch and the same carrier service remains after switch.
18622          *
18623          * @param carrierServicePackageName package name of the {@link CarrierService}. May be
18624          *                                  {@code null} when no carrier service is detected.
18625          * @param carrierServiceUid         UID of the {@link CarrierService}. May be
18626          *                                  {@link android.os.Process#INVALID_UID} if no carrier
18627          *                                  service is detected.
18628          */
onCarrierServiceChanged( @ullable String carrierServicePackageName, int carrierServiceUid)18629         default void onCarrierServiceChanged(
18630                 @Nullable String carrierServicePackageName, int carrierServiceUid) {
18631             // do nothing by default
18632         }
18633     }
18634 
18635     /**
18636      * Sets a voice service state override from telecom based on the current {@link PhoneAccount}s
18637      * registered. See {@link PhoneAccount#CAPABILITY_VOICE_CALLING_AVAILABLE}.
18638      *
18639      * <p>Currently, this API is only called to indicate over-the-top voice calling capability of
18640      * the SIM call manager, which will get merged into {@link ServiceState#getState} and propagated
18641      * to interested callers via {@link #getServiceState} and {@link
18642      * TelephonyCallback.ServiceStateListener}.
18643      *
18644      * <p>If callers are truly interested in the actual device <-> tower connection status and not
18645      * an overall "device can make voice calls" boolean, they can use {@link
18646      * ServiceState#getNetworkRegistrationInfo} to check CS registration state.
18647      *
18648      * @hide
18649      */
18650     @TestApi
18651     @SystemApi
18652     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
18653     @RequiresPermission(Manifest.permission.BIND_TELECOM_CONNECTION_SERVICE)
setVoiceServiceStateOverride(boolean hasService)18654     public void setVoiceServiceStateOverride(boolean hasService) {
18655         try {
18656             ITelephony telephony = getITelephony();
18657             if (telephony == null) {
18658                 throw new IllegalStateException("Telephony service is null");
18659             }
18660             telephony.setVoiceServiceStateOverride(getSubId(), hasService, getOpPackageName());
18661         } catch (RemoteException ex) {
18662             ex.rethrowAsRuntimeException();
18663         }
18664     }
18665 
18666     /**
18667      * Registers a {@link CarrierPrivilegesCallback} on the given {@code logicalSlotIndex} to
18668      * receive callbacks when the set of packages with carrier privileges changes. The callback will
18669      * immediately be called with the latest state.
18670      *
18671      * @param logicalSlotIndex The SIM slot to listen on
18672      * @param executor The executor where {@code callback} will be invoked
18673      * @param callback The callback to register
18674      * @hide
18675      */
18676     @SystemApi
18677     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
registerCarrierPrivilegesCallback( int logicalSlotIndex, @NonNull @CallbackExecutor Executor executor, @NonNull CarrierPrivilegesCallback callback)18678     public void registerCarrierPrivilegesCallback(
18679             int logicalSlotIndex,
18680             @NonNull @CallbackExecutor Executor executor,
18681             @NonNull CarrierPrivilegesCallback callback) {
18682         if (mContext == null) {
18683             throw new IllegalStateException("Telephony service is null");
18684         } else if (executor == null || callback == null) {
18685             throw new IllegalArgumentException(
18686                     "CarrierPrivilegesCallback and executor must be non-null");
18687         }
18688         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
18689         if (mTelephonyRegistryMgr == null) {
18690             throw new IllegalStateException("Telephony registry service is null");
18691         }
18692         mTelephonyRegistryMgr.addCarrierPrivilegesCallback(logicalSlotIndex, executor, callback);
18693     }
18694 
18695     /**
18696      * Unregisters an existing {@link CarrierPrivilegesCallback}.
18697      *
18698      * @hide
18699      */
18700     @SystemApi
18701     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
unregisterCarrierPrivilegesCallback(@onNull CarrierPrivilegesCallback callback)18702     public void unregisterCarrierPrivilegesCallback(@NonNull CarrierPrivilegesCallback callback) {
18703         if (mContext == null) {
18704             throw new IllegalStateException("Telephony service is null");
18705         } else if (callback == null) {
18706             throw new IllegalArgumentException("CarrierPrivilegesCallback must be non-null");
18707         }
18708         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
18709         if (mTelephonyRegistryMgr == null) {
18710             throw new IllegalStateException("Telephony registry service is null");
18711         }
18712         mTelephonyRegistryMgr.removeCarrierPrivilegesCallback(callback);
18713     }
18714 
18715     /**
18716      * set removable eSIM as default eUICC.
18717      *
18718      * @hide
18719      */
18720     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
18721     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
setRemovableEsimAsDefaultEuicc(boolean isDefault)18722     public void setRemovableEsimAsDefaultEuicc(boolean isDefault) {
18723         try {
18724             ITelephony telephony = getITelephony();
18725             if (telephony != null) {
18726                 telephony.setRemovableEsimAsDefaultEuicc(isDefault, getOpPackageName());
18727             }
18728         } catch (RemoteException e) {
18729             Log.e(TAG, "Error in setRemovableEsimAsDefault: " + e);
18730         }
18731     }
18732 
18733     /**
18734      * Returns whether the removable eSIM is default eUICC or not.
18735      *
18736      * @hide
18737      */
18738     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
18739     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
isRemovableEsimDefaultEuicc()18740     public boolean isRemovableEsimDefaultEuicc() {
18741         try {
18742             ITelephony telephony = getITelephony();
18743             if (telephony != null) {
18744                 return telephony.isRemovableEsimDefaultEuicc(getOpPackageName());
18745             }
18746         } catch (RemoteException e) {
18747             Log.e(TAG, "Error in isRemovableEsimDefaultEuicc: " + e);
18748         }
18749         return false;
18750     }
18751 
18752     /**
18753      * Returns a constant indicating the state of sim for the slot index.
18754      *
18755      * @param slotIndex Logical SIM slot index.
18756      *
18757      * @see TelephonyManager.SimState
18758      *
18759      * @hide
18760      */
18761     @SimState
getSimStateForSlotIndex(int slotIndex)18762     public static int getSimStateForSlotIndex(int slotIndex) {
18763         try {
18764             ITelephony telephony = getITelephony();
18765             if (telephony != null) {
18766                 return telephony.getSimStateForSlotIndex(slotIndex);
18767             }
18768         } catch (RemoteException e) {
18769             Log.e(TAG, "Error in getSimStateForSlotIndex: " + e);
18770         }
18771         return TelephonyManager.SIM_STATE_UNKNOWN;
18772     }
18773 
18774     /**
18775      * Captures parameters for collection of emergency
18776      * call diagnostic data
18777      * @hide
18778      */
18779     @SystemApi
18780     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
18781     public static final class EmergencyCallDiagnosticData {
18782         public static final class Builder {
18783             private boolean mCollectTelecomDumpsys;
18784             private boolean mCollectTelephonyDumpsys;
18785 
18786             // If this is set to a value other than -1L, then the logcat collection is enabled.
18787             // Logcat lines with this time or greater are collected how much is collected is
18788             // dependent on internal implementation. Time represented as milliseconds since boot.
18789             private long mLogcatStartTimeMillis = sUnsetLogcatStartTime;
18790 
18791             /**
18792              * Allows enabling of telecom dumpsys collection.
18793              * @param collectTelecomDumpsys Determines whether telecom dumpsys should be collected.
18794              * @return Builder instance corresponding to the configured call diagnostic params.
18795              */
setTelecomDumpsysCollectionEnabled( boolean collectTelecomDumpsys)18796             public @NonNull Builder setTelecomDumpsysCollectionEnabled(
18797                     boolean collectTelecomDumpsys) {
18798                 mCollectTelecomDumpsys = collectTelecomDumpsys;
18799                 return this;
18800             }
18801 
18802             /**
18803              * Allows enabling of telephony dumpsys collection.
18804              * @param collectTelephonyDumpsys Determines if telephony dumpsys should be collected.
18805              * @return Builder instance corresponding to the configured call diagnostic params.
18806              */
setTelephonyDumpsysCollectionEnabled( boolean collectTelephonyDumpsys)18807             public @NonNull Builder setTelephonyDumpsysCollectionEnabled(
18808                     boolean collectTelephonyDumpsys) {
18809                 mCollectTelephonyDumpsys = collectTelephonyDumpsys;
18810                 return this;
18811             }
18812 
18813             /**
18814              * Allows enabling of logcat (system,radio) collection.
18815              * @param startTimeMillis Enables logcat collection as of the indicated timestamp.
18816              * @return Builder instance corresponding to the configured call diagnostic params.
18817              */
setLogcatCollectionStartTimeMillis( @urrentTimeMillisLong long startTimeMillis)18818             public @NonNull Builder setLogcatCollectionStartTimeMillis(
18819                     @CurrentTimeMillisLong long startTimeMillis) {
18820                 mLogcatStartTimeMillis = startTimeMillis;
18821                 return this;
18822             }
18823 
18824             /**
18825              * Build the EmergencyCallDiagnosticData from the provided Builder config.
18826              * @return {@link EmergencyCallDiagnosticData} instance from provided builder.
18827              */
build()18828             public @NonNull EmergencyCallDiagnosticData build() {
18829                 return new EmergencyCallDiagnosticData(mCollectTelecomDumpsys,
18830                         mCollectTelephonyDumpsys, mLogcatStartTimeMillis);
18831             }
18832         }
18833 
18834         private boolean mCollectTelecomDumpsys;
18835         private boolean mCollectTelephonyDumpsys;
18836         private boolean mCollectLogcat;
18837         private long mLogcatStartTimeMillis;
18838 
18839         private static long sUnsetLogcatStartTime = -1L;
18840 
EmergencyCallDiagnosticData(boolean collectTelecomDumpsys, boolean collectTelephonyDumpsys, long logcatStartTimeMillis)18841         private EmergencyCallDiagnosticData(boolean collectTelecomDumpsys,
18842                 boolean collectTelephonyDumpsys, long logcatStartTimeMillis) {
18843             mCollectTelecomDumpsys = collectTelecomDumpsys;
18844             mCollectTelephonyDumpsys = collectTelephonyDumpsys;
18845             mLogcatStartTimeMillis = logcatStartTimeMillis;
18846             mCollectLogcat = logcatStartTimeMillis != sUnsetLogcatStartTime;
18847         }
18848 
isTelecomDumpsysCollectionEnabled()18849         public boolean isTelecomDumpsysCollectionEnabled() {
18850             return mCollectTelecomDumpsys;
18851         }
18852 
isTelephonyDumpsysCollectionEnabled()18853         public boolean isTelephonyDumpsysCollectionEnabled() {
18854             return mCollectTelephonyDumpsys;
18855         }
18856 
isLogcatCollectionEnabled()18857         public boolean isLogcatCollectionEnabled() {
18858             return mCollectLogcat;
18859         }
18860 
getLogcatCollectionStartTimeMillis()18861         public long getLogcatCollectionStartTimeMillis()
18862         {
18863             return mLogcatStartTimeMillis;
18864         }
18865 
18866         @Override
toString()18867         public String toString() {
18868             return "EmergencyCallDiagnosticData{"
18869                     + "mCollectTelecomDumpsys=" + mCollectTelecomDumpsys
18870                     + ", mCollectTelephonyDumpsys=" + mCollectTelephonyDumpsys
18871                     + ", mCollectLogcat=" + mCollectLogcat
18872                     + ", mLogcatStartTimeMillis=" + mLogcatStartTimeMillis
18873                     + '}';
18874         }
18875     }
18876 
18877     /**
18878      * Request telephony to persist state for debugging emergency call failures.
18879      *
18880      * @param dropboxTag Tag to use when persisting data to dropbox service.
18881      * @param data Parameters controlling what is collected in the diagnostics.
18882      *
18883      * @hide
18884      */
18885     @SystemApi
18886     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
18887     @RequiresPermission(android.Manifest.permission.READ_DROPBOX_DATA)
persistEmergencyCallDiagnosticData(@onNull String dropboxTag, @NonNull EmergencyCallDiagnosticData data)18888     public void persistEmergencyCallDiagnosticData(@NonNull String dropboxTag,
18889             @NonNull EmergencyCallDiagnosticData data) {
18890         try {
18891             ITelephony telephony = ITelephony.Stub.asInterface(
18892                     TelephonyFrameworkInitializer
18893                             .getTelephonyServiceManager()
18894                             .getTelephonyServiceRegisterer()
18895                             .get());
18896             if (telephony != null) {
18897                 telephony.persistEmergencyCallDiagnosticData(dropboxTag,
18898                         data.isLogcatCollectionEnabled(),
18899                         data.getLogcatCollectionStartTimeMillis(),
18900                         data.isTelecomDumpsysCollectionEnabled(),
18901                         data.isTelephonyDumpsysCollectionEnabled());
18902             }
18903         } catch (RemoteException e) {
18904             Log.e(TAG, "Error while persistEmergencyCallDiagnosticData: " + e);
18905         }
18906     }
18907 
18908     /**
18909      * Set the UE's ability to accept/reject null ciphered and null integrity-protected connections.
18910      *
18911      * The modem is required to ignore this in case of an emergency call.
18912      *
18913      * <p>Requires permission: android.Manifest.MODIFY_PHONE_STATE</p>
18914      *
18915      * @param enabled if null ciphered and null integrity protected connections are permitted
18916      * @throws IllegalStateException if the Telephony process is not currently available
18917      * @throws SecurityException if the caller does not have the required privileges
18918      * @throws UnsupportedOperationException if the modem does not support disabling null ciphers.
18919      * @hide
18920      */
18921     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNullCipherAndIntegrityEnabled(boolean enabled)18922     public void setNullCipherAndIntegrityEnabled(boolean enabled) {
18923         try {
18924             ITelephony telephony = getITelephony();
18925             if (telephony != null) {
18926                 telephony.setNullCipherAndIntegrityEnabled(enabled);
18927             } else {
18928                 throw new IllegalStateException("telephony service is null.");
18929             }
18930         } catch (RemoteException ex) {
18931             Rlog.e(TAG, "setNullCipherAndIntegrityEnabled RemoteException", ex);
18932             ex.rethrowFromSystemServer();
18933         }
18934     }
18935 
18936     /**
18937      * Get the value of the global preference for null cipher and integriy enablement.
18938      * Note: This does not return the state of the modem, only the persisted global preference.
18939      *
18940      * <p>Requires permission: android.Manifest.READ_PHONE_STATE</p>
18941      *
18942      * @throws IllegalStateException if the Telephony process is not currently available
18943      * @throws SecurityException if the caller does not have the required privileges
18944      * @throws UnsupportedOperationException if the modem does not support disabling null ciphers.
18945      * @hide
18946      */
18947     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
isNullCipherAndIntegrityPreferenceEnabled()18948     public boolean isNullCipherAndIntegrityPreferenceEnabled() {
18949         try {
18950             ITelephony telephony = getITelephony();
18951             if (telephony != null) {
18952                 return telephony.isNullCipherAndIntegrityPreferenceEnabled();
18953             } else {
18954                 throw new IllegalStateException("telephony service is null.");
18955             }
18956         } catch (RemoteException ex) {
18957             Rlog.e(TAG, "isNullCipherAndIntegrityPreferenceEnabled RemoteException", ex);
18958             ex.rethrowFromSystemServer();
18959         }
18960         return true;
18961     }
18962 
18963     /**
18964      * Enable or disable notifications sent for cellular identifier disclosure events.
18965      *
18966      * Disclosure events are defined as instances where a device has sent a cellular identifier
18967      * on the Non-access stratum (NAS) before a security context is established. As a result the
18968      * identifier is sent in the clear, which has privacy implications for the user.
18969      *
18970      * @param enable if notifications about disclosure events should be enabled
18971      * @throws IllegalStateException if the Telephony process is not currently available
18972      * @throws SecurityException if the caller does not have the required privileges
18973      * @throws UnsupportedOperationException if the modem does not support this feature.
18974      *
18975      * @hide
18976      */
18977     @FlaggedApi(Flags.FLAG_ENABLE_IDENTIFIER_DISCLOSURE_TRANSPARENCY)
18978     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
18979     @SystemApi
setEnableCellularIdentifierDisclosureNotifications(boolean enable)18980     public void setEnableCellularIdentifierDisclosureNotifications(boolean enable) {
18981         try {
18982             ITelephony telephony = getITelephony();
18983             if (telephony != null) {
18984                 telephony.setEnableCellularIdentifierDisclosureNotifications(enable);
18985             } else {
18986                 throw new IllegalStateException("telephony service is null.");
18987             }
18988         } catch (RemoteException ex) {
18989             Rlog.e(TAG, "setEnableCellularIdentifierDisclosureNotifications RemoteException", ex);
18990             ex.rethrowFromSystemServer();
18991         }
18992     }
18993 
18994     /**
18995      * Get whether or not cellular identifier disclosure notifications are enabled.
18996      *
18997      * @throws IllegalStateException if the Telephony process is not currently available
18998      * @throws SecurityException if the caller does not have the required privileges
18999      * @throws UnsupportedOperationException if the modem does not support this feature.
19000      *
19001      * @hide
19002      */
19003     @FlaggedApi(Flags.FLAG_ENABLE_IDENTIFIER_DISCLOSURE_TRANSPARENCY)
19004     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19005     @SystemApi
isCellularIdentifierDisclosureNotificationsEnabled()19006     public boolean isCellularIdentifierDisclosureNotificationsEnabled() {
19007         try {
19008             ITelephony telephony = getITelephony();
19009             if (telephony != null) {
19010                 return telephony.isCellularIdentifierDisclosureNotificationsEnabled();
19011             } else {
19012                 throw new IllegalStateException("telephony service is null.");
19013             }
19014         } catch (RemoteException ex) {
19015             Rlog.e(TAG, "isCellularIdentifierDisclosureNotificationsEnabled RemoteException", ex);
19016             ex.rethrowFromSystemServer();
19017         }
19018         return false;
19019     }
19020 
19021     /**
19022      * Enables or disables notifications sent when cellular null cipher or integrity algorithms
19023      * are in use by the cellular modem.
19024      *
19025      * @throws IllegalStateException if the Telephony process is not currently available
19026      * @throws SecurityException if the caller does not have the required privileges
19027      * @throws UnsupportedOperationException if the modem does not support reporting on ciphering
19028      * and integrity algorithms in use
19029      * @hide
19030      */
19031     @FlaggedApi(Flags.FLAG_ENABLE_MODEM_CIPHER_TRANSPARENCY)
19032     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
19033     @SystemApi
setNullCipherNotificationsEnabled(boolean enable)19034     public void setNullCipherNotificationsEnabled(boolean enable) {
19035         try {
19036             ITelephony telephony = getITelephony();
19037             if (telephony != null) {
19038                 telephony.setNullCipherNotificationsEnabled(enable);
19039             } else {
19040                 throw new IllegalStateException("telephony service is null.");
19041             }
19042         } catch (RemoteException ex) {
19043             Rlog.e(TAG, "setEnableNullCipherNotifications RemoteException", ex);
19044             ex.rethrowFromSystemServer();
19045         }
19046     }
19047 
19048     /**
19049      * Get whether notifications are enabled for null cipher or integrity algorithms in use by the
19050      * cellular modem.
19051      *
19052      * @throws IllegalStateException if the Telephony process is not currently available
19053      * @throws SecurityException if the caller does not have the required privileges
19054      * @throws UnsupportedOperationException if the modem does not support reporting on ciphering
19055      * and integrity algorithms in use
19056      * @hide
19057      */
19058     @FlaggedApi(Flags.FLAG_ENABLE_MODEM_CIPHER_TRANSPARENCY)
19059     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19060     @SystemApi
isNullCipherNotificationsEnabled()19061     public boolean isNullCipherNotificationsEnabled() {
19062         try {
19063             ITelephony telephony = getITelephony();
19064             if (telephony != null) {
19065                 return telephony.isNullCipherNotificationsEnabled();
19066             } else {
19067                 throw new IllegalStateException("telephony service is null.");
19068             }
19069         } catch (RemoteException ex) {
19070             Rlog.e(TAG, "isNullCipherNotificationsEnabled RemoteException", ex);
19071             ex.rethrowFromSystemServer();
19072         }
19073         return false;
19074     }
19075 
19076 
19077     /**
19078      * Get current cell broadcast message identifier ranges.
19079      *
19080      * @throws SecurityException if the caller does not have the required permission
19081      * @throws UnsupportedOperationException If the device does not have
19082      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
19083      *
19084      * @hide
19085      */
19086     @SystemApi
19087     @RequiresPermission(android.Manifest.permission.MODIFY_CELL_BROADCASTS)
19088     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
19089     @NonNull
getCellBroadcastIdRanges()19090     public List<CellBroadcastIdRange> getCellBroadcastIdRanges() {
19091         try {
19092             ITelephony telephony = getITelephony();
19093             if (telephony != null) {
19094                 return telephony.getCellBroadcastIdRanges(getSubId());
19095             } else {
19096                 throw new IllegalStateException("telephony service is null.");
19097             }
19098         } catch (RemoteException ex) {
19099             ex.rethrowFromSystemServer();
19100         }
19101         return new ArrayList<>();
19102     }
19103 
19104     /** @hide */
19105     @Retention(RetentionPolicy.SOURCE)
19106     @IntDef(prefix = {"CELL_BROADCAST_RESULT_"}, value = {
19107             CELL_BROADCAST_RESULT_UNKNOWN,
19108             CELL_BROADCAST_RESULT_SUCCESS,
19109             CELL_BROADCAST_RESULT_UNSUPPORTED,
19110             CELL_BROADCAST_RESULT_FAIL_CONFIG,
19111             CELL_BROADCAST_RESULT_FAIL_ACTIVATION})
19112     public @interface CellBroadcastResult {}
19113 
19114     /**
19115      * The result of the cell broadcast request is unknown
19116      * @hide
19117      */
19118     @SystemApi
19119     public static final int CELL_BROADCAST_RESULT_UNKNOWN = -1;
19120 
19121     /**
19122      * The cell broadcast request is successful.
19123      * @hide
19124      */
19125     @SystemApi
19126     public static final int CELL_BROADCAST_RESULT_SUCCESS = 0;
19127 
19128     /**
19129      * The cell broadcast request is not supported.
19130      * @hide
19131      */
19132     @SystemApi
19133     public static final int CELL_BROADCAST_RESULT_UNSUPPORTED = 1;
19134 
19135     /**
19136      * The cell broadcast request is failed due to the error to set config
19137      * @hide
19138      */
19139     @SystemApi
19140     public static final int CELL_BROADCAST_RESULT_FAIL_CONFIG = 2;
19141 
19142     /**
19143      * The cell broadcast request is failed due to the error to set activation
19144      * @hide
19145      */
19146     @SystemApi
19147     public static final int CELL_BROADCAST_RESULT_FAIL_ACTIVATION = 3;
19148 
19149     /**
19150      * Callback mode type
19151      * @hide
19152      */
19153     @Retention(RetentionPolicy.SOURCE)
19154     @IntDef(prefix = {"EMERGENCY_CALLBACK_MODE_"}, value = {
19155             EMERGENCY_CALLBACK_MODE_CALL,
19156             EMERGENCY_CALLBACK_MODE_SMS})
19157     public @interface EmergencyCallbackModeType {}
19158 
19159     /**
19160      * The callback mode is due to emergency call.
19161      * @hide
19162      */
19163     public static final int EMERGENCY_CALLBACK_MODE_CALL = 1;
19164 
19165     /**
19166      * The callback mode is due to emergency SMS.
19167      * @hide
19168      */
19169     public static final int EMERGENCY_CALLBACK_MODE_SMS = 2;
19170 
19171     /**
19172      * The reason for changing callback mode.
19173      * @hide
19174      */
19175     @Retention(RetentionPolicy.SOURCE)
19176     @IntDef(prefix = {"STOP_REASON_"},
19177             value = {
19178                     STOP_REASON_UNKNOWN,
19179                     STOP_REASON_OUTGOING_NORMAL_CALL_INITIATED,
19180                     STOP_REASON_NORMAL_SMS_SENT,
19181                     STOP_REASON_OUTGOING_EMERGENCY_CALL_INITIATED,
19182                     STOP_REASON_EMERGENCY_SMS_SENT,
19183                     STOP_REASON_TIMER_EXPIRED,
19184                     STOP_REASON_USER_ACTION,
19185             })
19186     public @interface EmergencyCallbackModeStopReason {}
19187 
19188     /**
19189      * unknown reason.
19190      * @hide
19191      */
19192     public static final int STOP_REASON_UNKNOWN = 0;
19193 
19194     /**
19195      * The call back mode is exited due to a new normal call is originated.
19196      * @hide
19197      */
19198     public static final int STOP_REASON_OUTGOING_NORMAL_CALL_INITIATED = 1;
19199 
19200     /**
19201      * The call back mode is exited due to a new normal SMS is originated.
19202      * @hide
19203      */
19204     public static final int STOP_REASON_NORMAL_SMS_SENT = 2;
19205 
19206     /**
19207      * The call back mode is exited due to a new emergency call is originated.
19208      * @hide
19209      */
19210     public static final int STOP_REASON_OUTGOING_EMERGENCY_CALL_INITIATED = 3;
19211 
19212     /**
19213      * The call back mode is exited due to a new emergency SMS is originated.
19214      * @hide
19215      */
19216     public static final int STOP_REASON_EMERGENCY_SMS_SENT = 4;
19217 
19218     /**
19219      * The call back mode is exited due to timer expiry.
19220      * @hide
19221      */
19222     public static final int STOP_REASON_TIMER_EXPIRED = 5;
19223 
19224     /**
19225      * The call back mode is exited due to user action.
19226      * @hide
19227      */
19228     public static final int STOP_REASON_USER_ACTION = 6;
19229 
19230     /**
19231      * Set reception of cell broadcast messages with the list of the given ranges
19232      *
19233      * <p>The ranges set previously will be overridden by the new one. Empty list
19234      * can be used to clear the ranges.
19235      *
19236      * @param ranges the list of {@link CellBroadcastIdRange} to be set.
19237      * @param executor The {@link Executor} that will be used to call the callback.
19238      * @param callback A callback called on the supplied {@link Executor} to notify
19239      * the result when the operation completes.
19240      * @throws SecurityException if the caller does not have the required permission
19241      * @throws IllegalArgumentException when the ranges are invalid.
19242      * @throws UnsupportedOperationException If the device does not have
19243      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
19244      * @hide
19245      */
19246     @SystemApi
19247     @RequiresPermission(android.Manifest.permission.MODIFY_CELL_BROADCASTS)
19248     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
setCellBroadcastIdRanges(@onNull List<CellBroadcastIdRange> ranges, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Integer> callback)19249     public void setCellBroadcastIdRanges(@NonNull List<CellBroadcastIdRange> ranges,
19250             @NonNull @CallbackExecutor Executor executor,
19251             @NonNull Consumer<Integer> callback) {
19252         IIntegerConsumer consumer = callback == null ? null : new IIntegerConsumer.Stub() {
19253             @Override
19254             public void accept(int result) {
19255                 final long identity = Binder.clearCallingIdentity();
19256                 try {
19257                     executor.execute(() -> callback.accept(result));
19258                 } finally {
19259                     Binder.restoreCallingIdentity(identity);
19260                 }
19261             }
19262         };
19263 
19264         try {
19265             ITelephony telephony = getITelephony();
19266             if (telephony != null) {
19267                 telephony.setCellBroadcastIdRanges(getSubId(), ranges, consumer);
19268             } else {
19269                 throw new IllegalStateException("telephony service is null.");
19270             }
19271         } catch (RemoteException ex) {
19272             ex.rethrowFromSystemServer();
19273         }
19274     }
19275 
19276     /**
19277      * Returns whether the domain selection service is supported.
19278      *
19279      * @return {@code true} if the domain selection service is supported.
19280      * @hide
19281      */
19282     @SystemApi
19283     @FlaggedApi(Flags.FLAG_USE_OEM_DOMAIN_SELECTION_SERVICE)
19284     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19285     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isDomainSelectionSupported()19286     public boolean isDomainSelectionSupported() {
19287         try {
19288             ITelephony telephony = getITelephony();
19289             if (telephony != null) {
19290                 return telephony.isDomainSelectionSupported();
19291             }
19292         } catch (RemoteException ex) {
19293             Rlog.w(TAG, "RemoteException", ex);
19294         }
19295         return false;
19296     }
19297 
19298     /**
19299      * Returns whether the AOSP domain selection service is supported.
19300      *
19301      * @return {@code true} if the AOSP domain selection service is supported.
19302      * @hide
19303      */
19304     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19305     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isAospDomainSelectionService()19306     public boolean isAospDomainSelectionService() {
19307         try {
19308             ITelephony telephony = getITelephony();
19309             if (telephony != null) {
19310                 return telephony.isAospDomainSelectionService();
19311             }
19312         } catch (RemoteException ex) {
19313             Rlog.w(TAG, "RemoteException", ex);
19314         }
19315         return false;
19316     }
19317 
19318     /**
19319      * Returns the primary IMEI (International Mobile Equipment Identity) of the device as
19320      * mentioned in GSMA TS.37. {@link #getImei(int)} returns the IMEI that belongs to the selected
19321      * slotID whereas this API {@link #getPrimaryImei()} returns primary IMEI of the device.
19322      * A single SIM device with only one IMEI will be set by default as primary IMEI.
19323      * A multi-SIM device with multiple IMEIs will have one of the IMEIs set as primary as
19324      * mentioned in GSMA TS37_2.2_REQ_8.
19325      *
19326      * <p>Requires one of the following permissions
19327      * <ul>
19328      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
19329      *     is a privileged permission that can only be granted to apps preloaded on the device.
19330      *     <li>If the calling app is the device owner of a fully-managed device, a profile
19331      *     owner of an organization-owned device, or their delegates (see {@link
19332      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
19333      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
19334      *     active subscription.
19335      *     <li>If the calling app is the default SMS role holder (see {@link
19336      *     RoleManager#isRoleHeld(String)}).
19337      *     <li>If the calling app has been granted the
19338      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
19339      * </ul>
19340      *
19341      * @return Primary IMEI of type string
19342      * @throws UnsupportedOperationException If the device does not have
19343      *          {@link PackageManager#FEATURE_TELEPHONY_GSM}.
19344      * @throws SecurityException if the caller does not have the required permission/privileges
19345      */
19346     @NonNull
19347     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_GSM)
getPrimaryImei()19348     public String getPrimaryImei() {
19349         try {
19350             ITelephony telephony = getITelephony();
19351             if (telephony == null) {
19352                 Rlog.e(TAG, "getPrimaryImei(): IPhoneSubInfo instance is NULL");
19353                 throw new IllegalStateException("Telephony service not available.");
19354             }
19355             return telephony.getPrimaryImei(getOpPackageName(), getAttributionTag());
19356         } catch (RemoteException ex) {
19357             Rlog.e(TAG, "getPrimaryImei() RemoteException : " + ex);
19358             throw ex.rethrowAsRuntimeException();
19359         }
19360     }
19361 
19362     /**
19363      * Convert SIM state into string.
19364      *
19365      * @param state SIM state.
19366      * @return SIM state in string format.
19367      *
19368      * @hide
19369      */
19370     @NonNull
simStateToString(@imState int state)19371     public static String simStateToString(@SimState int state) {
19372         switch (state) {
19373             case TelephonyManager.SIM_STATE_UNKNOWN:
19374                 return "UNKNOWN";
19375             case TelephonyManager.SIM_STATE_ABSENT:
19376                 return "ABSENT";
19377             case TelephonyManager.SIM_STATE_PIN_REQUIRED:
19378                 return "PIN_REQUIRED";
19379             case TelephonyManager.SIM_STATE_PUK_REQUIRED:
19380                 return "PUK_REQUIRED";
19381             case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
19382                 return "NETWORK_LOCKED";
19383             case TelephonyManager.SIM_STATE_READY:
19384                 return "READY";
19385             case TelephonyManager.SIM_STATE_NOT_READY:
19386                 return "NOT_READY";
19387             case TelephonyManager.SIM_STATE_PERM_DISABLED:
19388                 return "PERM_DISABLED";
19389             case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
19390                 return "CARD_IO_ERROR";
19391             case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
19392                 return "CARD_RESTRICTED";
19393             case TelephonyManager.SIM_STATE_LOADED:
19394                 return "LOADED";
19395             case TelephonyManager.SIM_STATE_PRESENT:
19396                 return "PRESENT";
19397             default:
19398                 return "UNKNOWN(" + state + ")";
19399         }
19400     }
19401 }
19402