• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.BoolRes;
27 import android.annotation.BytesLong;
28 import android.annotation.CallbackExecutor;
29 import android.annotation.CurrentTimeMillisLong;
30 import android.annotation.FlaggedApi;
31 import android.annotation.IntDef;
32 import android.annotation.LongDef;
33 import android.annotation.NonNull;
34 import android.annotation.Nullable;
35 import android.annotation.RequiresFeature;
36 import android.annotation.RequiresPermission;
37 import android.annotation.SdkConstant;
38 import android.annotation.SdkConstant.SdkConstantType;
39 import android.annotation.StringDef;
40 import android.annotation.SuppressAutoDoc;
41 import android.annotation.SuppressLint;
42 import android.annotation.SystemApi;
43 import android.annotation.SystemService;
44 import android.annotation.TestApi;
45 import android.annotation.WorkerThread;
46 import android.app.PendingIntent;
47 import android.app.PropertyInvalidatedCache;
48 import android.app.role.RoleManager;
49 import android.compat.Compatibility;
50 import android.compat.annotation.ChangeId;
51 import android.compat.annotation.EnabledAfter;
52 import android.compat.annotation.EnabledSince;
53 import android.compat.annotation.UnsupportedAppUsage;
54 import android.content.ComponentName;
55 import android.content.Context;
56 import android.content.ContextParams;
57 import android.content.Intent;
58 import android.content.pm.PackageManager;
59 import android.database.Cursor;
60 import android.net.ConnectivityManager;
61 import android.net.NetworkCapabilities;
62 import android.net.Uri;
63 import android.os.AsyncTask;
64 import android.os.Binder;
65 import android.os.Build;
66 import android.os.Bundle;
67 import android.os.Handler;
68 import android.os.IBinder;
69 import android.os.Looper;
70 import android.os.OutcomeReceiver;
71 import android.os.ParcelFileDescriptor;
72 import android.os.ParcelUuid;
73 import android.os.Parcelable;
74 import android.os.PersistableBundle;
75 import android.os.RemoteException;
76 import android.os.ResultReceiver;
77 import android.os.SystemProperties;
78 import android.os.WorkSource;
79 import android.provider.Settings.SettingNotFoundException;
80 import android.service.carrier.CarrierIdentifier;
81 import android.service.carrier.CarrierService;
82 import android.sysprop.TelephonyProperties;
83 import android.telecom.Call;
84 import android.telecom.CallScreeningService;
85 import android.telecom.Connection;
86 import android.telecom.InCallService;
87 import android.telecom.PhoneAccount;
88 import android.telecom.PhoneAccountHandle;
89 import android.telecom.TelecomManager;
90 import android.telephony.Annotation.ApnType;
91 import android.telephony.Annotation.CallState;
92 import android.telephony.Annotation.CarrierPrivilegeStatus;
93 import android.telephony.Annotation.NetworkType;
94 import android.telephony.Annotation.RadioPowerState;
95 import android.telephony.Annotation.SimActivationState;
96 import android.telephony.Annotation.ThermalMitigationResult;
97 import android.telephony.Annotation.UiccAppType;
98 import android.telephony.Annotation.UiccAppTypeExt;
99 import android.telephony.CallForwardingInfo.CallForwardingReason;
100 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
101 import android.telephony.data.ApnSetting;
102 import android.telephony.data.ApnSetting.MvnoType;
103 import android.telephony.data.NetworkSlicingConfig;
104 import android.telephony.emergency.EmergencyNumber;
105 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
106 import android.telephony.gba.UaSecurityProtocolIdentifier;
107 import android.telephony.ims.ImsMmTelManager;
108 import android.telephony.ims.aidl.IImsConfig;
109 import android.telephony.ims.aidl.IImsRegistration;
110 import android.telephony.ims.feature.MmTelFeature;
111 import android.telephony.ims.stub.ImsRegistrationImplBase;
112 import android.text.TextUtils;
113 import android.util.Log;
114 import android.util.Pair;
115 
116 import com.android.internal.annotations.GuardedBy;
117 import com.android.internal.annotations.VisibleForTesting;
118 import com.android.internal.os.BackgroundThread;
119 import com.android.internal.telephony.CellNetworkScanResult;
120 import com.android.internal.telephony.IBooleanConsumer;
121 import com.android.internal.telephony.ICallForwardingInfoCallback;
122 import com.android.internal.telephony.IIntegerConsumer;
123 import com.android.internal.telephony.INumberVerificationCallback;
124 import com.android.internal.telephony.IOns;
125 import com.android.internal.telephony.IPhoneSubInfo;
126 import com.android.internal.telephony.ISetOpportunisticDataCallback;
127 import com.android.internal.telephony.ISms;
128 import com.android.internal.telephony.ISub;
129 import com.android.internal.telephony.ITelephony;
130 import com.android.internal.telephony.IUpdateAvailableNetworksCallback;
131 import com.android.internal.telephony.IccLogicalChannelRequest;
132 import com.android.internal.telephony.OperatorInfo;
133 import com.android.internal.telephony.PhoneConstants;
134 import com.android.internal.telephony.RILConstants;
135 import com.android.internal.telephony.flags.Flags;
136 import com.android.internal.telephony.uicc.IccUtils;
137 import com.android.internal.telephony.util.TelephonyUtils;
138 import com.android.telephony.Rlog;
139 
140 import java.io.IOException;
141 import java.io.InputStream;
142 import java.io.OutputStream;
143 import java.lang.annotation.Retention;
144 import java.lang.annotation.RetentionPolicy;
145 import java.nio.file.Files;
146 import java.nio.file.Path;
147 import java.util.ArrayList;
148 import java.util.Arrays;
149 import java.util.Collection;
150 import java.util.Collections;
151 import java.util.HashMap;
152 import java.util.HashSet;
153 import java.util.List;
154 import java.util.Locale;
155 import java.util.Map;
156 import java.util.Objects;
157 import java.util.Optional;
158 import java.util.Set;
159 import java.util.UUID;
160 import java.util.concurrent.Executor;
161 import java.util.concurrent.RejectedExecutionException;
162 import java.util.function.Consumer;
163 import java.util.stream.Collectors;
164 import java.util.stream.IntStream;
165 
166 /**
167  * Provides access to information about the telephony services on
168  * the device. Applications can use the methods in this class to
169  * determine telephony services and states, as well as to access some
170  * types of subscriber information. Applications can also register
171  * a listener to receive notification of telephony state changes.
172  * <p>
173  * The returned TelephonyManager will use the default subscription for all calls.
174  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
175  * <code>
176  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
177  * </code>
178  * <p>
179  * Note that access to some telephony information is
180  * permission-protected. Your application cannot access the protected
181  * information unless it has the appropriate permissions declared in
182  * its manifest file. Where permissions apply, they are noted in the
183  * methods through which you access the protected information.
184  *
185  * <p>TelephonyManager is intended for use on devices that implement
186  * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
187  * that do not implement this feature, the behavior is not reliable.
188  */
189 @SystemService(Context.TELEPHONY_SERVICE)
190 @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
191 public class TelephonyManager {
192     private static final String TAG = "TelephonyManager";
193 
194     private TelephonyRegistryManager mTelephonyRegistryMgr;
195     /**
196      * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
197      * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
198      */
199     @ChangeId
200     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
201     private static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
202 
203     /**
204      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
205      * into the ResultReceiver Bundle.
206      * @hide
207      */
208     public static final String MODEM_ACTIVITY_RESULT_KEY = "controller_activity";
209 
210     /** @hide */
211     public static final String EXCEPTION_RESULT_KEY = "exception";
212 
213     /**
214      * The process name of the Phone app as well as many other apps that use this process name, such
215      * as settings and vendor components.
216      * @hide
217      */
218     public static final String PHONE_PROCESS_NAME = "com.android.phone";
219 
220     /**
221      * The allowed states of Wi-Fi calling.
222      *
223      * @hide
224      */
225     public interface WifiCallingChoices {
226         /** Always use Wi-Fi calling */
227         static final int ALWAYS_USE = 0;
228         /** Ask the user whether to use Wi-Fi on every call */
229         static final int ASK_EVERY_TIME = 1;
230         /** Never use Wi-Fi calling */
231         static final int NEVER_USE = 2;
232     }
233 
234     /** @hide */
235     @Retention(RetentionPolicy.SOURCE)
236     @IntDef(prefix = {"NETWORK_SELECTION_MODE_"},
237             value = {
238                     NETWORK_SELECTION_MODE_UNKNOWN,
239                     NETWORK_SELECTION_MODE_AUTO,
240                     NETWORK_SELECTION_MODE_MANUAL})
241     public @interface NetworkSelectionMode {}
242 
243     public static final int NETWORK_SELECTION_MODE_UNKNOWN = 0;
244     public static final int NETWORK_SELECTION_MODE_AUTO = 1;
245     public static final int NETWORK_SELECTION_MODE_MANUAL = 2;
246 
247     /**
248      * Reasons for Radio being powered off.
249      *
250      * @hide
251      */
252     @Retention(RetentionPolicy.SOURCE)
253     @IntDef(prefix = {"RADIO_POWER_REASON_"},
254             value = {
255                     RADIO_POWER_REASON_USER,
256                     RADIO_POWER_REASON_THERMAL,
257                     RADIO_POWER_REASON_CARRIER,
258                     RADIO_POWER_REASON_NEARBY_DEVICE})
259     public @interface RadioPowerReason {}
260 
261     /**
262      * This reason is used when users want to turn off radio, e.g., users turn on airplane mode.
263      *
264      * @hide
265      */
266     @SystemApi
267     public static final int RADIO_POWER_REASON_USER = 0;
268     /**
269      * This reason is used when radio needs to be turned off due to thermal.
270      *
271      * @hide
272      */
273     @SystemApi
274     public static final int RADIO_POWER_REASON_THERMAL = 1;
275     /**
276      * This reason is used when carriers want to turn off radio. A privileged app can request to
277      * turn off radio via the system service
278      * {@link com.android.carrierdefaultapp.CaptivePortalLoginActivity}, which subsequently calls
279      * the system APIs {@link requestRadioPowerOffForReason} and
280      * {@link clearRadioPowerOffForReason}.
281      *
282      * @hide
283      */
284     @SystemApi
285     public static final int RADIO_POWER_REASON_CARRIER = 2;
286     /**
287      * Used to reduce power on a battery-constrained device when Telephony services are available
288      * via a paired device which is nearby.
289      *
290      * @hide
291      */
292     @SystemApi
293     public static final int RADIO_POWER_REASON_NEARBY_DEVICE = 3;
294 
295     /** The otaspMode passed to SercvieState changes */
296     /** @hide */
297     static public final int OTASP_UNINITIALIZED = 0;
298     /** @hide */
299     static public final int OTASP_UNKNOWN = 1;
300     /** @hide */
301     static public final int OTASP_NEEDED = 2;
302     /** @hide */
303     static public final int OTASP_NOT_NEEDED = 3;
304     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
305     /** @hide */
306     static public final int OTASP_SIM_UNPROVISIONED = 5;
307 
308     /**
309      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
310      * available for use in ePDG links.
311      *
312      * @hide
313      */
314     @SystemApi
315     static public final int KEY_TYPE_EPDG = 1;
316 
317     /**
318      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
319      * available for use in WLAN links.
320      *
321      * @hide
322      */
323     @SystemApi
324     static public final int KEY_TYPE_WLAN = 2;
325 
326     /** @hide */
327     @Retention(RetentionPolicy.SOURCE)
328     @IntDef(prefix = {"KEY_TYPE_"}, value = {KEY_TYPE_EPDG, KEY_TYPE_WLAN})
329     public @interface KeyType {}
330 
331     /**
332      * No Single Radio Voice Call Continuity (SRVCC) handover is active.
333      * See TS 23.216 for more information.
334      * @hide
335      */
336     @SystemApi
337     public static final int SRVCC_STATE_HANDOVER_NONE  = -1;
338 
339     /**
340      * Single Radio Voice Call Continuity (SRVCC) handover has been started on the network.
341      * See TS 23.216 for more information.
342      * @hide
343      */
344     @SystemApi
345     public static final int SRVCC_STATE_HANDOVER_STARTED  = 0;
346 
347     /**
348      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has successfully completed.
349      * See TS 23.216 for more information.
350      * @hide
351      */
352     @SystemApi
353     public static final int SRVCC_STATE_HANDOVER_COMPLETED = 1;
354 
355     /**
356      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has failed.
357      * See TS 23.216 for more information.
358      * @hide
359      */
360     @SystemApi
361     public static final int SRVCC_STATE_HANDOVER_FAILED   = 2;
362 
363     /**
364      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has been canceled.
365      * See TS 23.216 for more information.
366      * @hide
367      */
368     @SystemApi
369     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
370 
371     /**
372      * Convert srvcc handover state to string.
373      *
374      * @param state The srvcc handover state.
375      * @return The srvcc handover state in string format.
376      *
377      * @hide
378      */
srvccStateToString(int state)379     public static @NonNull String srvccStateToString(int state) {
380         switch (state) {
381             case TelephonyManager.SRVCC_STATE_HANDOVER_NONE:
382                 return "NONE";
383             case TelephonyManager.SRVCC_STATE_HANDOVER_STARTED:
384                 return "STARTED";
385             case TelephonyManager.SRVCC_STATE_HANDOVER_COMPLETED:
386                 return "COMPLETED";
387             case TelephonyManager.SRVCC_STATE_HANDOVER_FAILED:
388                 return "FAILED";
389             case TelephonyManager.SRVCC_STATE_HANDOVER_CANCELED:
390                 return "CANCELED";
391             default:
392                 return "UNKNOWN(" + state + ")";
393         }
394     }
395 
396     /**
397      * A UICC card identifier used if the device does not support the operation.
398      * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
399      * eUICC, or the eUICC cannot be read.
400      */
401     public static final int UNSUPPORTED_CARD_ID = -1;
402 
403     /**
404      * A UICC card identifier used before the UICC card is loaded. See
405      * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
406      * <p>
407      * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
408      */
409     public static final int UNINITIALIZED_CARD_ID = -2;
410 
411     /**
412      * Default port index for a UICC.
413      *
414      * On physical SIM cards the only available port is 0.
415      * See {@link android.telephony.UiccPortInfo} for more information on ports.
416      *
417      * See {@link android.telephony.euicc.EuiccManager#isSimPortAvailable(int)} for information on
418      * how portIndex is used on eUICCs.
419      */
420     public static final int DEFAULT_PORT_INDEX = 0;
421 
422     /** @hide */
423     public static final int INVALID_PORT_INDEX = -1;
424 
425     /** @hide */
426     public static final String PROPERTY_ENABLE_NULL_CIPHER_TOGGLE = "enable_null_cipher_toggle";
427 
428     /**
429      * To apply the enforcement telephony feature and API
430      * @hide
431      */
432     @ChangeId
433     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM)
434     public static final long ENABLE_FEATURE_MAPPING = 297989574L;
435 
436     private final Context mContext;
437     private final int mSubId;
438     @UnsupportedAppUsage
439     private SubscriptionManager mSubscriptionManager;
440     private TelephonyScanManager mTelephonyScanManager;
441 
442     /** Cached service handles, cleared by resetServiceHandles() at death */
443     private static final Object sCacheLock = new Object();
444 
445     /** @hide */
446     private static boolean sServiceHandleCacheEnabled = true;
447 
448     @GuardedBy("sCacheLock")
449     private static ITelephony sITelephony;
450     @GuardedBy("sCacheLock")
451     private static IPhoneSubInfo sIPhoneSubInfo;
452     @GuardedBy("sCacheLock")
453     private static ISub sISub;
454     @GuardedBy("sCacheLock")
455     private static ISms sISms;
456     @GuardedBy("sCacheLock")
457     private static final DeathRecipient sServiceDeath = new DeathRecipient();
458 
459     /**
460      * Cache key for a {@link PropertyInvalidatedCache} which maps from {@link PhoneAccountHandle}
461      * to subscription Id.  The cache is initialized in {@code PhoneInterfaceManager}'s constructor
462      * when {@link PropertyInvalidatedCache#invalidateCache(String)} is called.
463      * The cache is cleared from {@code TelecomAccountRegistry#tearDown} when all phone accounts are
464      * removed from Telecom.
465      * @hide
466      */
467     public static final String CACHE_KEY_PHONE_ACCOUNT_TO_SUBID =
468             "cache_key.telephony.phone_account_to_subid";
469     private static final int CACHE_MAX_SIZE = 4;
470 
471     /**
472      * A {@link PropertyInvalidatedCache} which lives in an app's {@link TelephonyManager} instance.
473      * Caches any queries for a mapping between {@link PhoneAccountHandle} and {@code subscription
474      * id}.  The cache may be invalidated from Telephony when phone account re-registration takes
475      * place.
476      */
477     private PropertyInvalidatedCache<PhoneAccountHandle, Integer> mPhoneAccountHandleToSubIdCache =
478             new PropertyInvalidatedCache<PhoneAccountHandle, Integer>(CACHE_MAX_SIZE,
479                     CACHE_KEY_PHONE_ACCOUNT_TO_SUBID) {
480                 @Override
481                 public Integer recompute(PhoneAccountHandle phoneAccountHandle) {
482                     try {
483                         ITelephony telephony = getITelephony();
484                         if (telephony != null) {
485                             return telephony.getSubIdForPhoneAccountHandle(phoneAccountHandle,
486                                     mContext.getOpPackageName(), mContext.getAttributionTag());
487                         }
488                     } catch (RemoteException e) {
489                         throw e.rethrowAsRuntimeException();
490                     }
491                     return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
492                 }
493             };
494 
495     /** Enum indicating multisim variants
496      *  DSDS - Dual SIM Dual Standby
497      *  DSDA - Dual SIM Dual Active
498      *  TSTS - Triple SIM Triple Standby
499      **/
500     /** @hide */
501     @UnsupportedAppUsage(implicitMember =
502             "values()[Landroid/telephony/TelephonyManager$MultiSimVariants;")
503     public enum MultiSimVariants {
504         @UnsupportedAppUsage
505         DSDS,
506         @UnsupportedAppUsage
507         DSDA,
508         @UnsupportedAppUsage
509         TSTS,
510         @UnsupportedAppUsage
511         UNKNOWN
512     };
513 
514     /** @hide */
515     @UnsupportedAppUsage
TelephonyManager(Context context)516     public TelephonyManager(Context context) {
517         this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
518     }
519 
520     /** @hide */
521     @UnsupportedAppUsage
TelephonyManager(Context context, int subId)522     public TelephonyManager(Context context, int subId) {
523         mSubId = subId;
524         mContext = mergeAttributionAndRenouncedPermissions(context.getApplicationContext(),
525             context);
526         mSubscriptionManager = SubscriptionManager.from(mContext);
527     }
528 
529     /** @hide */
530     @UnsupportedAppUsage
TelephonyManager()531     private TelephonyManager() {
532         mContext = null;
533         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
534     }
535 
536     private static TelephonyManager sInstance = new TelephonyManager();
537 
538     /** @hide
539     /* @deprecated - use getSystemService as described above */
540     @Deprecated
541     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDefault()542     public static TelephonyManager getDefault() {
543         return sInstance;
544     }
545 
546     // This method takes the Application context and adds the attributionTag
547     // and renouncedPermissions from the given context.
mergeAttributionAndRenouncedPermissions(Context to, Context from)548     private Context mergeAttributionAndRenouncedPermissions(Context to, Context from) {
549         Context contextToReturn = from;
550         if (to != null) {
551             if (!Objects.equals(from.getAttributionTag(), to.getAttributionTag())) {
552                 contextToReturn = to.createAttributionContext(from.getAttributionTag());
553             } else {
554                 contextToReturn = to;
555             }
556 
557             Set<String> renouncedPermissions =
558                     from.getAttributionSource().getRenouncedPermissions();
559             if (!renouncedPermissions.isEmpty()) {
560                 if (to.getParams() != null) {
561                     contextToReturn = contextToReturn.createContext(
562                             new ContextParams.Builder(to.getParams())
563                                     .setRenouncedPermissions(renouncedPermissions).build());
564                 } else {
565                     contextToReturn = contextToReturn.createContext(
566                             new ContextParams.Builder()
567                                     .setRenouncedPermissions(renouncedPermissions).build());
568                 }
569             }
570         }
571         return contextToReturn;
572     }
573 
getOpPackageName()574     private String getOpPackageName() {
575         // For legacy reasons the TelephonyManager has API for getting
576         // a static instance with no context set preventing us from
577         // getting the op package name. As a workaround we do a best
578         // effort and get the context from the current activity thread.
579         if (mContext != null) {
580             return mContext.getOpPackageName();
581         } else {
582             ITelephony telephony = getITelephony();
583             if (telephony == null) return null;
584             try {
585                 return telephony.getCurrentPackageName();
586             } catch (RemoteException ex) {
587                 return null;
588             } catch (NullPointerException ex) {
589                 return null;
590             }
591         }
592     }
593 
getAttributionTag()594     private String getAttributionTag() {
595         // For legacy reasons the TelephonyManager has API for getting
596         // a static instance with no context set preventing us from
597         // getting the attribution tag.
598         if (mContext != null) {
599             return mContext.getAttributionTag();
600         }
601         return null;
602     }
603 
getRenouncedPermissions()604     private Set<String> getRenouncedPermissions() {
605         // For legacy reasons the TelephonyManager has API for getting
606         // a static instance with no context set preventing us from
607         // getting the attribution source.
608         if (mContext != null) {
609             return mContext.getAttributionSource().getRenouncedPermissions();
610         }
611         return Collections.emptySet();
612     }
613 
614     /**
615      * Post a runnable to the BackgroundThread.
616      *
617      * Used to invoke user callbacks without calling into the caller's executor from the caller's
618      * calling thread context, for example to provide asynchronous error information that is
619      * generated locally (not over a binder thread).
620      *
621      * <p>This is not necessary unless you are invoking caller's code asynchronously from within
622      * the caller's thread context.
623      *
624      * @param r a runnable.
625      */
runOnBackgroundThread(@onNull Runnable r)626     private static void runOnBackgroundThread(@NonNull Runnable r) {
627         try {
628             BackgroundThread.getExecutor().execute(r);
629         } catch (RejectedExecutionException e) {
630             throw new IllegalStateException(
631                     "Failed to post a callback from the caller's thread context.", e);
632         }
633     }
634 
635     /**
636      * Returns the multi SIM variant.
637      *
638      * <ul>
639      *   <li>Returns DSDS for Dual SIM Dual Standby.</li>
640      *   <li>Returns DSDA for Dual SIM Dual Active.</li>
641      *   <li>Returns TSTS for Triple SIM Triple Standby.</li>
642      *   <li>Returns UNKNOWN for others.</li>
643      * </ul>
644      */
645     /** {@hide} */
646     @UnsupportedAppUsage
getMultiSimConfiguration()647     public MultiSimVariants getMultiSimConfiguration() {
648         String mSimConfig =
649                 TelephonyProperties.multi_sim_config().orElse("");
650         if (mSimConfig.equals("dsds")) {
651             return MultiSimVariants.DSDS;
652         } else if (mSimConfig.equals("dsda")) {
653             return MultiSimVariants.DSDA;
654         } else if (mSimConfig.equals("tsts")) {
655             return MultiSimVariants.TSTS;
656         } else {
657             return MultiSimVariants.UNKNOWN;
658         }
659     }
660 
661     /**
662      * Returns the number of phones available.
663      *
664      * <ul>
665      *   <li>Returns 0 if none of voice, sms, data is supported.</li>
666      *   <li>Returns 1 for Single standby mode (Single SIM functionality).</li>
667      *   <li>Returns 2 for Dual standby mode (Dual SIM functionality).</li>
668      *   <li>Returns 3 for Tri standby mode (Tri SIM functionality).</li>
669      * </ul>
670      *
671      * @deprecated Use {@link #getActiveModemCount} instead.
672      */
673     @Deprecated
getPhoneCount()674     public int getPhoneCount() {
675         return getActiveModemCount();
676     }
677 
678     /**
679      * Returns the number of logical modems currently configured to be activated.
680      *
681      * <ul>
682      *   <li>Returns 0 if none of voice, sms, data is supported.</li>
683      *   <li>Returns 1 for Single standby mode (Single SIM functionality).</li>
684      *   <li>Returns 2 for Dual standby mode (Dual SIM functionality).</li>
685      *   <li>Returns 3 for Tri standby mode (Tri SIM functionality).</li>
686      * </ul>
687      */
getActiveModemCount()688     public int getActiveModemCount() {
689         int modemCount = 1;
690         switch (getMultiSimConfiguration()) {
691             case UNKNOWN:
692                 modemCount = 1;
693                 // check for voice and data support, 0 if not supported
694                 if (!isDeviceVoiceCapable() && !isSmsCapable() && !isDataCapable()) {
695                     modemCount = 0;
696                 }
697                 break;
698             case DSDS:
699             case DSDA:
700                 modemCount = 2;
701                 break;
702             case TSTS:
703                 modemCount = 3;
704                 break;
705         }
706         return modemCount;
707     }
708 
709     /**
710      * Return how many logical modem can be potentially active simultaneously, in terms of hardware
711      * capability.
712      * It might return different value from {@link #getActiveModemCount}. For example, for a
713      * dual-SIM capable device operating in single SIM mode (only one logical modem is turned on),
714      * {@link #getActiveModemCount} returns 1 while this API returns 2.
715      */
getSupportedModemCount()716     public int getSupportedModemCount() {
717         return TelephonyProperties.max_active_modems().orElse(getActiveModemCount());
718     }
719 
720     /**
721      * Gets the maximum number of SIMs that can be active, based on the device's multisim
722      * configuration.
723      * @return 1 for single-SIM, DSDS, and TSTS devices. 2 for DSDA devices.
724      * @hide
725      */
726     @SystemApi
getMaxNumberOfSimultaneouslyActiveSims()727     public int getMaxNumberOfSimultaneouslyActiveSims() {
728         switch (getMultiSimConfiguration()) {
729             case UNKNOWN:
730             case DSDS:
731             case TSTS:
732                 return 1;
733             case DSDA:
734                 return 2;
735         }
736         return 1;
737     }
738 
739     /** {@hide} */
740     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)741     public static TelephonyManager from(Context context) {
742         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
743     }
744 
745     /**
746      * Create a new TelephonyManager object pinned to the given subscription ID.
747      *
748      * @return a TelephonyManager that uses the given subId for all calls.
749      */
createForSubscriptionId(int subId)750     public TelephonyManager createForSubscriptionId(int subId) {
751       // Don't reuse any TelephonyManager objects.
752       return new TelephonyManager(mContext, subId);
753     }
754 
755     /**
756      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
757      * phone account.
758      *
759      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
760      * if the phone account does not correspond to a valid subscription ID.
761      */
762     @Nullable
createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle)763     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
764         int subId = getSubscriptionId(phoneAccountHandle);
765         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
766             return null;
767         }
768         return new TelephonyManager(mContext, subId);
769     }
770 
771     /** {@hide} */
772     @UnsupportedAppUsage
isMultiSimEnabled()773     public boolean isMultiSimEnabled() {
774         return getPhoneCount() > 1;
775     }
776 
777     private static final int MAXIMUM_CALL_COMPOSER_PICTURE_SIZE = 80000;
778 
779     /**
780      * Indicates the maximum size of the call composure picture.
781      *
782      * Pictures sent via
783      * {@link #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)}
784      * or {@link #uploadCallComposerPicture(Path, String, Executor, OutcomeReceiver)} must not
785      * exceed this size, or an error will be returned via the callback in those methods.
786      *
787      * @return Maximum file size in bytes.
788      */
getMaximumCallComposerPictureSize()789     public static @BytesLong long getMaximumCallComposerPictureSize() {
790         return MAXIMUM_CALL_COMPOSER_PICTURE_SIZE;
791     }
792 
793     //
794     // Broadcast Intent actions
795     //
796 
797     /**
798      * Broadcast intent action indicating that the call state
799      * on the device has changed.
800      *
801      * <p>
802      * The {@link #EXTRA_STATE} extra indicates the new call state.
803      * If a receiving app has {@link android.Manifest.permission#READ_CALL_LOG} permission, a second
804      * extra {@link #EXTRA_INCOMING_NUMBER} provides the phone number for incoming and outgoing
805      * calls as a String.
806      * <p>
807      * If the receiving app has
808      * {@link android.Manifest.permission#READ_CALL_LOG} and
809      * {@link android.Manifest.permission#READ_PHONE_STATE} permission, it will receive the
810      * broadcast twice; one with the {@link #EXTRA_INCOMING_NUMBER} populated with the phone number,
811      * and another with it blank.  Due to the nature of broadcasts, you cannot assume the order
812      * in which these broadcasts will arrive, however you are guaranteed to receive two in this
813      * case.  Apps which are interested in the {@link #EXTRA_INCOMING_NUMBER} can ignore the
814      * broadcasts where {@link #EXTRA_INCOMING_NUMBER} is not present in the extras (e.g. where
815      * {@link Intent#hasExtra(String)} returns {@code false}).
816      * <p class="note">
817      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
818      * broadcast in version 1.0, but it is no longer sticky.
819      * Instead, use {@link #getCallState} to synchronously query the current call state.
820      *
821      * @see #EXTRA_STATE
822      * @see #EXTRA_INCOMING_NUMBER
823      * @see #getCallState
824      */
825     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
826     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
827     public static final String ACTION_PHONE_STATE_CHANGED =
828             "android.intent.action.PHONE_STATE";
829 
830     /**
831      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
832      * call. By default, the device's default SMS app consumes this message and sends a text message
833      * to the caller. A third party app can also provide this functionality by consuming this Intent
834      * with a {@link android.app.Service} and sending the message using its own messaging system.
835      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
836      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
837      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
838      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
839      * set of phone numbers if there are multiple recipients. For example, {@code
840      * smsto:2065551234}.</p>
841      *
842      * <p>The intent may also contain extras for the message text (in {@link
843      * android.content.Intent#EXTRA_TEXT}) and a message subject
844      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
845      *
846      * <p class="note"><strong>Note:</strong>
847      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
848      * that requires the
849      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
850      * <p>For example, the service that receives this intent can be declared in the manifest file
851      * with an intent filter like this:</p>
852      * <pre>
853      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
854      * &lt;service android:name=".HeadlessSmsSendService"
855      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
856      *          android:exported="true" >
857      *   &lt;intent-filter>
858      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
859      *     &lt;category android:name="android.intent.category.DEFAULT" />
860      *     &lt;data android:scheme="sms" />
861      *     &lt;data android:scheme="smsto" />
862      *     &lt;data android:scheme="mms" />
863      *     &lt;data android:scheme="mmsto" />
864      *   &lt;/intent-filter>
865      * &lt;/service></pre>
866      * <p>
867      * Output: nothing.
868      */
869     @SdkConstant(SdkConstantType.SERVICE_ACTION)
870     public static final String ACTION_RESPOND_VIA_MESSAGE =
871             "android.intent.action.RESPOND_VIA_MESSAGE";
872 
873     /**
874      * The emergency dialer may choose to present activities with intent filters for this
875      * action as emergency assistance buttons that launch the activity when clicked.
876      *
877      * @hide
878      */
879     @SystemApi
880     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
881     public static final String ACTION_EMERGENCY_ASSISTANCE =
882             "android.telephony.action.EMERGENCY_ASSISTANCE";
883 
884     /**
885      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
886      * call settings page launched by
887      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
888      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
889      * which would also like to manage voicemail settings should set this meta-data to {@code true}
890      * in the manifest registration of their application.
891      *
892      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
893      * @see #ACTION_CONFIGURE_VOICEMAIL
894      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
895      */
896     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
897             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
898 
899     /**
900      * Open the voicemail settings activity to make changes to voicemail configuration.
901      *
902      * <p>
903      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} to
904      * configure voicemail.
905      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
906      * API if set.
907      *
908      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
909      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
910      */
911     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
912     public static final String ACTION_CONFIGURE_VOICEMAIL =
913             "android.telephony.action.CONFIGURE_VOICEMAIL";
914 
915     /**
916      * The boolean value indicating whether the voicemail settings activity launched by {@link
917      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
918      * used by dialer implementations which provides their own voicemail settings UI, but still
919      * needs to expose device specific voicemail settings to the user.
920      *
921      * @see #ACTION_CONFIGURE_VOICEMAIL
922      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
923      */
924     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
925             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
926 
927     /**
928      * @hide
929      */
930     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
931 
932     /**
933      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
934      * for a String containing the new call state.
935      *
936      * <p class="note">
937      * Retrieve with
938      * {@link android.content.Intent#getStringExtra(String)}.
939      *
940      * @see #EXTRA_STATE_IDLE
941      * @see #EXTRA_STATE_RINGING
942      * @see #EXTRA_STATE_OFFHOOK
943      */
944     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
945 
946     /**
947      * Value used with {@link #EXTRA_STATE} corresponding to
948      * {@link #CALL_STATE_IDLE}.
949      */
950     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
951 
952     /**
953      * Value used with {@link #EXTRA_STATE} corresponding to
954      * {@link #CALL_STATE_RINGING}.
955      */
956     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
957 
958     /**
959      * Value used with {@link #EXTRA_STATE} corresponding to
960      * {@link #CALL_STATE_OFFHOOK}.
961      */
962     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
963 
964     /**
965      * Extra key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
966      * for a String containing the incoming or outgoing phone number.
967      * <p>
968      * This extra is only populated for receivers of the {@link #ACTION_PHONE_STATE_CHANGED}
969      * broadcast which have been granted the {@link android.Manifest.permission#READ_CALL_LOG} and
970      * {@link android.Manifest.permission#READ_PHONE_STATE} permissions.
971      * <p>
972      * For incoming calls, the phone number is only guaranteed to be populated when the
973      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_RINGING}.
974      * If the incoming caller is from an unknown number, the extra will be populated with an empty
975      * string.
976      * For outgoing calls, the phone number is only guaranteed to be populated when the
977      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_OFFHOOK}.
978      * <p class="note">
979      * Retrieve with
980      * {@link android.content.Intent#getStringExtra(String)}.
981      * <p>
982      *
983      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
984      * to retrieve the phone number for calls instead.  Apps performing call screening should use
985      * the {@link CallScreeningService} API instead.
986      */
987     @Deprecated
988     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
989 
990     /**
991      * Broadcast intent action indicating that call disconnect cause has changed.
992      *
993      * <p>
994      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
995      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
996      *
997      * <p class="note">
998      * Requires the READ_PRECISE_PHONE_STATE permission.
999      *
1000      * @see #EXTRA_DISCONNECT_CAUSE
1001      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
1002      *
1003      * @hide
1004      */
1005     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1006     public static final String ACTION_CALL_DISCONNECT_CAUSE_CHANGED =
1007             "android.intent.action.CALL_DISCONNECT_CAUSE";
1008 
1009     /**
1010      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and {@link
1011      * TelephonyCallback.PreciseCallStateListener#onPreciseCallStateChanged(PreciseCallState)} for
1012      * an integer containing the disconnect cause.
1013      *
1014      * @see DisconnectCause
1015      *
1016      * <p class="note">
1017      * Retrieve with
1018      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
1019      *
1020      * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
1021      * @hide
1022      */
1023     @Deprecated
1024     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
1025 
1026     /**
1027      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and {@link
1028      * TelephonyCallback.PreciseCallStateListener#onPreciseCallStateChanged(PreciseCallState)} for
1029      * an integer containing the disconnect cause provided by the RIL.
1030      *
1031      * @see PreciseDisconnectCause
1032      *
1033      * <p class="note">
1034      * Retrieve with
1035      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
1036      *
1037      * @hide
1038      */
1039     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
1040 
1041     /**
1042      * Broadcast intent action for letting the default dialer to know to show voicemail
1043      * notification.
1044      *
1045      * <p>
1046      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
1047      * voicemail is received on.
1048      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
1049      * voicemails.
1050      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
1051      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
1052      * will call the voicemail number when sent. This extra will be empty if the voicemail number
1053      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
1054      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
1055      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
1056      * available when the voicemail number is not set.
1057      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
1058      * notification.
1059      *
1060      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
1061      * @see #EXTRA_NOTIFICATION_COUNT
1062      * @see #EXTRA_VOICEMAIL_NUMBER
1063      * @see #EXTRA_CALL_VOICEMAIL_INTENT
1064      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
1065      * @see #EXTRA_IS_REFRESH
1066      */
1067     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
1068             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
1069 
1070     /**
1071      * The extra used with an {@link #ACTION_CONFIGURE_VOICEMAIL} and
1072      * {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify the
1073      * {@link PhoneAccountHandle} the configuration or notification is for.
1074      * <p class="note">
1075      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
1076      */
1077     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
1078             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
1079 
1080     /**
1081      * The number of voice messages associated with the notification.
1082      */
1083     public static final String EXTRA_NOTIFICATION_COUNT =
1084             "android.telephony.extra.NOTIFICATION_COUNT";
1085 
1086     /**
1087      * The voicemail number.
1088      */
1089     public static final String EXTRA_VOICEMAIL_NUMBER =
1090             "android.telephony.extra.VOICEMAIL_NUMBER";
1091 
1092     /**
1093      * The intent to call voicemail.
1094      */
1095     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
1096             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
1097 
1098     /**
1099      * The intent to launch voicemail settings.
1100      */
1101     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
1102             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
1103 
1104     /**
1105      * Boolean value representing whether the {@link
1106      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
1107      * notification. Notification refresh happens after reboot or connectivity changes. The user has
1108      * already been notified for the voicemail so it should not alert the user, and should not be
1109      * shown again if the user has dismissed it.
1110      */
1111     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
1112 
1113     /**
1114      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
1115      * successfully handed over from WIFI to LTE.
1116      * <p>
1117      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1118      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1119      * @hide
1120      */
1121     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
1122             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
1123 
1124     /**
1125      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
1126      * successfully handed over from LTE to WIFI.
1127      * <p>
1128      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1129      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1130      * @hide
1131      */
1132     public static final String EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI =
1133             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI";
1134 
1135     /**
1136      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
1137      * handed over from LTE to WIFI.
1138      * <p>
1139      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1140      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1141      * @hide
1142      */
1143     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
1144             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
1145 
1146     /**
1147      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
1148      * audio because the data limit was reached.
1149      * <p>
1150      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1151      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1152      * @hide
1153      */
1154     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
1155             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
1156 
1157     /**
1158      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
1159      * audio because the data was disabled.
1160      * <p>
1161      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1162      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1163      * @hide
1164      */
1165     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
1166             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
1167 
1168     /**
1169      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
1170      * the user when an international call is placed while on WFC only.
1171      * <p>
1172      * Used when the carrier config value
1173      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
1174      * is on WFC (VoLTE not available) and an international number is dialed.
1175      * <p>
1176      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1177      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1178      * @hide
1179      */
1180     public static final String EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
1181             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
1182 
1183     /**
1184      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
1185      * forwarded to another number.
1186      * <p>
1187      * Sent in response to an IMS supplementary service notification indicating the call has been
1188      * forwarded.
1189      * <p>
1190      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1191      * The {@link Bundle} parameter is expected to be null when this connection event is used.
1192      * @hide
1193      */
1194     public static final String EVENT_CALL_FORWARDED =
1195             "android.telephony.event.EVENT_CALL_FORWARDED";
1196 
1197     /**
1198      * {@link android.telecom.Connection} event used to indicate that a supplementary service
1199      * notification has been received.
1200      * <p>
1201      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1202      * The {@link Bundle} parameter is expected to include the following extras:
1203      * <ul>
1204      *     <li>{@link #EXTRA_NOTIFICATION_TYPE} - the notification type.</li>
1205      *     <li>{@link #EXTRA_NOTIFICATION_CODE} - the notification code.</li>
1206      *     <li>{@link #EXTRA_NOTIFICATION_MESSAGE} - human-readable message associated with the
1207      *     supplementary service notification.</li>
1208      * </ul>
1209      * @hide
1210      */
1211     public static final String EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION =
1212             "android.telephony.event.EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION";
1213 
1214     /**
1215      * Event reported from the Telephony stack to indicate that the {@link Connection} is not
1216      * able to find any network and likely will not get connected. Upon receiving this event,
1217      * the dialer app should start the app included in the extras bundle of this event if satellite
1218      * is provisioned.
1219      * <p>
1220      * The dialer app receives this event via
1221      * {@link Call.Callback#onConnectionEvent(Call, String, Bundle)}.
1222      * <p>
1223      * The {@link Bundle} parameter is guaranteed to include the following extras if the below
1224      * conditions are met:
1225      * <ul>
1226      *     <li>{@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE} - the recommending handover
1227      *         type.</li>
1228      *     <li>{@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT} - the {@link PendingIntent}
1229      *         which will be launched by the Dialer app when receiving this connection event.</li>
1230      * </ul>
1231      * <p>
1232      * If the device is connected to satellite via carrier within the hysteresis time defined by
1233      * the carrier config
1234      * {@link CarrierConfigManager#KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT}, the component of
1235      * the {@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT} will be set to the default SMS
1236      * app.
1237      * <p>
1238      * Otherwise, if the overlay config {@code config_oem_enabled_satellite_handover_app} is
1239      * present, the app defined by this config will be used as the component of the
1240      * {@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT}. If this overlay config is empty,
1241      * {@link #EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT} will not be included in the event
1242      * {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE}.
1243      */
1244     public static final String EVENT_DISPLAY_EMERGENCY_MESSAGE =
1245             "android.telephony.event.DISPLAY_EMERGENCY_MESSAGE";
1246 
1247     /**
1248      * Integer extra key used with {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE} which indicates
1249      * the type of handover from emergency call to satellite messaging.
1250      * <p>
1251      * Will be either
1252      * android.telephony.satellite.SatelliteManager#EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE_SOS
1253      * or
1254      * android.telephony.satellite.SatelliteManager#EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE_T911
1255      * <p>
1256      * Set in the extras for the {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE} connection event.
1257      */
1258     public static final String EXTRA_EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE =
1259             "android.telephony.extra.EMERGENCY_CALL_TO_SATELLITE_HANDOVER_TYPE";
1260 
1261     /**
1262      * Extra key used with the {@link #EVENT_DISPLAY_EMERGENCY_MESSAGE} for a {@link PendingIntent}
1263      * which will be launched by the Dialer app.
1264      */
1265     public static final String EXTRA_EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT =
1266             "android.telephony.extra.EMERGENCY_CALL_TO_SATELLITE_LAUNCH_INTENT";
1267 
1268     /**
1269      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1270      * the type of supplementary service notification which occurred.
1271      * Will be either
1272      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_1}
1273      * or
1274      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_2}
1275      * <p>
1276      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1277      * @hide
1278      */
1279     public static final String EXTRA_NOTIFICATION_TYPE =
1280             "android.telephony.extra.NOTIFICATION_TYPE";
1281 
1282     /**
1283      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1284      * the supplementary service notification which occurred.
1285      * <p>
1286      * Depending on the {@link #EXTRA_NOTIFICATION_TYPE}, the code will be one of the {@code CODE_*}
1287      * codes defined in {@link com.android.internal.telephony.gsm.SuppServiceNotification}.
1288      * <p>
1289      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1290      * @hide
1291      */
1292     public static final String EXTRA_NOTIFICATION_CODE =
1293             "android.telephony.extra.NOTIFICATION_CODE";
1294 
1295     /**
1296      * {@link CharSequence} extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION}
1297      * which contains a human-readable message which can be displayed to the user for the
1298      * supplementary service notification.
1299      * <p>
1300      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1301      * @hide
1302      */
1303     public static final String EXTRA_NOTIFICATION_MESSAGE =
1304             "android.telephony.extra.NOTIFICATION_MESSAGE";
1305 
1306     /* Visual voicemail protocols */
1307 
1308     /**
1309      * The OMTP protocol.
1310      */
1311     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
1312 
1313     /**
1314      * A flavor of OMTP protocol with a different mobile originated (MO) format
1315      */
1316     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
1317 
1318     /**
1319      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
1320      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
1321      * setting, this key will not exist.
1322      *
1323      * @see #getVisualVoicemailSettings()
1324      * @hide
1325      */
1326     @SystemApi
1327     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
1328             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
1329 
1330     /**
1331      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
1332      * access PIN scrambled during the auto provisioning process. The user is expected to reset
1333      * their PIN if this value is not {@code null}.
1334      *
1335      * @see #getVisualVoicemailSettings()
1336      * @hide
1337      */
1338     @SystemApi
1339     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
1340             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
1341 
1342     /**
1343      * Broadcast action to be received by Broadcast receivers.
1344      *
1345      * Indicates multi-SIM configuration is changed. For example, it changed
1346      * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
1347      *
1348      * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
1349      * or that all steps during multi-SIM change are done. To know those information you still need
1350      * to listen to SIM_STATE changes or active subscription changes.
1351      *
1352      * See extra of {@link #EXTRA_ACTIVE_SIM_SUPPORTED_COUNT} for updated value.
1353      */
1354     public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
1355             "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
1356 
1357 
1358     /**
1359      * The number of active SIM supported by current multi-SIM config. It's not related to how many
1360      * SIM/subscriptions are currently active.
1361      *
1362      * Same value will be returned by {@link #getActiveModemCount()}.
1363      *
1364      * For single SIM mode, it's 1.
1365      * For DSDS or DSDA mode, it's 2.
1366      * For triple-SIM mode, it's 3.
1367      *
1368      * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
1369      *
1370      * type: integer
1371      */
1372     public static final String EXTRA_ACTIVE_SIM_SUPPORTED_COUNT =
1373             "android.telephony.extra.ACTIVE_SIM_SUPPORTED_COUNT";
1374 
1375     /**
1376      * @hide
1377      */
1378     public static final String USSD_RESPONSE = "USSD_RESPONSE";
1379 
1380     /**
1381      * USSD return code success.
1382      * @hide
1383      */
1384     public static final int USSD_RETURN_SUCCESS = 100;
1385 
1386     /**
1387      * Failed code returned when the mobile network has failed to complete a USSD request.
1388      * <p>
1389      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1390      * TelephonyManager, String, int)}.
1391      */
1392     public static final int USSD_RETURN_FAILURE = -1;
1393 
1394     /**
1395      * Failure code returned when a USSD request has failed to execute because the Telephony
1396      * service is unavailable.
1397      * <p>
1398      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1399      * TelephonyManager, String, int)}.
1400      */
1401     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
1402 
1403     /**
1404      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which leaves the roaming
1405      * mode set to the radio default or to the user's preference if they've indicated one.
1406      *
1407      * @deprecated Legacy CDMA is unsupported.
1408      */
1409     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
1410     @Deprecated
1411     public static final int CDMA_ROAMING_MODE_RADIO_DEFAULT = -1;
1412     /**
1413      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which only permits
1414      * connections on home networks.
1415      *
1416      * @deprecated Legacy CDMA is unsupported.
1417      */
1418     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
1419     @Deprecated
1420     public static final int CDMA_ROAMING_MODE_HOME = 0;
1421     /**
1422      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1423      * affiliated networks.
1424      *
1425      * @deprecated Legacy CDMA is unsupported.
1426      */
1427     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
1428     @Deprecated
1429     public static final int CDMA_ROAMING_MODE_AFFILIATED = 1;
1430     /**
1431      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1432      * any network.
1433      *
1434      * @deprecated Legacy CDMA is unsupported.
1435      */
1436     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
1437     @Deprecated
1438     public static final int CDMA_ROAMING_MODE_ANY = 2;
1439 
1440     /** @hide
1441      * @deprecated Legacy CDMA is unsupported.
1442      */
1443     @Deprecated
1444     @IntDef(prefix = { "CDMA_ROAMING_MODE_" }, value = {
1445             CDMA_ROAMING_MODE_RADIO_DEFAULT,
1446             CDMA_ROAMING_MODE_HOME,
1447             CDMA_ROAMING_MODE_AFFILIATED,
1448             CDMA_ROAMING_MODE_ANY
1449     })
1450     @Retention(RetentionPolicy.SOURCE)
1451     public @interface CdmaRoamingMode{}
1452 
1453     /**
1454      * An unknown carrier id. It could either be subscription unavailable or the subscription
1455      * carrier cannot be recognized. Unrecognized carriers here means
1456      * {@link #getSimOperator() MCC+MNC} cannot be identified.
1457      */
1458     public static final int UNKNOWN_CARRIER_ID = -1;
1459 
1460     /**
1461      * An unknown carrier id list version.
1462      * @hide
1463      */
1464     @TestApi
1465     public static final int UNKNOWN_CARRIER_ID_LIST_VERSION = -1;
1466 
1467     /**
1468      * Broadcast Action: The subscription carrier identity has changed.
1469      * This intent could be sent on the following events:
1470      * <ul>
1471      *   <li>Subscription absent. Carrier identity could change from a valid id to
1472      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID}.</li>
1473      *   <li>Subscription loaded. Carrier identity could change from
1474      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID} to a valid id.</li>
1475      *   <li>The subscription carrier is recognized after a remote update.</li>
1476      * </ul>
1477      * The intent will have the following extra values:
1478      * <ul>
1479      *   <li>{@link #EXTRA_CARRIER_ID} The up-to-date carrier id of the current subscription id.
1480      *   </li>
1481      *   <li>{@link #EXTRA_CARRIER_NAME} The up-to-date carrier name of the current subscription.
1482      *   </li>
1483      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1484      *   identity.
1485      *   </li>
1486      * </ul>
1487      * <p class="note">This is a protected intent that can only be sent by the system.
1488      */
1489     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1490     public static final String ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED =
1491             "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED";
1492 
1493     /**
1494      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which indicates
1495      * the updated carrier id returned by {@link TelephonyManager#getSimCarrierId()}.
1496      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1497      * the carrier cannot be identified.
1498      */
1499     public static final String EXTRA_CARRIER_ID = "android.telephony.extra.CARRIER_ID";
1500 
1501     /**
1502      * An string extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which
1503      * indicates the updated carrier name of the current subscription.
1504      * @see TelephonyManager#getSimCarrierIdName()
1505      * <p>Carrier name is a user-facing name of the carrier id {@link #EXTRA_CARRIER_ID},
1506      * usually the brand name of the subsidiary (e.g. T-Mobile).
1507      */
1508     public static final String EXTRA_CARRIER_NAME = "android.telephony.extra.CARRIER_NAME";
1509 
1510     /**
1511      * Broadcast Action: The subscription specific carrier identity has changed.
1512      *
1513      * A specific carrier ID returns the fine-grained carrier ID of the current subscription.
1514      * It can represent the fact that a carrier may be in effect an aggregation of other carriers
1515      * (ie in an MVNO type scenario) where each of these specific carriers which are used to make
1516      * up the actual carrier service may have different carrier configurations.
1517      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
1518      * different carrier configuration for different service offering such as a prepaid plan.
1519      *
1520      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
1521      * about the carrier itself should use the regular carrier ID returned by
1522      * {@link #getSimCarrierId()}.
1523      *
1524      * <p>Similar like {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED}, this intent will be
1525      * sent on the event of {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} while its also
1526      * possible to be sent without {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} when
1527      * specific carrier ID changes while carrier ID remains the same.
1528      * e.g, the same subscription switches to different IMSI could potentially change its
1529      * specific carrier ID while carrier id remains the same.
1530      * @see #getSimSpecificCarrierId()
1531      * @see #getSimCarrierId()
1532      *
1533      * The intent will have the following extra values:
1534      * <ul>
1535      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_ID} The up-to-date specific carrier id of the
1536      *   current subscription.
1537      *   </li>
1538      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_NAME} The up-to-date name of the specific carrier id.
1539      *   </li>
1540      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1541      *   identity.
1542      *   </li>
1543      * </ul>
1544      * <p class="note">This is a protected intent that can only be sent by the system.
1545      */
1546     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1547     public static final String ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED =
1548             "android.telephony.action.SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED";
1549 
1550     /**
1551      * An int extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED} which
1552      * indicates the updated specific carrier id returned by
1553      * {@link TelephonyManager#getSimSpecificCarrierId()}. Note, its possible specific carrier id
1554      * changes while {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} remains the same
1555      * e.g, when subscription switch to different IMSIs.
1556      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1557      * the carrier cannot be identified.
1558      */
1559     public static final String EXTRA_SPECIFIC_CARRIER_ID =
1560             "android.telephony.extra.SPECIFIC_CARRIER_ID";
1561 
1562     /**
1563      * An string extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED}
1564      * which indicates the updated specific carrier name returned by
1565      * {@link TelephonyManager#getSimSpecificCarrierIdName()}.
1566      * <p>it's a user-facing name of the specific carrier id {@link #EXTRA_SPECIFIC_CARRIER_ID}
1567      * e.g, Tracfone-AT&T
1568      */
1569     public static final String EXTRA_SPECIFIC_CARRIER_NAME =
1570             "android.telephony.extra.SPECIFIC_CARRIER_NAME";
1571 
1572     /**
1573      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} to indicate the
1574      * subscription which has changed; or in general whenever a subscription ID needs specified.
1575      */
1576     public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
1577 
1578     /**
1579      * Broadcast Action: The Service Provider string(s) have been updated. Activities or
1580      * services that use these strings should update their display.
1581      *
1582      * <p>The intent will have the following extra values:
1583      * <dl>
1584      *   <dt>{@link #EXTRA_SHOW_PLMN}</dt>
1585      *   <dd>Boolean that indicates whether the PLMN should be shown.</dd>
1586      *   <dt>{@link #EXTRA_PLMN}</dt>
1587      *   <dd>The operator name of the registered network, as a string.</dd>
1588      *   <dt>{@link #EXTRA_SHOW_SPN}</dt>
1589      *   <dd>Boolean that indicates whether the SPN should be shown.</dd>
1590      *   <dt>{@link #EXTRA_SPN}</dt>
1591      *   <dd>The service provider name, as a string.</dd>
1592      *   <dt>{@link #EXTRA_DATA_SPN}</dt>
1593      *   <dd>The service provider name for data service, as a string.</dd>
1594      * </dl>
1595      *
1596      * Note that {@link #EXTRA_SHOW_PLMN} may indicate that {@link #EXTRA_PLMN} should be displayed,
1597      * even though the value for {@link #EXTRA_PLMN} is null. This can happen, for example, if the
1598      * phone has not registered to a network yet. In this case the receiver may substitute an
1599      * appropriate placeholder string (eg, "No service").
1600      *
1601      * It is recommended to display {@link #EXTRA_PLMN} before / above {@link #EXTRA_SPN} if
1602      * both are displayed.
1603      *
1604      * <p>Note: this is a protected intent that can only be sent by the system.
1605      * @hide
1606      */
1607     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1608     public static final String ACTION_SERVICE_PROVIDERS_UPDATED =
1609             "android.telephony.action.SERVICE_PROVIDERS_UPDATED";
1610 
1611     /**
1612      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1613      * whether the PLMN should be shown.
1614      * @hide
1615      */
1616     public static final String EXTRA_SHOW_PLMN = "android.telephony.extra.SHOW_PLMN";
1617 
1618     /**
1619      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1620      * the operator name of the registered network.
1621      * @hide
1622      */
1623     public static final String EXTRA_PLMN = "android.telephony.extra.PLMN";
1624 
1625     /**
1626      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1627      * whether the PLMN should be shown.
1628      * @hide
1629      */
1630     public static final String EXTRA_SHOW_SPN = "android.telephony.extra.SHOW_SPN";
1631 
1632     /**
1633      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1634      * the service provider name.
1635      * @hide
1636      */
1637     public static final String EXTRA_SPN = "android.telephony.extra.SPN";
1638 
1639     /**
1640      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1641      * the service provider name for data service.
1642      * @hide
1643      */
1644     public static final String EXTRA_DATA_SPN = "android.telephony.extra.DATA_SPN";
1645 
1646     /**
1647      * Broadcast intent action indicating that when data stall recovery is attempted by Telephony,
1648      * intended for report every data stall recovery step attempted.
1649      *
1650      * <p>
1651      * The {@link #EXTRA_RECOVERY_ACTION} extra indicates the action associated with the data
1652      * stall recovery.
1653      * The phone id where the data stall recovery is attempted.
1654      *
1655      * <p class="note">
1656      * Requires the READ_PHONE_STATE permission.
1657      *
1658      * <p class="note">
1659      * This is a protected intent that can only be sent by the system.
1660      *
1661      * @see #EXTRA_RECOVERY_ACTION
1662      *
1663      * @hide
1664      */
1665     // TODO(b/78370030) : Restrict this to system applications only
1666     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1667     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1668     public static final String ACTION_DATA_STALL_DETECTED =
1669             "android.intent.action.DATA_STALL_DETECTED";
1670 
1671     /**
1672      * A service action that identifies
1673      * a {@link android.service.carrier.CarrierMessagingClientService} subclass in the
1674      * AndroidManifest.xml.
1675      *
1676      * <p>See {@link android.service.carrier.CarrierMessagingClientService} for the details.
1677      */
1678     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1679     public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE =
1680             "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
1681 
1682     /**
1683      * An int extra used with {@link #ACTION_DATA_STALL_DETECTED} to indicate the
1684      * action associated with the data stall recovery.
1685      *
1686      * @see #ACTION_DATA_STALL_DETECTED
1687      *
1688      * @hide
1689      */
1690     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
1691 
1692     private static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000;
1693 
1694     /**
1695      * Intent sent when an error occurs that debug tools should log and possibly take further
1696      * action such as capturing vendor-specific logs.
1697      *
1698      * A privileged application that reads these events should take appropriate vendor-specific
1699      * action to record the event and collect further information to assist in analysis, debugging,
1700      * and resolution of any associated issue.
1701      *
1702      * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
1703      * should generally be sent at a low rate. Instead, this mechanism should be used for the
1704      * framework to notify a debugging application that an event (such as a bug) has occured
1705      * within the framework if that event should trigger the collection and preservation of other
1706      * more detailed device state for debugging.
1707      *
1708      * <p>At most one application can receive these events and should register a receiver in
1709      * in the application manifest. For performance reasons, if no application to receive these
1710      * events is detected at boot, then these events will not be sent.
1711      *
1712      * <p>Each event will include an {@link EXTRA_ANOMALY_ID} that will uniquely identify the
1713      * event that has occurred. Each event will be sent to the diagnostic monitor only once per
1714      * boot cycle (as another optimization).
1715      *
1716      * @see #EXTRA_ANOMALY_ID
1717      * @see #EXTRA_ANOMALY_DESCRIPTION
1718      * @hide
1719      */
1720     @SystemApi
1721     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1722     public static final String ACTION_ANOMALY_REPORTED =
1723             "android.telephony.action.ANOMALY_REPORTED";
1724 
1725     /**
1726      * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
1727      *
1728      * This field must be included in all {@link ACTION_ANOMALY_REPORTED} events.
1729      *
1730      * @see #ACTION_ANOMALY_REPORTED
1731      * @hide
1732      */
1733     @SystemApi
1734     public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
1735 
1736     /**
1737      * A freeform string description of the Anomaly.
1738      *
1739      * This field is optional for all {@link ACTION_ANOMALY_REPORTED}s, as a guideline should not
1740      * exceed 80 characters, and should be as short as possible to convey the essence of the event.
1741      *
1742      * @see #ACTION_ANOMALY_REPORTED
1743      * @hide
1744      */
1745     @SystemApi
1746     public static final String EXTRA_ANOMALY_DESCRIPTION =
1747             "android.telephony.extra.ANOMALY_DESCRIPTION";
1748 
1749     /**
1750      * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
1751      *
1752      * @hide
1753      */
1754     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1755     public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
1756             "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
1757 
1758     /**
1759      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1760      * to indicate what type of SIM selection is needed.
1761      *
1762      * @hide
1763      */
1764     public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
1765             "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
1766 
1767     /** @hide */
1768     @IntDef({
1769             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE,
1770             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
1771             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE,
1772             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS,
1773             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL
1774     })
1775     @Retention(RetentionPolicy.SOURCE)
1776     public @interface DefaultSubscriptionSelectType{}
1777 
1778     /**
1779      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1780      * to indicate there's no need to re-select any default subscription.
1781      * @hide
1782      */
1783     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
1784 
1785     /**
1786      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1787      * to indicate there's a need to select default data subscription.
1788      * @hide
1789      */
1790     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
1791 
1792     /**
1793      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1794      * to indicate there's a need to select default voice call subscription.
1795      * @hide
1796      */
1797     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
1798 
1799     /**
1800      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1801      * to indicate there's a need to select default sms subscription.
1802      * @hide
1803      */
1804     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
1805 
1806     /**
1807      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1808      * to indicate the current SIM should be preferred for all data / voice / sms.
1809      * {@link #EXTRA_SUBSCRIPTION_ID} will specified to indicate
1810      * which subscription should be the default subscription.
1811      * @hide
1812      */
1813     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL = 4;
1814 
1815     /**
1816      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1817      * to indicate that default subscription for data/sms/voice is now determined, that
1818      * it should dismiss any dialog or pop-ups that is asking user to select default sub.
1819      * This is used when, for example, opportunistic subscription is configured. At that
1820      * time the primary becomes default sub there's no need to ask user to select anymore.
1821      * @hide
1822      */
1823     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS = 5;
1824 
1825     /**
1826      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1827      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1828      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1829      *
1830      * @deprecated Legacy CDMA is unsupported.
1831      * @hide
1832      */
1833     @Deprecated
1834     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1835             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1836 
1837     /** @hide
1838      * @deprecated Legacy CDMA is unsupported.
1839      */
1840     @Deprecated
1841     @IntDef({
1842             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1843             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1844     })
1845     @Retention(RetentionPolicy.SOURCE)
1846     public @interface SimCombinationWarningType{}
1847 
1848     /**
1849      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1850      * to indicate there's no SIM combination warning.
1851      *
1852      * @deprecated Legacy CDMA is unsupported.
1853      * @hide
1854      */
1855     @Deprecated
1856     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1857 
1858     /**
1859      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1860      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1861      *
1862      * @deprecated Legacy CDMA is unsupported.
1863      * @hide
1864      */
1865     @Deprecated
1866     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1867 
1868     /**
1869      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1870      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1871      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1872      * name will be "operator1 & operator2".
1873      *
1874      * TODO(b/379356026): Deprecate if this is CDMA specific
1875      * @hide
1876      */
1877     public static final String EXTRA_SIM_COMBINATION_NAMES =
1878             "android.telephony.extra.SIM_COMBINATION_NAMES";
1879 
1880     /**
1881      * <p>Broadcast Action: The emergency callback mode is changed.
1882      * <ul>
1883      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1884      *   false=ECM off</li>
1885      * </ul>
1886      * <p class="note">
1887      * You can <em>not</em> receive this through components declared
1888      * in manifests, only by explicitly registering for it with
1889      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1890      * android.content.IntentFilter) Context.registerReceiver()}.
1891      *
1892      * <p class="note">This is a protected intent that can only be sent by the system.
1893      *
1894      * @see #EXTRA_PHONE_IN_ECM_STATE
1895      *
1896      * @hide
1897      */
1898     @SystemApi
1899     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1900     @SuppressLint("ActionValue")
1901     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1902             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1903 
1904 
1905     /**
1906      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1907      * Indicates whether the phone is in an emergency phone state.
1908      *
1909      * @hide
1910      */
1911     @SystemApi
1912     public static final String EXTRA_PHONE_IN_ECM_STATE =
1913             "android.telephony.extra.PHONE_IN_ECM_STATE";
1914 
1915     /**
1916      * Broadcast action sent when a data connection is redirected with validation failure.
1917      *
1918      * This action is intended for sim/account status checks and only sent to the carrier apps
1919      * specified in the carrier config for the subscription ID that's attached to this intent.
1920      *
1921      * The intent will have the following extra values:
1922      * <ul>
1923      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1924      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>A string indicating the redirection url</dd>
1925      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1926      *          <dd>The subscription ID on which the validation failure happened.</dd>
1927      * </ul>
1928      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1929      */
1930     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1931     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1932             "android.telephony.action.CARRIER_SIGNAL_REDIRECTED";
1933 
1934     /**
1935      * Broadcast action sent when a data connection setup fails.
1936      *
1937      * This action is intended for sim/account status checks and only sent to the carrier apps
1938      * specified in the carrier config for the subscription ID that's attached to this intent.
1939      *
1940      * The intent will have the following extra values:
1941      * <ul>
1942      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1943      *   <li>{@link #EXTRA_DATA_FAIL_CAUSE}</li><dd>A integer indicating the data fail cause.</dd>
1944      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1945      *          <dd>The subscription ID on which the data setup failure happened.</dd>
1946      * </ul>
1947      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1948      */
1949     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1950     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1951             "android.telephony.action.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1952 
1953     /**
1954      * Broadcast action sent when a PCO value becomes available from the modem.
1955      *
1956      * This action is intended for sim/account status checks and only sent to the carrier apps
1957      * specified in the carrier config for the subscription ID that's attached to this intent.
1958      *
1959      * The intent will have the following extra values:</p>
1960      * <ul>
1961      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1962      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>An integer indicating the protocol of the apn
1963      *      connection</dd>
1964      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the PCO id for the data.</dd>
1965      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of PCO data read from modem.</dd>
1966      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1967      *          <dd>The subscription ID for which the PCO info was received.</dd>
1968      * </ul>
1969      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1970      */
1971     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1972     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1973             "android.telephony.action.CARRIER_SIGNAL_PCO_VALUE";
1974 
1975     /**
1976      * Broadcast action sent when the availability of the system default network changes.
1977      *
1978      * @see ConnectivityManager#registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)
1979      *
1980      * This action is intended for carrier apps to set/reset carrier actions. It is only sent to the
1981      * carrier apps specified in the carrier config for the subscription ID attached to this intent.
1982      *
1983      * The intent will have the following extra values:</p>
1984      * <ul>
1985      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1986      *   <dd>{@code true} if the default network is now available, {@code false} otherwise.</dd>
1987      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1988      *          <dd>The subscription ID on which the default network availability changed.</dd>
1989      * </ul>
1990      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1991      */
1992     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1993     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1994             "android.telephony.action.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1995 
1996     /**
1997      * Broadcast action sent when carrier apps should reset their internal state.
1998      *
1999      * Sent when certain events such as turning on/off mobile data, removing the SIM, etc. require
2000      * carrier apps to reset their state.
2001      *
2002      * This action is intended to signal carrier apps to perform cleanup operations. It is only sent
2003      * to the carrier apps specified in the carrier config for the subscription ID attached to
2004      * this intent.
2005      *
2006      * The intent will have the following extra values:</p>
2007      * <ul>
2008      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
2009      *          <dd>The subscription ID for which state should be reset.</dd>
2010      * </ul>
2011      * <p class="note">This is a protected intent that can only be sent by the system.</p>
2012      */
2013     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2014     public static final String ACTION_CARRIER_SIGNAL_RESET =
2015             "android.telephony.action.CARRIER_SIGNAL_RESET";
2016 
2017     /**
2018      * String extra containing the redirection URL sent with
2019      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
2020      */
2021     public static final String EXTRA_REDIRECTION_URL = "android.telephony.extra.REDIRECTION_URL";
2022 
2023     /**
2024      * An integer extra containing the data fail cause.
2025      *
2026      * Sent with {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}. See {@link DataFailCause}
2027      * for a list of possible values.
2028      */
2029     public static final String EXTRA_DATA_FAIL_CAUSE = "android.telephony.extra.DATA_FAIL_CAUSE";
2030 
2031     /**
2032      * An integer extra containing the APN type.
2033      *
2034      * Sent with the  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
2035      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}, and {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE}
2036      * broadcasts.
2037      * See the {@code TYPE_} constants in {@link ApnSetting} for a list of possible values.
2038      */
2039     public static final String EXTRA_APN_TYPE = "android.telephony.extra.APN_TYPE";
2040 
2041     /**
2042      * An integer extra containing the protocol of the apn connection.
2043      *
2044      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
2045      * See the {@code PROTOCOL_*} constants in {@link ApnSetting} for a list of possible values.
2046      */
2047     public static final String EXTRA_APN_PROTOCOL = "android.telephony.extra.APN_PROTOCOL";
2048 
2049     /**
2050      * An integer extra indicating the ID for the PCO data.
2051      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
2052      */
2053     public static final String EXTRA_PCO_ID = "android.telephony.extra.PCO_ID";
2054 
2055     /**
2056      * A byte array extra containing PCO data read from the modem.
2057      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
2058      */
2059     public static final String EXTRA_PCO_VALUE = "android.telephony.extra.PCO_VALUE";
2060 
2061     /**
2062      * A boolean extra indicating the availability of the default network.
2063      * Sent with the {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcast.
2064      */
2065     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE =
2066             "android.telephony.extra.DEFAULT_NETWORK_AVAILABLE";
2067 
2068     /**
2069      * <p>Broadcast Action: The emergency call state is changed.
2070      * <ul>
2071      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
2072      *   call, false otherwise</li>
2073      * </ul>
2074      * <p class="note">
2075      * You can <em>not</em> receive this through components declared
2076      * in manifests, only by explicitly registering for it with
2077      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
2078      * android.content.IntentFilter) Context.registerReceiver()}.
2079      *
2080      * <p class="note">This is a protected intent that can only be sent by the system.
2081      *
2082      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
2083      *
2084      * @hide
2085      */
2086     @SystemApi
2087     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2088     @SuppressLint("ActionValue")
2089     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
2090             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
2091 
2092 
2093     /**
2094      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
2095      * It indicates whether the phone is making an emergency call.
2096      *
2097      * @hide
2098      */
2099     @SystemApi
2100     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
2101             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
2102 
2103     /**
2104      * <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
2105      * <p class="note">.
2106      * This is to pop up a notice to show user that the phone is in emergency callback mode
2107      * and data calls and outgoing sms are blocked.
2108      *
2109      * <p class="note">This is a protected intent that can only be sent by the system.
2110      *
2111      * @hide
2112      */
2113     @SystemApi
2114     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS =
2115             "android.telephony.action.SHOW_NOTICE_ECM_BLOCK_OTHERS";
2116 
2117     /**
2118      * Broadcast Action: The default data subscription has changed in a multi-SIM device.
2119      * This has the following extra values:</p>
2120      * <ul>
2121      *   <li><em>subscription</em> - A int, the current data default subscription.</li>
2122      * </ul>
2123      *
2124      * @hide
2125      */
2126     @SystemApi
2127     @SuppressLint("ActionValue")
2128     public static final String ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED =
2129             "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED";
2130 
2131     /**
2132      * Broadcast Action: The default voice subscription has changed in a mult-SIm device.
2133      * This has the following extra values:</p>
2134      * <ul>
2135      *   <li><em>subscription</em> - A int, the current voice default subscription.</li>
2136      * </ul>
2137      *
2138      * @hide
2139      */
2140     @SystemApi
2141     @SuppressLint("ActionValue")
2142     public static final String ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED =
2143             "android.intent.action.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED";
2144 
2145     /**
2146      * Broadcast Action: This triggers a client initiated OMA-DM session to the OMA server.
2147      * <p class="note">
2148      * Open Mobile Alliance (OMA) Device Management (DM).
2149      *
2150      * This intent is used by the system components to trigger OMA-DM
2151      *
2152      * @hide
2153      */
2154     @SystemApi
2155     @SuppressLint("ActionValue")
2156     public static final String ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE =
2157             "com.android.omadm.service.CONFIGURATION_UPDATE";
2158 
2159     /**
2160      * Activity action: Show setting to reset mobile networks.
2161      *
2162      * <p>On devices with a settings activity to reset mobile networks, the activity should be
2163      * launched without additional permissions.
2164      *
2165      * <p>On some devices, this settings activity may not exist. Callers should ensure that this
2166      * case is appropriately handled.
2167      */
2168     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
2169     public static final String ACTION_RESET_MOBILE_NETWORK_SETTINGS =
2170             "android.telephony.action.RESET_MOBILE_NETWORK_SETTINGS";
2171 
2172     //
2173     //
2174     // Device Info
2175     //
2176     //
2177 
2178     /**
2179      * Returns the software version number for the device, for example,
2180      * the IMEI/SV for GSM phones. Return null if the software version is
2181      * not available.
2182      * <p>
2183      *
2184      * @throws UnsupportedOperationException If the device does not have
2185      *          {@link PackageManager#FEATURE_TELEPHONY}.
2186      */
2187     @RequiresPermission(anyOf = {
2188             android.Manifest.permission.READ_PHONE_STATE,
2189             android.Manifest.permission.READ_BASIC_PHONE_STATE})
2190     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
2191     @Nullable
getDeviceSoftwareVersion()2192     public String getDeviceSoftwareVersion() {
2193         return getDeviceSoftwareVersion(getSlotIndex());
2194     }
2195 
2196     /**
2197      * Returns the software version number for the device, for example,
2198      * the IMEI/SV for GSM phones. Return null if the software version is
2199      * not available.
2200      * <p>
2201      * Requires Permission: READ_PHONE_STATE.
2202      *
2203      * @param slotIndex of which deviceID is returned
2204      *
2205      * @throws UnsupportedOperationException If the device does not have
2206      *          {@link PackageManager#FEATURE_TELEPHONY}.
2207      * @hide
2208      */
2209     @SystemApi
2210     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2211     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
2212     @Nullable
getDeviceSoftwareVersion(int slotIndex)2213     public String getDeviceSoftwareVersion(int slotIndex) {
2214         ITelephony telephony = getITelephony();
2215         if (telephony == null) return null;
2216 
2217         try {
2218             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
2219                     getAttributionTag());
2220         } catch (RemoteException ex) {
2221             return null;
2222         } catch (NullPointerException ex) {
2223             return null;
2224         }
2225     }
2226 
2227     /**
2228      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
2229      * or ESN for CDMA phones. Return null if device ID is not available.
2230      *
2231      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2232      * restrictions, and apps are recommended to use resettable identifiers (see <a
2233      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2234      * method can be invoked if one of the following requirements is met:
2235      * <ul>
2236      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2237      *     is a privileged permission that can only be granted to apps preloaded on the device.
2238      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2239      *     owner of an organization-owned device, or their delegates (see {@link
2240      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2241      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2242      *     active subscription.
2243      *     <li>If the calling app is the default SMS role holder (see {@link
2244      *     RoleManager#isRoleHeld(String)}).
2245      * </ul>
2246      *
2247      * <p>If the calling app does not meet one of these requirements then this method will behave
2248      * as follows:
2249      *
2250      * <ul>
2251      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2252      *     READ_PHONE_STATE permission then null is returned.</li>
2253      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2254      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2255      *     higher, then a SecurityException is thrown.</li>
2256      * </ul>
2257      *
2258      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2259      * MEID for CDMA.
2260      */
2261     @Deprecated
2262     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2263     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()2264     public String getDeviceId() {
2265         try {
2266             ITelephony telephony = getITelephony();
2267             if (telephony == null)
2268                 return null;
2269             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
2270                     mContext.getAttributionTag());
2271         } catch (RemoteException ex) {
2272             return null;
2273         } catch (NullPointerException ex) {
2274             return null;
2275         }
2276     }
2277 
2278     /**
2279      * Returns the unique device ID of a subscription, for example, the IMEI for
2280      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
2281      *
2282      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2283      * restrictions, and apps are recommended to use resettable identifiers (see <a
2284      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2285      * method can be invoked if one of the following requirements is met:
2286      * <ul>
2287      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2288      *     is a privileged permission that can only be granted to apps preloaded on the device.
2289      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2290      *     owner of an organization-owned device, or their delegates (see {@link
2291      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2292      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2293      *     active subscription.
2294      *     <li>If the calling app is the default SMS role holder (see {@link
2295      *     RoleManager#isRoleHeld(String)}).
2296      * </ul>
2297      *
2298      * <p>If the calling app does not meet one of these requirements then this method will behave
2299      * as follows:
2300      *
2301      * <ul>
2302      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2303      *     READ_PHONE_STATE permission then null is returned.</li>
2304      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2305      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2306      *     higher, then a SecurityException is thrown.</li>
2307      * </ul>
2308      *
2309      * @param slotIndex of which deviceID is returned
2310      *
2311      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2312      * MEID for CDMA.
2313      */
2314     @Deprecated
2315     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2316     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)2317     public String getDeviceId(int slotIndex) {
2318         // FIXME this assumes phoneId == slotIndex
2319         try {
2320             IPhoneSubInfo info = getSubscriberInfoService();
2321             if (info == null)
2322                 return null;
2323             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
2324                     mContext.getAttributionTag());
2325         } catch (RemoteException ex) {
2326             return null;
2327         } catch (NullPointerException ex) {
2328             return null;
2329         }
2330     }
2331 
2332     /**
2333      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2334      * available.
2335      *
2336      * See {@link #getImei(int)} for details on the required permissions and behavior
2337      * when the caller does not hold sufficient permissions.
2338      */
2339     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2340     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei()2341     public String getImei() {
2342         return getImei(getSlotIndex());
2343     }
2344 
2345     /**
2346      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2347      * available.
2348      *
2349      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2350      * restrictions, and apps are recommended to use resettable identifiers (see <a
2351      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2352      * method can be invoked if one of the following requirements is met:
2353      * <ul>
2354      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2355      *     is a privileged permission that can only be granted to apps preloaded on the device.
2356      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2357      *     owner of an organization-owned device, or their delegates (see {@link
2358      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2359      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2360      *     active subscription.
2361      *     <li>If the calling app is the default SMS role holder (see {@link
2362      *     RoleManager#isRoleHeld(String)}).
2363      *     <li>If the calling app has been granted the
2364      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
2365      * </ul>
2366      *
2367      * <p>If the calling app does not meet one of these requirements then this method will behave
2368      * as follows:
2369      *
2370      * <ul>
2371      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2372      *     READ_PHONE_STATE permission then null is returned.</li>
2373      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2374      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2375      *     higher, then a SecurityException is thrown.</li>
2376      * </ul>
2377      *
2378      * @param slotIndex of which IMEI is returned
2379      */
2380     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2381     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei(int slotIndex)2382     public String getImei(int slotIndex) {
2383         ITelephony telephony = getITelephony();
2384         if (telephony == null) return null;
2385 
2386         try {
2387             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
2388         } catch (RemoteException ex) {
2389             return null;
2390         } catch (NullPointerException ex) {
2391             return null;
2392         }
2393     }
2394 
2395     /**
2396      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2397      * available.
2398      */
2399     @Nullable
getTypeAllocationCode()2400     public String getTypeAllocationCode() {
2401         return getTypeAllocationCode(getSlotIndex());
2402     }
2403 
2404     /**
2405      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2406      * available.
2407      *
2408      * @param slotIndex of which Type Allocation Code is returned
2409      */
2410     @Nullable
getTypeAllocationCode(int slotIndex)2411     public String getTypeAllocationCode(int slotIndex) {
2412         ITelephony telephony = getITelephony();
2413         if (telephony == null) return null;
2414 
2415         try {
2416             return telephony.getTypeAllocationCodeForSlot(slotIndex);
2417         } catch (RemoteException ex) {
2418             return null;
2419         } catch (NullPointerException ex) {
2420             return null;
2421         }
2422     }
2423 
2424     /**
2425      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2426      *
2427      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2428      * restrictions, and apps are recommended to use resettable identifiers (see <a
2429      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2430      * method can be invoked if one of the following requirements is met:
2431      * <ul>
2432      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2433      *     is a privileged permission that can only be granted to apps preloaded on the device.
2434      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2435      *     owner of an organization-owned device, or their delegates (see {@link
2436      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2437      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2438      *     active subscription.
2439      *     <li>If the calling app is the default SMS role holder (see {@link
2440      *     RoleManager#isRoleHeld(String)}).
2441      * </ul>
2442      *
2443      * <p>If the calling app does not meet one of these requirements then this method will behave
2444      * as follows:
2445      *
2446      * <ul>
2447      *     <li>If the device is running Android 25Q2 or later, then null is returned.</li>
2448      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2449      *     READ_PHONE_STATE permission then null is returned.</li>
2450      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2451      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2452      *     higher, then a SecurityException is thrown.</li>
2453      * </ul>
2454      *
2455      * @deprecated Legacy CDMA is unsupported.
2456      * @throws UnsupportedOperationException If the device is running
2457      *          Android 25Q1 or earlier and does not have
2458      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2459      */
2460     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
2461     @Deprecated
2462     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2463     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2464     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getMeid()2465     public String getMeid() {
2466         if (Flags.cleanupCdma()) return null;
2467         return getMeid(getSlotIndex());
2468     }
2469 
2470     /**
2471      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2472      *
2473      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2474      * restrictions, and apps are recommended to use resettable identifiers (see <a
2475      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2476      * method can be invoked if one of the following requirements is met:
2477      * <ul>
2478      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2479      *     is a privileged permission that can only be granted to apps preloaded on the device.
2480      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2481      *     owner of an organization-owned device, or their delegates (see {@link
2482      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2483      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2484      *     active subscription.
2485      *     <li>If the calling app is the default SMS role holder (see {@link
2486      *     RoleManager#isRoleHeld(String)}).
2487      * </ul>
2488      *
2489      * <p>If the calling app does not meet one of these requirements then this method will behave
2490      * as follows:
2491      *
2492      * <ul>
2493      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2494      *     READ_PHONE_STATE permission then null is returned.</li>
2495      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2496      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2497      *     higher, then a SecurityException is thrown.</li>
2498      * </ul>
2499      *
2500      * @param slotIndex of which MEID is returned
2501      *
2502      * @deprecated Legacy CDMA is unsupported.
2503      * @throws UnsupportedOperationException If the device does not have
2504      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2505      */
2506     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
2507     @Deprecated
2508     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2509     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2510     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getMeid(int slotIndex)2511     public String getMeid(int slotIndex) {
2512         if (Flags.cleanupCdma()) return null;
2513         ITelephony telephony = getITelephony();
2514         if (telephony == null) return null;
2515 
2516         try {
2517             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
2518                     getAttributionTag());
2519             if (TextUtils.isEmpty(meid)) {
2520                 Log.d(TAG, "getMeid: return null because MEID is not available");
2521                 return null;
2522             }
2523             return meid;
2524         } catch (RemoteException ex) {
2525             return null;
2526         } catch (NullPointerException ex) {
2527             return null;
2528         }
2529     }
2530 
2531     /**
2532      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2533      * available.
2534      *
2535      * @deprecated Legacy CDMA is unsupported.
2536      * @throws UnsupportedOperationException If the device does not have
2537      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2538      */
2539     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
2540     @Deprecated
2541     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
2542     @Nullable
getManufacturerCode()2543     public String getManufacturerCode() {
2544         if (Flags.cleanupCdma()) return null;
2545         return getManufacturerCode(getSlotIndex());
2546     }
2547 
2548     /**
2549      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2550      * available.
2551      *
2552      * @param slotIndex of which Type Allocation Code is returned
2553      *
2554      * @deprecated Legacy CDMA is unsupported.
2555      * @throws UnsupportedOperationException If the device does not have
2556      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
2557      */
2558     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
2559     @Deprecated
2560     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
2561     @Nullable
getManufacturerCode(int slotIndex)2562     public String getManufacturerCode(int slotIndex) {
2563         if (Flags.cleanupCdma()) return null;
2564         ITelephony telephony = getITelephony();
2565         if (telephony == null) return null;
2566 
2567         try {
2568             return telephony.getManufacturerCodeForSlot(slotIndex);
2569         } catch (RemoteException ex) {
2570             return null;
2571         } catch (NullPointerException ex) {
2572             return null;
2573         }
2574     }
2575 
2576     /**
2577      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2578      *
2579      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2580      * restrictions, and apps are recommended to use resettable identifiers (see <a
2581      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2582      * method can be invoked if one of the following requirements is met:
2583      * <ul>
2584      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2585      *     is a privileged permission that can only be granted to apps preloaded on the device.
2586      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2587      *     owner of an organization-owned device, or their delegates (see {@link
2588      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2589      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2590      *     <li>If the calling app is the default SMS role holder (see {@link
2591      *     RoleManager#isRoleHeld(String)}).
2592      * </ul>
2593      *
2594      * <p>If the calling app does not meet one of these requirements then this method will behave
2595      * as follows:
2596      *
2597      * <ul>
2598      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2599      *     READ_PHONE_STATE permission then null is returned.</li>
2600      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2601      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2602      *     higher, then a SecurityException is thrown.</li>
2603      * </ul>
2604      *
2605      * @throws UnsupportedOperationException If the device does not have
2606      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
2607      */
2608     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2609     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
2610     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getNai()2611     public String getNai() {
2612         return getNaiBySubscriberId(getSubId());
2613     }
2614 
getNaiBySubscriberId(int subId)2615     private String getNaiBySubscriberId(int subId) {
2616         try {
2617             IPhoneSubInfo info = getSubscriberInfoService();
2618             if (info == null)
2619                 return null;
2620             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2621                     mContext.getAttributionTag());
2622             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2623                 Rlog.v(TAG, "Nai = " + nai);
2624             }
2625             return nai;
2626         } catch (RemoteException ex) {
2627             return null;
2628         } catch (NullPointerException ex) {
2629             return null;
2630         }
2631     }
2632 
2633     /**
2634      * Returns the current location of the device.
2635      *<p>
2636      * If there is only one radio in the device and that radio has an LTE connection,
2637      * this method will return null. The implementation must not to try add LTE
2638      * identifiers into the existing cdma/gsm classes.
2639      *<p>
2640      * @return Current location of the device or null if not available.
2641      *
2642      * @throws UnsupportedOperationException If the device does not have
2643      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
2644      *
2645      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2646      */
2647     @Deprecated
2648     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
2649     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getCellLocation()2650     public CellLocation getCellLocation() {
2651         try {
2652             ITelephony telephony = getITelephony();
2653             if (telephony == null) {
2654                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2655                 return null;
2656             }
2657 
2658             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2659                     mContext.getAttributionTag());
2660             CellLocation cl = cellIdentity.asCellLocation();
2661             if (cl == null || cl.isEmpty()) {
2662                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2663                         + " phone type doesn't match CellLocation type");
2664                 return null;
2665             }
2666 
2667             return cl;
2668         } catch (RemoteException ex) {
2669             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2670             return null;
2671         }
2672     }
2673 
2674     /**
2675      * Returns the neighboring cell information of the device.
2676      *
2677      * @return List of NeighboringCellInfo or null if info unavailable.
2678      *
2679      * @throws UnsupportedOperationException If the device does not have
2680      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
2681      * @removed
2682      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2683      *             from NeighboringCellInfo, including LTE cell information.
2684      */
2685     @Deprecated
2686     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
2687     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNeighboringCellInfo()2688     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2689         try {
2690             ITelephony telephony = getITelephony();
2691             if (telephony == null)
2692                 return null;
2693             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2694                     mContext.getAttributionTag());
2695         } catch (RemoteException ex) {
2696             return null;
2697         } catch (NullPointerException ex) {
2698             return null;
2699         }
2700     }
2701 
2702     /** No phone radio. */
2703     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2704     /** Phone radio is GSM. */
2705     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2706     /**
2707      * Phone radio is CDMA.
2708      *
2709      * @deprecated Legacy CDMA is unsupported.
2710      */
2711     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
2712     @Deprecated
2713     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2714     /** Phone is via SIP. */
2715     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2716 
2717     /**
2718      * Phone is via IMS.
2719      *
2720      * @hide
2721      */
2722     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2723 
2724     /**
2725      * Phone is via Third Party.
2726      *
2727      * @hide
2728      */
2729     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2730 
2731     /**
2732      * Returns the current phone type.
2733      * TODO: This is a last minute change and hence hidden.
2734      *
2735      * @see #PHONE_TYPE_NONE
2736      * @see #PHONE_TYPE_GSM
2737      * @see #PHONE_TYPE_CDMA
2738      * @see #PHONE_TYPE_SIP
2739      *
2740      * @throws UnsupportedOperationException If the device does not have
2741      *          {@link PackageManager#FEATURE_TELEPHONY}.
2742      * {@hide}
2743      */
2744     @SystemApi
2745     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
getCurrentPhoneType()2746     public int getCurrentPhoneType() {
2747         return getCurrentPhoneType(getSubId());
2748     }
2749 
2750     /**
2751      * Returns a constant indicating the device phone type for a subscription.
2752      *
2753      * @see #PHONE_TYPE_NONE
2754      * @see #PHONE_TYPE_GSM
2755      * @see #PHONE_TYPE_CDMA
2756      *
2757      * @param subId for which phone type is returned
2758      *
2759      * @throws UnsupportedOperationException If the device does not have
2760      *          {@link PackageManager#FEATURE_TELEPHONY}.
2761      * @hide
2762      */
2763     @SystemApi
2764     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
getCurrentPhoneType(int subId)2765     public int getCurrentPhoneType(int subId) {
2766         int phoneId;
2767         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2768             // if we don't have any sims, we don't have subscriptions, but we
2769             // still may want to know what type of phone we've got.
2770             phoneId = 0;
2771         } else {
2772             phoneId = SubscriptionManager.getPhoneId(subId);
2773         }
2774 
2775         return getCurrentPhoneTypeForSlot(phoneId);
2776     }
2777 
2778     /**
2779      * See getCurrentPhoneType.
2780      *
2781      * @hide
2782      */
getCurrentPhoneTypeForSlot(int slotIndex)2783     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2784         try{
2785             ITelephony telephony = getITelephony();
2786             if (telephony != null) {
2787                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2788             } else {
2789                 // This can happen when the ITelephony interface is not up yet.
2790                 return getPhoneTypeFromProperty(slotIndex);
2791             }
2792         } catch (RemoteException ex) {
2793             // This shouldn't happen in the normal case, as a backup we
2794             // read from the system property.
2795             return getPhoneTypeFromProperty(slotIndex);
2796         } catch (NullPointerException ex) {
2797             // This shouldn't happen in the normal case, as a backup we
2798             // read from the system property.
2799             return getPhoneTypeFromProperty(slotIndex);
2800         }
2801     }
2802 
2803     /**
2804      * Returns a constant indicating the device phone type.  This
2805      * indicates the type of radio used to transmit voice/data calls.
2806      *
2807      * @see #PHONE_TYPE_NONE
2808      * @see #PHONE_TYPE_GSM
2809      * @see #PHONE_TYPE_CDMA
2810      * @see #PHONE_TYPE_SIP
2811      *
2812      * @throws UnsupportedOperationException If the device does not have
2813      *          {@link PackageManager#FEATURE_TELEPHONY}.
2814      */
2815     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
getPhoneType()2816     public int getPhoneType() {
2817         if (!isDeviceVoiceCapable() && !isDataCapable()) {
2818             return PHONE_TYPE_NONE;
2819         }
2820         return getCurrentPhoneType();
2821     }
2822 
2823     /** {@hide} */
2824     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2825     private int getPhoneTypeFromProperty(int phoneId) {
2826         Integer type = getTelephonyProperty(
2827                 phoneId, TelephonyProperties.current_active_phone(), null);
2828         if (type != null) return type;
2829         return getPhoneTypeFromNetworkType(phoneId);
2830     }
2831 
2832     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2833     private int getPhoneTypeFromNetworkType(int phoneId) {
2834         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2835         // use the system property for default network type.
2836         // This is a fail safe, and can only happen at first boot.
2837         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2838         if (mode != null) {
2839             return TelephonyManager.getPhoneType(mode);
2840         }
2841         return TelephonyManager.PHONE_TYPE_NONE;
2842     }
2843 
2844     /**
2845      * This function returns the type of the phone, depending
2846      * on the network mode.
2847      *
2848      * @param networkMode
2849      * @return Phone Type
2850      *
2851      * @hide
2852      */
2853     @UnsupportedAppUsage
getPhoneType(int networkMode)2854     public static int getPhoneType(int networkMode) {
2855         switch(networkMode) {
2856         case RILConstants.NETWORK_MODE_CDMA:
2857         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2858         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2859             return PhoneConstants.PHONE_TYPE_CDMA;
2860 
2861         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2862         case RILConstants.NETWORK_MODE_GSM_ONLY:
2863         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2864         case RILConstants.NETWORK_MODE_GSM_UMTS:
2865         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2866         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2867         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2868         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2869         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2870         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2871         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2872         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2873         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2874         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2875         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2876         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2877             return PhoneConstants.PHONE_TYPE_GSM;
2878 
2879         // Use CDMA Phone for the global mode including CDMA
2880         case RILConstants.NETWORK_MODE_GLOBAL:
2881         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2882         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2883             return PhoneConstants.PHONE_TYPE_CDMA;
2884 
2885         case RILConstants.NETWORK_MODE_LTE_ONLY:
2886             if (TelephonyProperties.lte_on_cdma_device().orElse(
2887                     PhoneConstants.LTE_ON_CDMA_FALSE) == PhoneConstants.LTE_ON_CDMA_TRUE) {
2888                 return PhoneConstants.PHONE_TYPE_CDMA;
2889             } else {
2890                 return PhoneConstants.PHONE_TYPE_GSM;
2891             }
2892         default:
2893             return PhoneConstants.PHONE_TYPE_GSM;
2894         }
2895     }
2896 
2897     /**
2898      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2899      * @hide
2900      */
2901     @SystemApi
getMaxNumberVerificationTimeoutMillis()2902     public static long getMaxNumberVerificationTimeoutMillis() {
2903         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2904     }
2905 
2906     //
2907     //
2908     // Current Network
2909     //
2910     //
2911 
2912     /**
2913      * Returns the alphabetic name of current registered operator.
2914      * <p>
2915      * Availability: Only when user is registered to a network. Result may be
2916      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2917      * on a CDMA network).
2918      */
2919     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkOperatorName()2920     public String getNetworkOperatorName() {
2921         return getNetworkOperatorName(getSubId());
2922     }
2923 
2924     /**
2925      * Returns the alphabetic name of current registered operator
2926      * for a particular subscription.
2927      * <p>
2928      * Availability: Only when user is registered to a network. Result may be
2929      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2930      * on a CDMA network).
2931      * @param subId
2932      * @hide
2933      */
2934     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2935     public String getNetworkOperatorName(int subId) {
2936         int phoneId = SubscriptionManager.getPhoneId(subId);
2937         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2938     }
2939 
2940     /**
2941      * Returns the numeric name (MCC+MNC) of current registered operator.
2942      * <p>
2943      * Availability: Only when user is registered to a network. Result may be
2944      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2945      * on a CDMA network).
2946      */
2947     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkOperator()2948     public String getNetworkOperator() {
2949         return getNetworkOperatorForPhone(getPhoneId());
2950     }
2951 
2952     /**
2953      * Returns the numeric name (MCC+MNC) of current registered operator
2954      * for a particular subscription.
2955      * <p>
2956      * Availability: Only when user is registered to a network. Result may be
2957      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2958      * on a CDMA network).
2959      *
2960      * @param subId
2961      * @hide
2962      */
2963     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2964     public String getNetworkOperator(int subId) {
2965         int phoneId = SubscriptionManager.getPhoneId(subId);
2966         return getNetworkOperatorForPhone(phoneId);
2967      }
2968 
2969     /**
2970      * Returns the numeric name (MCC+MNC) of current registered operator
2971      * for a particular subscription.
2972      * <p>
2973      * Availability: Only when user is registered to a network. Result may be
2974      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2975      * on a CDMA network).
2976      *
2977      * @param phoneId
2978      * @hide
2979      **/
2980     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2981     public String getNetworkOperatorForPhone(int phoneId) {
2982         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2983     }
2984 
2985 
2986     /**
2987      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2988      * network specifier is used by {@link
2989      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2990      * android.net.NetworkRequest} that connects through the subscription.
2991      *
2992      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2993      * @see #createForSubscriptionId(int)
2994      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2995      */
2996     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getNetworkSpecifier()2997     public String getNetworkSpecifier() {
2998         return String.valueOf(getSubId());
2999     }
3000 
3001     /**
3002      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
3003      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
3004      * default values.
3005      *
3006      * <p>This method may take several seconds to complete, so it should only be called from a
3007      * worker thread.
3008      *
3009      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3010      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3011      *
3012      * @see CarrierConfigManager#getConfigForSubId(int)
3013      * @see #createForSubscriptionId(int)
3014      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
3015      *
3016      * @throws UnsupportedOperationException If the device does not have
3017      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3018      */
3019     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3020     @WorkerThread
3021     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3022     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierConfig()3023     public PersistableBundle getCarrierConfig() {
3024         CarrierConfigManager carrierConfigManager = mContext
3025                 .getSystemService(CarrierConfigManager.class);
3026         return carrierConfigManager.getConfigForSubId(getSubId());
3027     }
3028 
3029     /**
3030      * Returns true if the device is considered roaming on the current
3031      * network, for GSM purposes.
3032      * <p>
3033      * Availability: Only when user registered to a network.
3034      */
3035     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isNetworkRoaming()3036     public boolean isNetworkRoaming() {
3037         return isNetworkRoaming(getSubId());
3038     }
3039 
3040     /**
3041      * Returns true if the device is considered roaming on the current
3042      * network for a subscription.
3043      * <p>
3044      * Availability: Only when user registered to a network.
3045      *
3046      * @param subId
3047      * @hide
3048      */
3049     @UnsupportedAppUsage
isNetworkRoaming(int subId)3050     public boolean isNetworkRoaming(int subId) {
3051         int phoneId = SubscriptionManager.getPhoneId(subId);
3052         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
3053     }
3054 
3055     /**
3056      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
3057      * the current registered operator or the cell nearby, if available.
3058      *
3059      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
3060      * if on a CDMA network).
3061      * <p>
3062      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
3063      * available.
3064      *
3065      * @throws UnsupportedOperationException If the device does not have
3066      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3067      */
3068     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkCountryIso()3069     public String getNetworkCountryIso() {
3070         return getNetworkCountryIso(getSlotIndex());
3071     }
3072 
3073     /**
3074      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
3075      * the current registered operator or the cell nearby, if available. This is same as
3076      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
3077      * accessing network country info from the SIM slot that does not have SIM inserted.
3078      *
3079      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
3080      * if on a CDMA network).
3081      * <p>
3082      *
3083      * @param slotIndex the SIM slot index to get network country ISO.
3084      *
3085      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
3086      * available.
3087      *
3088      * @throws IllegalArgumentException when the slotIndex is invalid.
3089      * @throws UnsupportedOperationException If the device does not have
3090      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3091      *
3092      */
3093     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
3094     @NonNull
getNetworkCountryIso(int slotIndex)3095     public String getNetworkCountryIso(int slotIndex) {
3096         try {
3097             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
3098                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
3099                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
3100             }
3101 
3102             ITelephony telephony = getITelephony();
3103             if (telephony == null) return "";
3104             return telephony.getNetworkCountryIsoForPhone(slotIndex);
3105         } catch (RemoteException ex) {
3106             return "";
3107         }
3108     }
3109 
3110     /**
3111      * @hide
3112      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
3113      */
3114     @Deprecated
3115     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
3116             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)3117     public String getNetworkCountryIsoForPhone(int phoneId) {
3118         return getNetworkCountryIso(phoneId);
3119     }
3120 
3121     /*
3122      * When adding a network type to the list below, make sure to add the correct icon to
3123      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
3124      * Do not add negative types.
3125      */
3126     /** Network type is unknown */
3127     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
3128     /** Current network is GPRS */
3129     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
3130     /** Current network is EDGE */
3131     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
3132     /** Current network is UMTS */
3133     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
3134     /**
3135      * Current network is CDMA: Either IS95A or IS95B
3136      * @deprecated Legacy CDMA is unsupported.
3137      */
3138     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
3139     @Deprecated
3140     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
3141     /**
3142      * Current network is EVDO revision 0
3143      * @deprecated Legacy CDMA is unsupported.
3144      */
3145     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
3146     @Deprecated
3147     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
3148     /**
3149      * Current network is EVDO revision A
3150      * @deprecated Legacy CDMA is unsupported.
3151      */
3152     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
3153     @Deprecated
3154     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
3155     /**
3156      * Current network is 1xRTT
3157      * @deprecated Legacy CDMA is unsupported.
3158      */
3159     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
3160     @Deprecated
3161     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
3162     /** Current network is HSDPA */
3163     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
3164     /** Current network is HSUPA */
3165     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
3166     /** Current network is HSPA */
3167     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
3168     /**
3169      * Current network is iDen
3170      * @deprecated Legacy network type no longer being used starting in Android U.
3171      */
3172     @Deprecated
3173     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
3174     /**
3175      * Current network is EVDO revision B
3176      * @deprecated Legacy CDMA is unsupported.
3177      */
3178     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
3179     @Deprecated
3180     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
3181     /** Current network is LTE */
3182     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
3183     /**
3184      * Current network is eHRPD
3185      * @deprecated Legacy CDMA is unsupported.
3186      */
3187     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
3188     @Deprecated
3189     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
3190     /** Current network is HSPA+ */
3191     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
3192     /** Current network is GSM */
3193     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
3194     /** Current network is TD_SCDMA */
3195     public static final int NETWORK_TYPE_TD_SCDMA =
3196             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
3197     /** Current network is IWLAN */
3198     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
3199     /** Current network is LTE_CA {@hide} */
3200     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3201     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
3202     /**
3203      * Current network is NR (New Radio) 5G.
3204      * This will only be returned for 5G SA.
3205      * For 5G NSA, the network type will be {@link #NETWORK_TYPE_LTE}.
3206      */
3207     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
3208 
3209     private static final @NetworkType int[] NETWORK_TYPES = {
3210             NETWORK_TYPE_GPRS,
3211             NETWORK_TYPE_EDGE,
3212             NETWORK_TYPE_UMTS,
3213             NETWORK_TYPE_CDMA,
3214             NETWORK_TYPE_EVDO_0,
3215             NETWORK_TYPE_EVDO_A,
3216             NETWORK_TYPE_1xRTT,
3217             NETWORK_TYPE_HSDPA,
3218             NETWORK_TYPE_HSUPA,
3219             NETWORK_TYPE_HSPA,
3220             NETWORK_TYPE_IDEN,
3221             NETWORK_TYPE_EVDO_B,
3222             NETWORK_TYPE_LTE,
3223             NETWORK_TYPE_EHRPD,
3224             NETWORK_TYPE_HSPAP,
3225             NETWORK_TYPE_GSM,
3226             NETWORK_TYPE_TD_SCDMA,
3227             NETWORK_TYPE_IWLAN,
3228             NETWORK_TYPE_LTE_CA,
3229             NETWORK_TYPE_NR
3230     };
3231 
3232     /**
3233      * Returns an array of all valid network types.
3234      *
3235      * @return An integer array containing all valid network types in no particular order.
3236      *
3237      * @hide
3238      */
3239     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getAllNetworkTypes()3240     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
3241         return NETWORK_TYPES.clone();
3242     }
3243 
3244     /**
3245      * Return the current data network type.
3246      *
3247      * @deprecated use {@link #getDataNetworkType()}
3248      * @return the NETWORK_TYPE_xxxx for current data connection.
3249      *
3250      * @throws UnsupportedOperationException If the device does not have
3251      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3252      */
3253     @Deprecated
3254     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3255     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkType()3256     public @NetworkType int getNetworkType() {
3257         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3258     }
3259 
3260     /**
3261      * Returns a constant indicating the radio technology (network type)
3262      * currently in use on the device for a subscription.
3263      * @return the network type
3264      *
3265      * @param subId for which network type is returned
3266      *
3267      * @see #NETWORK_TYPE_UNKNOWN
3268      * @see #NETWORK_TYPE_GPRS
3269      * @see #NETWORK_TYPE_EDGE
3270      * @see #NETWORK_TYPE_UMTS
3271      * @see #NETWORK_TYPE_HSDPA
3272      * @see #NETWORK_TYPE_HSUPA
3273      * @see #NETWORK_TYPE_HSPA
3274      * @see #NETWORK_TYPE_CDMA
3275      * @see #NETWORK_TYPE_EVDO_0
3276      * @see #NETWORK_TYPE_EVDO_A
3277      * @see #NETWORK_TYPE_EVDO_B
3278      * @see #NETWORK_TYPE_1xRTT
3279      * @see #NETWORK_TYPE_IDEN
3280      * @see #NETWORK_TYPE_LTE
3281      * @see #NETWORK_TYPE_EHRPD
3282      * @see #NETWORK_TYPE_HSPAP
3283      * @see #NETWORK_TYPE_NR
3284      *
3285      * @hide
3286      */
3287     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3288     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)3289     public int getNetworkType(int subId) {
3290         try {
3291             ITelephony telephony = getITelephony();
3292             if (telephony != null) {
3293                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
3294                         getAttributionTag());
3295             } else {
3296                 // This can happen when the ITelephony interface is not up yet.
3297                 return NETWORK_TYPE_UNKNOWN;
3298             }
3299         } catch (RemoteException ex) {
3300             // This shouldn't happen in the normal case
3301             return NETWORK_TYPE_UNKNOWN;
3302         } catch (NullPointerException ex) {
3303             // This could happen before phone restarts due to crashing
3304             return NETWORK_TYPE_UNKNOWN;
3305         }
3306     }
3307 
3308     /**
3309      * Returns a constant indicating the radio technology (network type)
3310      * currently in use on the device for data transmission.
3311      *
3312      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
3313      * subId. Otherwise, applies to {@link SubscriptionManager#getActiveDataSubscriptionId()}.
3314      *
3315      * Note: Before {@link SubscriptionManager#getActiveDataSubscriptionId()} was introduced in API
3316      * level 30, it was applied to {@link SubscriptionManager#getDefaultDataSubscriptionId()} which
3317      * may be different now from {@link SubscriptionManager#getActiveDataSubscriptionId()}, e.g.
3318      * when opportunistic network is providing cellular internet connection to the user.
3319      *
3320      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3321      * or {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
3322      * READ_BASIC_PHONE_STATE} or that the calling app has carrier privileges
3323      * (see {@link #hasCarrierPrivileges}).
3324      *
3325      * @return the network type
3326      *
3327      * @see #NETWORK_TYPE_UNKNOWN
3328      * @see #NETWORK_TYPE_GPRS
3329      * @see #NETWORK_TYPE_EDGE
3330      * @see #NETWORK_TYPE_UMTS
3331      * @see #NETWORK_TYPE_HSDPA
3332      * @see #NETWORK_TYPE_HSUPA
3333      * @see #NETWORK_TYPE_HSPA
3334      * @see #NETWORK_TYPE_CDMA
3335      * @see #NETWORK_TYPE_EVDO_0
3336      * @see #NETWORK_TYPE_EVDO_A
3337      * @see #NETWORK_TYPE_EVDO_B
3338      * @see #NETWORK_TYPE_1xRTT
3339      * @see #NETWORK_TYPE_IDEN
3340      * @see #NETWORK_TYPE_LTE
3341      * @see #NETWORK_TYPE_EHRPD
3342      * @see #NETWORK_TYPE_HSPAP
3343      * @see #NETWORK_TYPE_NR
3344      *
3345      * @throws UnsupportedOperationException If the device does not have
3346      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
3347      */
3348     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3349     @RequiresPermission(anyOf = {
3350             android.Manifest.permission.READ_PHONE_STATE,
3351             android.Manifest.permission.READ_BASIC_PHONE_STATE})
3352     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getDataNetworkType()3353     public @NetworkType int getDataNetworkType() {
3354         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
3355     }
3356 
3357     /**
3358      * Returns a constant indicating the radio technology (network type)
3359      * currently in use on the device for data transmission for a subscription
3360      * @return the network type
3361      *
3362      * @param subId for which network type is returned
3363      * @hide
3364      */
3365     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3366     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)3367     public int getDataNetworkType(int subId) {
3368         try{
3369             ITelephony telephony = getITelephony();
3370             if (telephony != null) {
3371                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
3372                         getAttributionTag());
3373             } else {
3374                 Log.e(TAG, "getDataNetworkType: ITelephony interface is not up yet");
3375                 return NETWORK_TYPE_UNKNOWN;
3376             }
3377         } catch (RemoteException // Shouldn't happen in the normal case
3378                 | NullPointerException ex // Could happen before phone restarts due to crashing
3379         ) {
3380             Log.e(TAG, "getDataNetworkType: " + ex.getMessage());
3381             return NETWORK_TYPE_UNKNOWN;
3382         }
3383     }
3384 
3385     /**
3386      * Returns the NETWORK_TYPE_xxxx for voice
3387      *
3388      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3389      * or {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
3390      * READ_BASIC_PHONE_STATE} or that the calling app has carrier privileges
3391      * (see {@link #hasCarrierPrivileges}).
3392      *
3393      * @throws UnsupportedOperationException If the device does not have
3394      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
3395      */
3396     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3397     @RequiresPermission(anyOf = {
3398             android.Manifest.permission.READ_PHONE_STATE,
3399             android.Manifest.permission.READ_BASIC_PHONE_STATE})
3400     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceNetworkType()3401     public @NetworkType int getVoiceNetworkType() {
3402         return getVoiceNetworkType(getSubId());
3403     }
3404 
3405     /**
3406      * Returns the NETWORK_TYPE_xxxx for voice for a subId
3407      * @hide
3408      */
3409     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3410     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)3411     public int getVoiceNetworkType(int subId) {
3412         try{
3413             ITelephony telephony = getITelephony();
3414             if (telephony != null) {
3415                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
3416                         getAttributionTag());
3417             } else {
3418                 // This can happen when the ITelephony interface is not up yet.
3419                 return NETWORK_TYPE_UNKNOWN;
3420             }
3421         } catch(RemoteException ex) {
3422             // This shouldn't happen in the normal case
3423             return NETWORK_TYPE_UNKNOWN;
3424         } catch (NullPointerException ex) {
3425             // This could happen before phone restarts due to crashing
3426             return NETWORK_TYPE_UNKNOWN;
3427         }
3428     }
3429 
3430     /**
3431      * Returns a string representation of the radio technology (network type)
3432      * currently in use on the device.
3433      * @return the name of the radio technology
3434      *
3435      * @hide pending API council review
3436      */
3437     @UnsupportedAppUsage
getNetworkTypeName()3438     public String getNetworkTypeName() {
3439         return getNetworkTypeName(getNetworkType());
3440     }
3441 
3442     /**
3443      * Returns a string representation of the radio technology (network type)
3444      * currently in use on the device.
3445      * @param subId for which network type is returned
3446      * @return the name of the radio technology
3447      *
3448      */
3449     /** {@hide} */
3450     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)3451     public static String getNetworkTypeName(@NetworkType int type) {
3452         switch (type) {
3453             case NETWORK_TYPE_GPRS:
3454                 return "GPRS";
3455             case NETWORK_TYPE_EDGE:
3456                 return "EDGE";
3457             case NETWORK_TYPE_UMTS:
3458                 return "UMTS";
3459             case NETWORK_TYPE_HSDPA:
3460                 return "HSDPA";
3461             case NETWORK_TYPE_HSUPA:
3462                 return "HSUPA";
3463             case NETWORK_TYPE_HSPA:
3464                 return "HSPA";
3465             case NETWORK_TYPE_CDMA:
3466                 return "CDMA";
3467             case NETWORK_TYPE_EVDO_0:
3468                 return "CDMA - EvDo rev. 0";
3469             case NETWORK_TYPE_EVDO_A:
3470                 return "CDMA - EvDo rev. A";
3471             case NETWORK_TYPE_EVDO_B:
3472                 return "CDMA - EvDo rev. B";
3473             case NETWORK_TYPE_1xRTT:
3474                 return "CDMA - 1xRTT";
3475             case NETWORK_TYPE_LTE:
3476                 return "LTE";
3477             case NETWORK_TYPE_EHRPD:
3478                 return "CDMA - eHRPD";
3479             case NETWORK_TYPE_IDEN:
3480                 return "iDEN";
3481             case NETWORK_TYPE_HSPAP:
3482                 return "HSPA+";
3483             case NETWORK_TYPE_GSM:
3484                 return "GSM";
3485             case NETWORK_TYPE_TD_SCDMA:
3486                 return "TD_SCDMA";
3487             case NETWORK_TYPE_IWLAN:
3488                 return "IWLAN";
3489             case NETWORK_TYPE_LTE_CA:
3490                 return "LTE_CA";
3491             case NETWORK_TYPE_NR:
3492                 return "NR";
3493             case NETWORK_TYPE_UNKNOWN:
3494                 return "UNKNOWN";
3495             default:
3496                 return "UNKNOWN(" + type + ")";
3497         }
3498     }
3499 
3500     /**
3501      * Returns the bitmask for a given technology (network type)
3502      * @param networkType for which bitmask is returned
3503      * @return the network type bitmask
3504      * {@hide}
3505      */
getBitMaskForNetworkType(@etworkType int networkType)3506     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
3507         switch(networkType) {
3508             case NETWORK_TYPE_GSM:
3509                 return NETWORK_TYPE_BITMASK_GSM;
3510             case NETWORK_TYPE_GPRS:
3511                 return NETWORK_TYPE_BITMASK_GPRS;
3512             case NETWORK_TYPE_EDGE:
3513                 return NETWORK_TYPE_BITMASK_EDGE;
3514             case NETWORK_TYPE_CDMA:
3515                 return NETWORK_TYPE_BITMASK_CDMA;
3516             case NETWORK_TYPE_1xRTT:
3517                 return NETWORK_TYPE_BITMASK_1xRTT;
3518             case NETWORK_TYPE_EVDO_0:
3519                 return NETWORK_TYPE_BITMASK_EVDO_0;
3520             case NETWORK_TYPE_EVDO_A:
3521                 return NETWORK_TYPE_BITMASK_EVDO_A;
3522             case NETWORK_TYPE_EVDO_B:
3523                 return NETWORK_TYPE_BITMASK_EVDO_B;
3524             case NETWORK_TYPE_EHRPD:
3525                 return NETWORK_TYPE_BITMASK_EHRPD;
3526             case NETWORK_TYPE_HSUPA:
3527                 return NETWORK_TYPE_BITMASK_HSUPA;
3528             case NETWORK_TYPE_HSDPA:
3529                 return NETWORK_TYPE_BITMASK_HSDPA;
3530             case NETWORK_TYPE_HSPA:
3531                 return NETWORK_TYPE_BITMASK_HSPA;
3532             case NETWORK_TYPE_HSPAP:
3533                 return NETWORK_TYPE_BITMASK_HSPAP;
3534             case NETWORK_TYPE_UMTS:
3535                 return NETWORK_TYPE_BITMASK_UMTS;
3536             case NETWORK_TYPE_TD_SCDMA:
3537                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
3538             case NETWORK_TYPE_LTE:
3539             case NETWORK_TYPE_LTE_CA:
3540                 return NETWORK_TYPE_BITMASK_LTE;
3541             case NETWORK_TYPE_NR:
3542                 return NETWORK_TYPE_BITMASK_NR;
3543             case NETWORK_TYPE_IWLAN:
3544                 return NETWORK_TYPE_BITMASK_IWLAN;
3545             case NETWORK_TYPE_IDEN:
3546                 return NETWORK_TYPE_BITMASK_IDEN;
3547             default:
3548                 return NETWORK_TYPE_BITMASK_UNKNOWN;
3549         }
3550     }
3551 
3552     //
3553     //
3554     // SIM Card
3555     //
3556     //
3557 
3558     /** @hide */
3559     @IntDef(prefix = {"SIM_STATE_"},
3560             value = {
3561                     SIM_STATE_UNKNOWN,
3562                     SIM_STATE_ABSENT,
3563                     SIM_STATE_PIN_REQUIRED,
3564                     SIM_STATE_PUK_REQUIRED,
3565                     SIM_STATE_NETWORK_LOCKED,
3566                     SIM_STATE_READY,
3567                     SIM_STATE_NOT_READY,
3568                     SIM_STATE_PERM_DISABLED,
3569                     SIM_STATE_CARD_IO_ERROR,
3570                     SIM_STATE_CARD_RESTRICTED,
3571                     SIM_STATE_LOADED,
3572                     SIM_STATE_PRESENT,
3573             })
3574     @Retention(RetentionPolicy.SOURCE)
3575     public @interface SimState {}
3576 
3577     /**
3578      * SIM card state: Unknown. Signifies that the SIM is in transition
3579      * between states. For example, when the user inputs the SIM pin
3580      * under PIN_REQUIRED state, a query for sim status returns
3581      * this state before turning to SIM_STATE_READY.
3582      *
3583      * These are the ordinal value of IccCardConstants.State.
3584      */
3585 
3586     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
3587     /** SIM card state: no SIM card is available in the device */
3588     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3589     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3590     public static final int SIM_STATE_PIN_REQUIRED =
3591             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3592     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3593     public static final int SIM_STATE_PUK_REQUIRED =
3594             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3595     /** SIM card state: Locked: requires a network PIN to unlock */
3596     public static final int SIM_STATE_NETWORK_LOCKED =
3597             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3598     /** SIM card state: Ready */
3599     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3600     /** SIM card state: SIM Card is NOT READY */
3601     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3602     /** SIM card state: SIM Card Error, permanently disabled */
3603     public static final int SIM_STATE_PERM_DISABLED =
3604             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3605     /** SIM card state: SIM Card Error, present but faulty */
3606     public static final int SIM_STATE_CARD_IO_ERROR =
3607             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3608     /** SIM card state: SIM Card restricted, present but not usable due to
3609      * carrier restrictions.
3610      */
3611     public static final int SIM_STATE_CARD_RESTRICTED =
3612             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3613     /**
3614      * SIM card state: Loaded: SIM card applications have been loaded
3615      * @hide
3616      */
3617     @SystemApi
3618     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3619     /**
3620      * SIM card state: SIM Card is present
3621      * @hide
3622      */
3623     @SystemApi
3624     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3625 
3626     /**
3627      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3628      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3629      *
3630      * @hide
3631      */
3632     @SystemApi
3633     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3634 
3635     /**
3636      * Broadcast Action: The sim card state has changed.
3637      * The intent will have the following extra values:</p>
3638      * <dl>
3639      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3640      *   <dd>The sim card state. One of:
3641      *     <dl>
3642      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3643      *       <dd>SIM card not found</dd>
3644      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3645      *       <dd>SIM card IO error</dd>
3646      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3647      *       <dd>SIM card is restricted</dd>
3648      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3649      *       <dd>SIM card is present</dd>
3650      *     </dl>
3651      *   </dd>
3652      * </dl>
3653      *
3654      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3655      *
3656      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3657      *
3658      * <p class="note">This is a protected intent that can only be sent by the system.
3659      * @hide
3660      */
3661     @SystemApi
3662     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3663     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3664             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3665 
3666     /**
3667      * Broadcast Action: The sim application state has changed.
3668      * The intent will have the following extra values:</p>
3669      * <dl>
3670      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3671      *   <dd>The sim application state. One of:
3672      *     <dl>
3673      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3674      *       <dd>SIM card applications not ready</dd>
3675      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3676      *       <dd>SIM card PIN locked</dd>
3677      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3678      *       <dd>SIM card PUK locked</dd>
3679      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3680      *       <dd>SIM card network locked</dd>
3681      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3682      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3683      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3684      *       <dd>SIM card data loaded</dd>
3685      *     </dl>
3686      *   </dd>
3687      * </dl>
3688      *
3689      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3690      *
3691      * <p class="note">The current state can also be queried using
3692      * {@link #getSimApplicationState()}.
3693      *
3694      * <p class="note">This is a protected intent that can only be sent by the system.
3695      * @hide
3696      */
3697     @SystemApi
3698     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3699     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3700             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3701 
3702     /**
3703      * Broadcast Action: Status of the SIM slots on the device has changed.
3704      *
3705      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3706      *
3707      * <p class="note">The status can be queried using
3708      * {@link #getUiccSlotsInfo()}
3709      *
3710      * <p class="note">This is a protected intent that can only be sent by the system.
3711      * @hide
3712      */
3713     @SystemApi
3714     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3715     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3716             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3717 
3718     /**
3719      * Broadcast Action: A debug code has been entered in the dialer.
3720      * <p>
3721      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3722      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3723      * (see {@link #hasCarrierPrivileges}).
3724      * <p>
3725      * These "secret codes" are used to activate developer menus by dialing certain codes.
3726      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3727      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3728      * receiver would be woken up even if it is not currently running.
3729      * <p>
3730      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3731      * in the next Android version.
3732      * Before that both of these two actions will be broadcast.
3733      */
3734     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3735     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3736 
3737     /**
3738      * This API is used to check if there is an ICC card present in the device.
3739      *
3740      * An ICC card is a smart card that contains a subscriber identity module (SIM) and is used
3741      * to identify and authenticate users to a mobile network.
3742      *
3743      * Note: In case of embedded SIM there is an ICC card always present irrespective
3744      * of whether an active SIM profile is present or not so this API would always return true.
3745      *
3746      * @return true if a ICC card is present.
3747      *
3748      * @throws UnsupportedOperationException If the device does not have
3749      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3750      */
3751     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
hasIccCard()3752     public boolean hasIccCard() {
3753         return hasIccCard(getSlotIndex());
3754     }
3755 
3756     /**
3757      * @return true if a ICC card is present for a subscription
3758      *
3759      * @param slotIndex for which icc card presence is checked
3760      */
3761     /** {@hide} */
3762     // FIXME Input argument slotIndex should be of type int
3763     @UnsupportedAppUsage
hasIccCard(int slotIndex)3764     public boolean hasIccCard(int slotIndex) {
3765 
3766         try {
3767             ITelephony telephony = getITelephony();
3768             if (telephony == null)
3769                 return false;
3770             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3771         } catch (RemoteException ex) {
3772             // Assume no ICC card if remote exception which shouldn't happen
3773             return false;
3774         } catch (NullPointerException ex) {
3775             // This could happen before phone restarts due to crashing
3776             return false;
3777         }
3778     }
3779 
3780     /**
3781      * Returns a constant indicating the state of the default SIM card.
3782      *
3783      * @see #SIM_STATE_UNKNOWN
3784      * @see #SIM_STATE_ABSENT
3785      * @see #SIM_STATE_PIN_REQUIRED
3786      * @see #SIM_STATE_PUK_REQUIRED
3787      * @see #SIM_STATE_NETWORK_LOCKED
3788      * @see #SIM_STATE_READY
3789      * @see #SIM_STATE_NOT_READY
3790      * @see #SIM_STATE_PERM_DISABLED
3791      * @see #SIM_STATE_CARD_IO_ERROR
3792      * @see #SIM_STATE_CARD_RESTRICTED
3793      *
3794      * @throws UnsupportedOperationException If the device does not have
3795      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3796      */
3797     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimState()3798     public @SimState int getSimState() {
3799         int simState = getSimStateIncludingLoaded();
3800         if (simState == SIM_STATE_LOADED) {
3801             simState = SIM_STATE_READY;
3802         }
3803         return simState;
3804     }
3805 
getSimStateIncludingLoaded()3806     private @SimState int getSimStateIncludingLoaded() {
3807         int slotIndex = getSlotIndex();
3808         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3809         // sim state
3810         if (slotIndex < 0) {
3811             // query for all slots and return absent if all sim states are absent, otherwise
3812             // return unknown
3813             for (int i = 0; i < getPhoneCount(); i++) {
3814                 int simState = getSimState(i);
3815                 if (simState != SIM_STATE_ABSENT) {
3816                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3817                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3818                     return SIM_STATE_UNKNOWN;
3819                 }
3820             }
3821             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3822                     "state as absent");
3823             return SIM_STATE_ABSENT;
3824         }
3825         return getSimStateForSlotIndex(slotIndex);
3826     }
3827 
3828     /**
3829      * Returns a constant indicating the state of the default SIM card.
3830      *
3831      * @see #SIM_STATE_UNKNOWN
3832      * @see #SIM_STATE_ABSENT
3833      * @see #SIM_STATE_CARD_IO_ERROR
3834      * @see #SIM_STATE_CARD_RESTRICTED
3835      * @see #SIM_STATE_PRESENT
3836      *
3837      * @throws UnsupportedOperationException If the device does not have
3838      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3839      * @hide
3840      */
3841     @SystemApi
3842     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCardState()3843     public @SimState int getSimCardState() {
3844         int simState = getSimState();
3845         return getSimCardStateFromSimState(simState);
3846     }
3847 
3848     /**
3849      * Returns a constant indicating the state of the device SIM card in a physical slot.
3850      *
3851      * @param physicalSlotIndex physical slot index
3852      *
3853      * @see #SIM_STATE_UNKNOWN
3854      * @see #SIM_STATE_ABSENT
3855      * @see #SIM_STATE_CARD_IO_ERROR
3856      * @see #SIM_STATE_CARD_RESTRICTED
3857      * @see #SIM_STATE_PRESENT
3858      *
3859      * @throws UnsupportedOperationException If the device does not have
3860      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3861      * @hide
3862      * @deprecated instead use {@link #getSimCardState(int, int)}
3863      */
3864     @SystemApi
3865     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3866     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
3867     @Deprecated
getSimCardState(int physicalSlotIndex)3868     public @SimState int getSimCardState(int physicalSlotIndex) {
3869         int activePort = getFirstActivePortIndex(physicalSlotIndex);
3870         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex, activePort));
3871         return getSimCardStateFromSimState(simState);
3872     }
3873 
3874     /**
3875      * Returns a constant indicating the state of the device SIM card in a physical slot and
3876      * port index.
3877      *
3878      * @param physicalSlotIndex physical slot index
3879      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3880      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3881      *
3882      * @see #SIM_STATE_UNKNOWN
3883      * @see #SIM_STATE_ABSENT
3884      * @see #SIM_STATE_CARD_IO_ERROR
3885      * @see #SIM_STATE_CARD_RESTRICTED
3886      * @see #SIM_STATE_PRESENT
3887      *
3888      * @throws UnsupportedOperationException If the device does not have
3889      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3890      * @hide
3891      */
3892     @SystemApi
3893     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3894     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCardState(int physicalSlotIndex, int portIndex)3895     public @SimState int getSimCardState(int physicalSlotIndex, int portIndex) {
3896         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex, portIndex));
3897         return getSimCardStateFromSimState(simState);
3898     }
3899     /**
3900      * Converts SIM state to SIM card state.
3901      * @param simState
3902      * @return SIM card state
3903      */
getSimCardStateFromSimState(int simState)3904     private @SimState int getSimCardStateFromSimState(int simState) {
3905         switch (simState) {
3906             case SIM_STATE_UNKNOWN:
3907             case SIM_STATE_ABSENT:
3908             case SIM_STATE_CARD_IO_ERROR:
3909             case SIM_STATE_CARD_RESTRICTED:
3910                 return simState;
3911             default:
3912                 return SIM_STATE_PRESENT;
3913         }
3914     }
3915 
3916     /**
3917      * Converts a physical slot index to logical slot index.
3918      * @param physicalSlotIndex physical slot index
3919      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3920      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3921      * @return logical slot index
3922      */
getLogicalSlotIndex(int physicalSlotIndex, int portIndex)3923     private int getLogicalSlotIndex(int physicalSlotIndex, int portIndex) {
3924         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3925         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length
3926                 && slotInfos[physicalSlotIndex] != null) {
3927             for (UiccPortInfo portInfo : slotInfos[physicalSlotIndex].getPorts()) {
3928                 if (portInfo.getPortIndex() == portIndex) {
3929                     return portInfo.getLogicalSlotIndex();
3930                 }
3931             }
3932         }
3933 
3934         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3935     }
3936 
3937     /**
3938      * Returns a constant indicating the state of the card applications on the default SIM card.
3939      *
3940      * @see #SIM_STATE_UNKNOWN
3941      * @see #SIM_STATE_PIN_REQUIRED
3942      * @see #SIM_STATE_PUK_REQUIRED
3943      * @see #SIM_STATE_NETWORK_LOCKED
3944      * @see #SIM_STATE_NOT_READY
3945      * @see #SIM_STATE_PERM_DISABLED
3946      * @see #SIM_STATE_LOADED
3947      *
3948      * @throws UnsupportedOperationException If the device does not have
3949      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3950      * @hide
3951      */
3952     @SystemApi
3953     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimApplicationState()3954     public @SimState int getSimApplicationState() {
3955         int simState = getSimStateIncludingLoaded();
3956         return getSimApplicationStateFromSimState(simState);
3957     }
3958 
3959     /**
3960      * Returns a constant indicating the state of the card applications on the device SIM card in
3961      * a physical slot.
3962      *
3963      * @param physicalSlotIndex physical slot index
3964      *
3965      * @see #SIM_STATE_UNKNOWN
3966      * @see #SIM_STATE_PIN_REQUIRED
3967      * @see #SIM_STATE_PUK_REQUIRED
3968      * @see #SIM_STATE_NETWORK_LOCKED
3969      * @see #SIM_STATE_NOT_READY
3970      * @see #SIM_STATE_PERM_DISABLED
3971      * @see #SIM_STATE_LOADED
3972      *
3973      * @throws UnsupportedOperationException If the device does not have
3974      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
3975      * @hide
3976      * @deprecated instead use {@link #getSimApplicationState(int, int)}
3977      */
3978     @SystemApi
3979     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3980     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
3981     @Deprecated
getSimApplicationState(int physicalSlotIndex)3982     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3983         int activePort = getFirstActivePortIndex(physicalSlotIndex);
3984         int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, activePort));
3985         return getSimApplicationStateFromSimState(simState);
3986     }
3987 
3988     /**
3989      * Returns a constant indicating the state of the card applications on the device SIM card in
3990      * a physical slot.
3991      *
3992      * @param physicalSlotIndex physical slot index
3993      * @param portIndex The port index is an enumeration of the ports available on the UICC.
3994      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
3995      *
3996      * @see #SIM_STATE_UNKNOWN
3997      * @see #SIM_STATE_PIN_REQUIRED
3998      * @see #SIM_STATE_PUK_REQUIRED
3999      * @see #SIM_STATE_NETWORK_LOCKED
4000      * @see #SIM_STATE_NOT_READY
4001      * @see #SIM_STATE_PERM_DISABLED
4002      * @see #SIM_STATE_LOADED
4003      *
4004      * @throws UnsupportedOperationException If the device does not have
4005      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4006      * @hide
4007      */
4008     @SystemApi
4009     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4010     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimApplicationState(int physicalSlotIndex, int portIndex)4011     public @SimState int getSimApplicationState(int physicalSlotIndex, int portIndex) {
4012         int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, portIndex));
4013         return getSimApplicationStateFromSimState(simState);
4014     }
4015 
4016     /**
4017      * Converts SIM state to SIM application state.
4018      * @param simState
4019      * @return SIM application state
4020      */
getSimApplicationStateFromSimState(int simState)4021     private @SimState int getSimApplicationStateFromSimState(int simState) {
4022         switch (simState) {
4023             case SIM_STATE_UNKNOWN:
4024             case SIM_STATE_ABSENT:
4025             case SIM_STATE_CARD_IO_ERROR:
4026             case SIM_STATE_CARD_RESTRICTED:
4027                 return SIM_STATE_UNKNOWN;
4028             case SIM_STATE_READY:
4029                 // Ready is not a valid state anymore. The state that is broadcast goes from
4030                 // NOT_READY to either LOCKED or LOADED.
4031                 return SIM_STATE_NOT_READY;
4032             default:
4033                 return simState;
4034         }
4035     }
4036 
4037 
4038     /**
4039      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
4040      * on the UICC card.
4041      *
4042      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
4043      *
4044      * @param appType the uicc app type like {@link APPTYPE_CSIM}
4045      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
4046      *
4047      * @throws UnsupportedOperationException If the device does not have
4048      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4049      * @hide
4050      */
4051     @SystemApi
4052     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4053     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
isApplicationOnUicc(@iccAppType int appType)4054     public boolean isApplicationOnUicc(@UiccAppType int appType) {
4055         try {
4056             ITelephony service = getITelephony();
4057             if (service != null) {
4058                 return service.isApplicationOnUicc(getSubId(), appType);
4059             }
4060         } catch (RemoteException e) {
4061             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
4062         }
4063         return false;
4064     }
4065 
4066     /**
4067      * Returns a constant indicating the state of the device SIM card in a logical slot.
4068      *
4069      * @param slotIndex logical slot index
4070      *
4071      * @see #SIM_STATE_UNKNOWN
4072      * @see #SIM_STATE_ABSENT
4073      * @see #SIM_STATE_PIN_REQUIRED
4074      * @see #SIM_STATE_PUK_REQUIRED
4075      * @see #SIM_STATE_NETWORK_LOCKED
4076      * @see #SIM_STATE_READY
4077      * @see #SIM_STATE_NOT_READY
4078      * @see #SIM_STATE_PERM_DISABLED
4079      * @see #SIM_STATE_CARD_IO_ERROR
4080      * @see #SIM_STATE_CARD_RESTRICTED
4081      *
4082      * @throws UnsupportedOperationException If the device does not have
4083      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4084      */
4085     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimState(int slotIndex)4086     public @SimState int getSimState(int slotIndex) {
4087         int simState = getSimStateForSlotIndex(slotIndex);
4088         if (simState == SIM_STATE_LOADED) {
4089             simState = SIM_STATE_READY;
4090         }
4091         return simState;
4092     }
4093 
4094     /**
4095      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4096      * provider of the SIM. 5 or 6 decimal digits.
4097      * <p>
4098      * Availability: SIM state must be {@link #SIM_STATE_READY}
4099      *
4100      * @see #getSimState
4101      */
4102     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimOperator()4103     public String getSimOperator() {
4104         return getSimOperatorNumeric();
4105     }
4106 
4107     /**
4108      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4109      * provider of the SIM. 5 or 6 decimal digits.
4110      * <p>
4111      * Availability: SIM state must be {@link #SIM_STATE_READY}
4112      *
4113      * @see #getSimState
4114      *
4115      * @param subId for which SimOperator is returned
4116      * @hide
4117      */
4118     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)4119     public String getSimOperator(int subId) {
4120         return getSimOperatorNumeric(subId);
4121     }
4122 
4123     /**
4124      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4125      * provider of the SIM. 5 or 6 decimal digits.
4126      * <p>
4127      * Availability: SIM state must be {@link #SIM_STATE_READY}
4128      *
4129      * @see #getSimState
4130      * @hide
4131      */
4132     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()4133     public String getSimOperatorNumeric() {
4134         int subId = mSubId;
4135         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4136             subId = SubscriptionManager.getDefaultDataSubscriptionId();
4137             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4138                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
4139                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4140                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
4141                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
4142                         subId = SubscriptionManager.getDefaultSubscriptionId();
4143                     }
4144                 }
4145             }
4146         }
4147         return getSimOperatorNumeric(subId);
4148     }
4149 
4150     /**
4151      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4152      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
4153      * <p>
4154      * Availability: SIM state must be {@link #SIM_STATE_READY}
4155      *
4156      * @see #getSimState
4157      *
4158      * @param subId for which SimOperator is returned
4159      * @hide
4160      */
4161     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)4162     public String getSimOperatorNumeric(int subId) {
4163         int phoneId = SubscriptionManager.getPhoneId(subId);
4164         return getSimOperatorNumericForPhone(phoneId);
4165     }
4166 
4167     /**
4168      * Returns the MCC+MNC (mobile country code + mobile network code) of the
4169      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
4170      * <p>
4171      *
4172      * @param phoneId for which SimOperator is returned
4173      * @hide
4174      */
4175     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)4176     public String getSimOperatorNumericForPhone(int phoneId) {
4177         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
4178     }
4179 
4180     /**
4181      * Returns the Service Provider Name (SPN).
4182      * <p>
4183      * Availability: SIM state must be {@link #SIM_STATE_READY}
4184      *
4185      * @see #getSimState
4186      */
4187     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimOperatorName()4188     public String getSimOperatorName() {
4189         return getSimOperatorNameForPhone(getPhoneId());
4190     }
4191 
4192     /**
4193      * Returns the Service Provider Name (SPN).
4194      * <p>
4195      * Availability: SIM state must be {@link #SIM_STATE_READY}
4196      *
4197      * @see #getSimState
4198      *
4199      * @param subId for which SimOperatorName is returned
4200      * @hide
4201      */
4202     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)4203     public String getSimOperatorName(int subId) {
4204         int phoneId = SubscriptionManager.getPhoneId(subId);
4205         return getSimOperatorNameForPhone(phoneId);
4206     }
4207 
4208     /**
4209      * Returns the Service Provider Name (SPN).
4210      *
4211      * @hide
4212      */
4213     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)4214     public String getSimOperatorNameForPhone(int phoneId) {
4215         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
4216     }
4217 
4218     /**
4219      * Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
4220      * <p>
4221      * The ISO-3166-1 alpha-2 country code is provided in lowercase 2 character format.
4222      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string is not
4223      * available.
4224      */
4225     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCountryIso()4226     public String getSimCountryIso() {
4227         return getSimCountryIsoForPhone(getPhoneId());
4228     }
4229 
4230     /**
4231      * Returns the ISO country code equivalent for the SIM provider's country code.
4232      *
4233      * @param subId for which SimCountryIso is returned
4234      * @hide
4235      */
4236     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)4237     public static String getSimCountryIso(int subId) {
4238         int phoneId = SubscriptionManager.getPhoneId(subId);
4239         return getSimCountryIsoForPhone(phoneId);
4240     }
4241 
4242     /**
4243      * Returns the ISO country code equivalent for the SIM provider's country code.
4244      *
4245      * @hide
4246      */
4247     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)4248     public static String getSimCountryIsoForPhone(int phoneId) {
4249         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
4250     }
4251 
4252     /**
4253      * Returns the serial number of the SIM, if applicable. Return null if it is
4254      * unavailable.
4255      *
4256      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4257      * restrictions, and apps are recommended to use resettable identifiers (see <a
4258      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4259      * method can be invoked if one of the following requirements is met:
4260      * <ul>
4261      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4262      *     is a privileged permission that can only be granted to apps preloaded on the device.
4263      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4264      *     owner of an organization-owned device, or their delegates (see {@link
4265      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4266      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4267      *     <li>If the calling app is the default SMS role holder (see {@link
4268      *     RoleManager#isRoleHeld(String)}).
4269      * </ul>
4270      *
4271      * <p>If the calling app does not meet one of these requirements then this method will behave
4272      * as follows:
4273      *
4274      * <ul>
4275      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4276      *     READ_PHONE_STATE permission then null is returned.</li>
4277      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4278      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4279      *     higher, then a SecurityException is thrown.</li>
4280      * </ul>
4281      *
4282      * @throws UnsupportedOperationException If the device does not have
4283      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4284      */
4285     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4286     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4287     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSerialNumber()4288     public String getSimSerialNumber() {
4289          return getSimSerialNumber(getSubId());
4290     }
4291 
4292     /**
4293      * Returns the serial number for the given subscription, if applicable. Return null if it is
4294      * unavailable.
4295      *
4296      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4297      * restrictions, and apps are recommended to use resettable identifiers (see <a
4298      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4299      * method can be invoked if one of the following requirements is met:
4300      * <ul>
4301      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4302      *     is a privileged permission that can only be granted to apps preloaded on the device.
4303      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4304      *     owner of an organization-owned device, or their delegates (see {@link
4305      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4306      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4307      *     <li>If the calling app is the default SMS role holder (see {@link
4308      *     RoleManager#isRoleHeld(String)}).
4309      * </ul>
4310      *
4311      * <p>If the calling app does not meet one of these requirements then this method will behave
4312      * as follows:
4313      *
4314      * <ul>
4315      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4316      *     READ_PHONE_STATE permission then null is returned.</li>
4317      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4318      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4319      *     higher, then a SecurityException is thrown.</li>
4320      * </ul>
4321      *
4322      * @param subId for which Sim Serial number is returned
4323      * @hide
4324      */
4325     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4326     @UnsupportedAppUsage
getSimSerialNumber(int subId)4327     public String getSimSerialNumber(int subId) {
4328         try {
4329             IPhoneSubInfo info = getSubscriberInfoService();
4330             if (info == null)
4331                 return null;
4332             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
4333                     mContext.getAttributionTag());
4334         } catch (RemoteException ex) {
4335             return null;
4336         } catch (NullPointerException ex) {
4337             // This could happen before phone restarts due to crashing
4338             return null;
4339         }
4340     }
4341 
4342     /**
4343      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
4344      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
4345      *
4346      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
4347      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
4348      *
4349      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
4350      *         {@code false} if not supported or unknown
4351      *
4352      * @throws UnsupportedOperationException If the device does not have
4353      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
4354      * @hide
4355      */
4356     @SystemApi
4357     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4358     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isLteCdmaEvdoGsmWcdmaEnabled()4359     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
4360         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
4361     }
4362 
4363     /**
4364      * Return if the current radio is LTE on CDMA for Subscription. This
4365      * is a tri-state return value as for a period of time
4366      * the mode may be unknown.
4367      *
4368      * @param subId for which radio is LTE on CDMA is returned
4369      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
4370      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
4371      * @hide
4372      */
4373     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4374     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)4375     public int getLteOnCdmaMode(int subId) {
4376         try {
4377             ITelephony telephony = getITelephony();
4378             if (telephony == null)
4379                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4380             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
4381                     getAttributionTag());
4382         } catch (RemoteException ex) {
4383             // Assume no ICC card if remote exception which shouldn't happen
4384             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4385         } catch (NullPointerException ex) {
4386             // This could happen before phone restarts due to crashing
4387             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
4388         }
4389     }
4390 
4391     /**
4392      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
4393      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
4394      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
4395      *
4396      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
4397      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
4398      * through a factory reset.
4399      *
4400      * @return card ID of the default eUICC card, if loaded.
4401      *
4402      * @throws UnsupportedOperationException If the device does not have
4403      *          {@link PackageManager#FEATURE_TELEPHONY_EUICC}.
4404      */
4405     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
getCardIdForDefaultEuicc()4406     public int getCardIdForDefaultEuicc() {
4407         try {
4408             ITelephony telephony = getITelephony();
4409             if (telephony == null) {
4410                 return UNINITIALIZED_CARD_ID;
4411             }
4412             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
4413         } catch (RemoteException e) {
4414             return UNINITIALIZED_CARD_ID;
4415         }
4416     }
4417 
4418     /**
4419      * Gets information about currently inserted UICCs and eUICCs.
4420      * <p>
4421      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4422      * <p>
4423      * If the caller has carrier priviliges on any active subscription, then they have permission to
4424      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
4425      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the physical slot index where the card is
4426      * inserted ({@link UiccCardInfo#getPhysicalSlotIndex()}.
4427      * <p>
4428      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
4429      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
4430      * UICC or eUICC card.
4431      * <p>
4432      * See {@link UiccCardInfo} for more details on the kind of information available.
4433      *
4434      * @return a list of UiccCardInfo objects, representing information on the currently inserted
4435      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
4436      * the caller does not have adequate permissions for that card.
4437      *
4438      * @throws UnsupportedOperationException If the device does not have
4439      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4440      */
4441     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4442     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4443     @NonNull
getUiccCardsInfo()4444     public List<UiccCardInfo> getUiccCardsInfo() {
4445         try {
4446             ITelephony telephony = getITelephony();
4447             if (telephony == null) {
4448                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
4449                 return new ArrayList<UiccCardInfo>();
4450             }
4451             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
4452         } catch (RemoteException e) {
4453             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
4454             return new ArrayList<UiccCardInfo>();
4455         }
4456     }
4457 
4458     /**
4459      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
4460      * available, which is possible between phone process starting and getting slot info from modem.
4461      *
4462      * @return UiccSlotInfo array.
4463      *
4464      * @throws UnsupportedOperationException If the device does not have
4465      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4466      * @hide
4467      */
4468     @SystemApi
4469     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4470     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getUiccSlotsInfo()4471     public UiccSlotInfo[] getUiccSlotsInfo() {
4472         try {
4473             ITelephony telephony = getITelephony();
4474             if (telephony == null) {
4475                 return null;
4476             }
4477             return telephony.getUiccSlotsInfo(mContext.getOpPackageName());
4478         } catch (RemoteException e) {
4479             return null;
4480         }
4481     }
4482 
4483     /**
4484      * Test method to reload the UICC profile.
4485      *
4486      * @hide
4487      */
4488     @TestApi
4489     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()4490     public void refreshUiccProfile() {
4491         try {
4492             ITelephony telephony = getITelephony();
4493             telephony.refreshUiccProfile(mSubId);
4494         } catch (RemoteException ex) {
4495             Rlog.w(TAG, "RemoteException", ex);
4496         }
4497     }
4498 
4499     /**
4500      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
4501      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
4502      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
4503      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
4504      * logical slots.
4505      *
4506      * @param physicalSlots The content of the array represents the physical slot index. The array
4507      *        size should be same as {@link #getUiccSlotsInfo()}.
4508      * @return boolean Return true if the switch succeeds, false if the switch fails.
4509      *
4510      * @throws UnsupportedOperationException If the device does not have
4511      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4512      * @hide
4513      * @deprecated {@link #setSimSlotMapping(Collection, Executor, Consumer)}
4514      */
4515      // TODO: once integrating the HAL changes we can  convert int[] to List<UiccSlotMapping> and
4516      // converge API's in ITelephony.aidl and PhoneInterfaceManager
4517 
4518     @SystemApi
4519     @Deprecated
4520     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4521     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
switchSlots(int[] physicalSlots)4522     public boolean switchSlots(int[] physicalSlots) {
4523         try {
4524             ITelephony telephony = getITelephony();
4525             if (telephony == null) {
4526                 return false;
4527             }
4528             return telephony.switchSlots(physicalSlots);
4529         } catch (RemoteException e) {
4530             return false;
4531         }
4532     }
4533 
4534     /**
4535      * @param slotMapping Logical to physical slot and port mapping.
4536      * @return {@code true} if slotMapping is valid.
4537      * @return {@code false} if slotMapping is invalid.
4538      *
4539      * slotMapping is invalid if there are different entries (physical slot + port) mapping to the
4540      * same logical slot or if there are same {physical slot + port} mapping to the different
4541      * logical slot
4542      * @hide
4543      */
isSlotMappingValid(@onNull Collection<UiccSlotMapping> slotMapping)4544     private static boolean isSlotMappingValid(@NonNull Collection<UiccSlotMapping> slotMapping) {
4545         // Grouping the collection by logicalSlotIndex, finding different entries mapping to the
4546         // same logical slot
4547         Map<Integer, List<UiccSlotMapping>> slotMappingInfo = slotMapping.stream().collect(
4548                 Collectors.groupingBy(UiccSlotMapping::getLogicalSlotIndex));
4549         for (Map.Entry<Integer, List<UiccSlotMapping>> entry : slotMappingInfo.entrySet()) {
4550             List<UiccSlotMapping> logicalSlotMap = entry.getValue();
4551             if (logicalSlotMap.size() > 1) {
4552                 // duplicate logicalSlotIndex found
4553                 return false;
4554             }
4555         }
4556 
4557         // Grouping the collection by physical slot and port, finding same entries mapping to the
4558         // different logical slot
4559         Map<List<Integer>, List<UiccSlotMapping>> slotMapInfos = slotMapping.stream().collect(
4560                 Collectors.groupingBy(
4561                         slot -> Arrays.asList(slot.getPhysicalSlotIndex(), slot.getPortIndex())));
4562         for (Map.Entry<List<Integer>, List<UiccSlotMapping>> entry : slotMapInfos.entrySet()) {
4563             List<UiccSlotMapping> portAndPhysicalSlotList = entry.getValue();
4564             if (portAndPhysicalSlotList.size() > 1) {
4565                 // duplicate pair of portIndex and physicalSlotIndex found
4566                 return false;
4567             }
4568         }
4569         return true;
4570     }
4571     /**
4572      * Maps the logical slots to physical slots and ports. Mapping is specified from
4573      * {@link UiccSlotMapping} which consist of both physical slot index and port index.
4574      * Logical slot is the slot that is seen by modem. Physical slot is the actual physical slot.
4575      * Port index is the index (enumerated value) for the associated port available on the SIM.
4576      * Each physical slot can have multiple ports if
4577      * {@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP} is supported.
4578      *
4579      * Example: no. of logical slots 1 and physical slots 2 do not support MEP, each physical slot
4580      * has one port:
4581      * The only logical slot (index 0) can be mapped to first physical slot (value 0), port(index
4582      * 0) or
4583      * second physical slot(value 1), port (index 0), while the other physical slot remains unmapped
4584      * and inactive.
4585      * slotMapping[0] = UiccSlotMapping{0 //port index, 0 //physical slot, 0 //logical slot} or
4586      * slotMapping[0] = UiccSlotMapping{0 //port index, 1 //physical slot, 0 //logical slot}
4587      *
4588      * Example no. of logical slots 2 and physical slots 2 supports MEP with 2 ports available:
4589      * Each logical slot must be mapped to a port (physical slot and port combination).
4590      * First logical slot (index 0) can be mapped to physical slot 1 and the second logical slot
4591      * can be mapped to either port from physical slot 2.
4592      *
4593      * slotMapping[0] = UiccSlotMapping{0, 0, 0} and slotMapping[1] = UiccSlotMapping{0, 1, 1} or
4594      * slotMapping[0] = UiccSlotMapping{0, 0, 0} and slotMapping[1] = UiccSlotMapping{1, 1, 1}
4595      *
4596      * or the other way around, the second logical slot(index 1) can be mapped to physical slot 1
4597      * and the first logical slot can be mapped to either port from physical slot 2.
4598      *
4599      * slotMapping[1] = UiccSlotMapping{0, 0, 0} and slotMapping[0] = UiccSlotMapping{0, 1, 1} or
4600      * slotMapping[1] = UiccSlotMapping{0, 0, 0} and slotMapping[0] = UiccSlotMapping{1, 1, 1}
4601      *
4602      * another possible mapping is each logical slot maps to each port of physical slot 2 and there
4603      * is no active logical modem mapped to physical slot 1.
4604      *
4605      * slotMapping[0] = UiccSlotMapping{0, 1, 0} and slotMapping[1] = UiccSlotMapping{1, 1, 1} or
4606      * slotMapping[0] = UiccSlotMapping{1, 1, 0} and slotMapping[1] = UiccSlotMapping{0, 1, 1}
4607      *
4608      * @param slotMapping Logical to physical slot and port mapping.
4609      * @throws IllegalStateException if telephony service is null or slot mapping was sent when the
4610      *         radio in middle of a silent restart or other invalid states to handle the command
4611      * @throws IllegalArgumentException if the caller passes in an invalid collection of
4612      *         UiccSlotMapping like duplicate data, etc
4613      *
4614      * @throws UnsupportedOperationException If the device does not have
4615      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4616      * @hide
4617      */
4618     @SystemApi
4619     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4620     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimSlotMapping(@onNull Collection<UiccSlotMapping> slotMapping)4621     public void setSimSlotMapping(@NonNull Collection<UiccSlotMapping> slotMapping) {
4622         try {
4623             ITelephony telephony = getITelephony();
4624             if (telephony != null) {
4625                 if (isSlotMappingValid(slotMapping)) {
4626                     boolean result = telephony.setSimSlotMapping(new ArrayList(slotMapping));
4627                     if (!result) {
4628                         throw new IllegalStateException("setSimSlotMapping has failed");
4629                     }
4630                 } else {
4631                     throw new IllegalArgumentException("Duplicate UiccSlotMapping data found");
4632                 }
4633             } else {
4634                 throw new IllegalStateException("telephony service is null.");
4635             }
4636         } catch (RemoteException e) {
4637             throw e.rethrowAsRuntimeException();
4638         }
4639     }
4640 
4641     /**
4642      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
4643      * id and the value is the physical slots id mapped to this logical slot id.
4644      *
4645      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
4646      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
4647      *
4648      * @throws UnsupportedOperationException If the device does not have
4649      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4650      * @hide
4651      * @deprecated use {@link #getSimSlotMapping()} instead.
4652      */
4653     @SystemApi
4654     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4655     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4656     @NonNull
4657     @Deprecated
getLogicalToPhysicalSlotMapping()4658     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
4659         Map<Integer, Integer> slotMapping = new HashMap<>();
4660         try {
4661             ITelephony telephony = getITelephony();
4662             if (telephony != null) {
4663                 List<UiccSlotMapping> simSlotsMapping = telephony.getSlotsMapping(
4664                         mContext.getOpPackageName());
4665                 for (UiccSlotMapping slotMap : simSlotsMapping) {
4666                     slotMapping.put(slotMap.getLogicalSlotIndex(), slotMap.getPhysicalSlotIndex());
4667                 }
4668             }
4669         } catch (RemoteException e) {
4670             Log.e(TAG, "getSlotsMapping RemoteException", e);
4671         }
4672         return slotMapping;
4673     }
4674 
4675     /**
4676      * Get the mapping from logical slots to physical sim slots and port indexes. Initially the
4677      * logical slot index was mapped to physical slot index, but with support for multi-enabled
4678      * profile(MEP){@link PackageManager#FEATURE_TELEPHONY_EUICC_MEP},logical slot is now mapped to
4679      * port index.
4680      *
4681      * @return a collection of {@link UiccSlotMapping} which indicates the mapping from logical
4682      *         slots to ports and physical slots.
4683      *
4684      * @throws UnsupportedOperationException If the device does not have
4685      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4686      * @hide
4687      */
4688     @SystemApi
4689     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4690     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4691     @NonNull
getSimSlotMapping()4692     public Collection<UiccSlotMapping> getSimSlotMapping() {
4693         List<UiccSlotMapping> slotMap;
4694         try {
4695             ITelephony telephony = getITelephony();
4696             if (telephony != null) {
4697                 slotMap = telephony.getSlotsMapping(mContext.getOpPackageName());
4698             } else {
4699                 throw new IllegalStateException("telephony service is null.");
4700             }
4701         } catch (RemoteException e) {
4702             throw e.rethrowAsRuntimeException();
4703         }
4704         return slotMap;
4705     }
4706     //
4707     //
4708     // Subscriber Info
4709     //
4710     //
4711 
4712     /**
4713      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
4714      * Return null if it is unavailable.
4715      *
4716      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4717      * restrictions, and apps are recommended to use resettable identifiers (see <a
4718      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4719      * method can be invoked if one of the following requirements is met:
4720      * <ul>
4721      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4722      *     is a privileged permission that can only be granted to apps preloaded on the device.
4723      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4724      *     owner of an organization-owned device, or their delegates (see {@link
4725      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4726      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4727      *     <li>If the calling app is the default SMS role holder (see {@link
4728      *     RoleManager#isRoleHeld(String)}).
4729      *     <li>If the calling app has been granted the
4730      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
4731      * </ul>
4732      *
4733      * <p>If the calling app does not meet one of these requirements then this method will behave
4734      * as follows:
4735      *
4736      * <ul>
4737      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4738      *     READ_PHONE_STATE permission then null is returned.</li>
4739      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4740      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4741      *     higher, then a SecurityException is thrown.</li>
4742      * </ul>
4743      *
4744      * @throws UnsupportedOperationException If the device does not have
4745      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4746      */
4747     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4748     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4749     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriberId()4750     public String getSubscriberId() {
4751         return getSubscriberId(getSubId());
4752     }
4753 
4754     /**
4755      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
4756      * for a subscription.
4757      * Return null if it is unavailable.
4758      *
4759      * See {@link #getSubscriberId()} for details on the required permissions and behavior
4760      * when the caller does not hold sufficient permissions.
4761      *
4762      * @param subId whose subscriber id is returned
4763      * @hide
4764      */
4765     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4766     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)4767     public String getSubscriberId(int subId) {
4768         try {
4769             IPhoneSubInfo info = getSubscriberInfoService();
4770             if (info == null)
4771                 return null;
4772             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
4773                     mContext.getAttributionTag());
4774         } catch (RemoteException ex) {
4775             return null;
4776         } catch (NullPointerException ex) {
4777             // This could happen before phone restarts due to crashing
4778             return null;
4779         }
4780     }
4781 
4782     /**
4783      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
4784      * including the public key and the key identifier; or {@code null} if not available.
4785      * <p>
4786      * For a multi-sim device, the dafault data sim is used if not specified.
4787      * <p>
4788      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
4789      *
4790      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
4791      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
4792      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
4793      *         IMSI and IMPI. This includes the public key and the key identifier. This information
4794      *         will be stored in the device keystore. {@code null} will be returned when no key is
4795      *         found, and the carrier does not require a key.
4796      * @throws IllegalArgumentException when an invalid key is found or when key is required but
4797      *         not found.
4798      * @throws UnsupportedOperationException If the device does not have
4799      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4800      * @hide
4801      */
4802     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4803     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4804     @SystemApi
4805     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)4806     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
4807         try {
4808             IPhoneSubInfo info = getSubscriberInfoService();
4809             if (info == null) {
4810                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
4811                 return null;
4812             }
4813             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4814             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
4815                 throw new IllegalArgumentException("IMSI error: Invalid key type");
4816             }
4817             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
4818                     subId, keyType, mContext.getOpPackageName());
4819             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
4820                 Rlog.e(TAG, "IMSI error: key is required but not found");
4821                 throw new IllegalArgumentException("IMSI error: key is required but not found");
4822             }
4823             return imsiEncryptionInfo;
4824         } catch (RemoteException ex) {
4825             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4826         } catch (NullPointerException ex) {
4827             // This could happen before phone restarts due to crashing
4828             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
4829         }
4830         return null;
4831     }
4832 
4833     /**
4834      * Resets the carrier keys used to encrypt the IMSI and IMPI.
4835      * <p>
4836      * This involves 2 steps:
4837      *  1. Delete the keys from the database.
4838      *  2. Send an intent to download new Certificates.
4839      * <p>
4840      * For a multi-sim device, the dafault data sim is used if not specified.
4841      * <p>
4842      * Requires Permission: MODIFY_PHONE_STATE.
4843      *
4844      * @see #getCarrierInfoForImsiEncryption
4845      *
4846      * @throws UnsupportedOperationException If the device does not have
4847      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
4848      * @hide
4849      */
4850     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4851     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
4852     @SystemApi
resetCarrierKeysForImsiEncryption()4853     public void resetCarrierKeysForImsiEncryption() {
4854         try {
4855             IPhoneSubInfo info = getSubscriberInfoService();
4856             if (info == null) {
4857                 throw new RuntimeException("IMSI error: Subscriber Info is null");
4858             }
4859             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4860             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
4861         } catch (RemoteException ex) {
4862             Rlog.e(TAG, "Telephony#getCarrierInfoForImsiEncryption RemoteException" + ex);
4863         }
4864     }
4865 
4866     /**
4867      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
4868      * @param keyType the key type which is being checked. (WLAN, EPDG)
4869      * @return true if the digit at position keyType is 1, else false.
4870      * @hide
4871      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)4872     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
4873         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
4874         return (returnValue == 1) ? true : false;
4875     }
4876 
4877     /**
4878      * If Carrier requires Imsi to be encrypted.
4879      * @hide
4880      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4881     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4882         CarrierConfigManager configManager =
4883                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4884         if (configManager == null) {
4885             return false;
4886         }
4887         PersistableBundle pb = configManager.getConfigForSubId(subId);
4888         if (pb == null) {
4889             return false;
4890         }
4891         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4892         return isKeyEnabled(keyAvailability, keyType);
4893     }
4894 
4895     /**
4896      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4897      * This includes the public key and the key identifier. This information will be stored in the
4898      * device keystore.
4899      * <p>
4900      * Requires Permission:
4901      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4902      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4903      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4904      *        The keyIdentifier Attribute value pair that helps a server locate
4905      *        the private key to decrypt the permanent identity. This field is
4906      *        optional and if it is present then it’s always separated from encrypted
4907      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4908      *        with “name=value” format.
4909      * @hide
4910      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4911     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4912         try {
4913             IPhoneSubInfo info = getSubscriberInfoService();
4914             if (info == null) return;
4915             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4916                     imsiEncryptionInfo);
4917         } catch (NullPointerException ex) {
4918             // This could happen before phone restarts due to crashing
4919             return;
4920         } catch (RemoteException ex) {
4921             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4922             return;
4923         }
4924     }
4925 
4926     /**
4927      * Exception that may be supplied to the callback in {@link #uploadCallComposerPicture} if
4928      * something goes awry.
4929      */
4930     public static class CallComposerException extends Exception {
4931         /**
4932          * Used internally only, signals success of the upload to the carrier.
4933          * @hide
4934          */
4935         public static final int SUCCESS = -1;
4936         /**
4937          * Indicates that an unknown error was encountered when uploading the call composer picture.
4938          *
4939          * Clients that encounter this error should retry the upload.
4940          */
4941         public static final int ERROR_UNKNOWN = 0;
4942 
4943         /**
4944          * Indicates that the phone process died or otherwise became unavailable while uploading the
4945          * call composer picture.
4946          *
4947          * Clients that encounter this error should retry the upload.
4948          */
4949         public static final int ERROR_REMOTE_END_CLOSED = 1;
4950 
4951         /**
4952          * Indicates that the file or stream supplied exceeds the size limit defined in
4953          * {@link #getMaximumCallComposerPictureSize()}.
4954          *
4955          * Clients that encounter this error should retry the upload after reducing the size of the
4956          * picture.
4957          */
4958         public static final int ERROR_FILE_TOO_LARGE = 2;
4959 
4960         /**
4961          * Indicates that the device failed to authenticate with the carrier when uploading the
4962          * picture.
4963          *
4964          * Clients that encounter this error should not retry the upload unless a reboot or radio
4965          * reset has been performed in the interim.
4966          */
4967         public static final int ERROR_AUTHENTICATION_FAILED = 3;
4968 
4969         /**
4970          * Indicates that the {@link InputStream} passed to {@link #uploadCallComposerPicture}
4971          * was closed.
4972          *
4973          * The caller should retry if this error is encountered, and be sure to not close the stream
4974          * before the callback is called this time.
4975          */
4976         public static final int ERROR_INPUT_CLOSED = 4;
4977 
4978         /**
4979          * Indicates that an {@link IOException} was encountered while reading the picture.
4980          *
4981          * The offending {@link IOException} will be available via {@link #getIOException()}.
4982          * Clients should use the contents of the exception to determine whether a retry is
4983          * warranted.
4984          */
4985         public static final int ERROR_IO_EXCEPTION = 5;
4986 
4987         /**
4988          * Indicates that the device is currently not connected to a network that's capable of
4989          * reaching a carrier's RCS servers.
4990          *
4991          * Clients should prompt the user to remedy the issue by moving to an area with better
4992          * signal, by connecting to a different network, or to retry at another time.
4993          */
4994         public static final int ERROR_NETWORK_UNAVAILABLE = 6;
4995 
4996         /** @hide */
4997         @IntDef(prefix = {"ERROR_"}, value = {
4998                 ERROR_UNKNOWN,
4999                 ERROR_REMOTE_END_CLOSED,
5000                 ERROR_FILE_TOO_LARGE,
5001                 ERROR_AUTHENTICATION_FAILED,
5002                 ERROR_INPUT_CLOSED,
5003                 ERROR_IO_EXCEPTION,
5004                 ERROR_NETWORK_UNAVAILABLE,
5005         })
5006 
5007         @Retention(RetentionPolicy.SOURCE)
5008         public @interface CallComposerError {}
5009 
5010         private final int mErrorCode;
5011         private final IOException mIOException;
5012 
CallComposerException(@allComposerError int errorCode, @Nullable IOException ioException)5013         public CallComposerException(@CallComposerError int errorCode,
5014                 @Nullable IOException ioException) {
5015             mErrorCode = errorCode;
5016             mIOException = ioException;
5017         }
5018 
5019         /**
5020          * Fetches the error code associated with this exception.
5021          * @return An error code.
5022          */
getErrorCode()5023         public @CallComposerError int getErrorCode() {
5024             return mErrorCode;
5025         }
5026 
5027         /**
5028          * Fetches the {@link IOException} that caused the error.
5029          */
5030         // Follows the naming of IOException
5031         @SuppressLint("AcronymName")
getIOException()5032         public @Nullable IOException getIOException() {
5033             return mIOException;
5034         }
5035     }
5036 
5037     /** @hide */
5038     public static final String KEY_CALL_COMPOSER_PICTURE_HANDLE = "call_composer_picture_handle";
5039 
5040     /**
5041      * Uploads a picture to the carrier network for use with call composer.
5042      *
5043      * @see #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)
5044      * @param pictureToUpload Path to a local file containing the picture to upload.
5045      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg)
5046      * @param executor The {@link Executor} on which the {@code pictureToUpload} file will be read
5047      *                 from disk, as well as on which {@code callback} will be called.
5048      * @param callback A callback called when the upload operation terminates, either in success
5049      *                 or in error.
5050      *
5051      * @throws UnsupportedOperationException If the device does not have
5052      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5053      */
5054     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
uploadCallComposerPicture(@onNull Path pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)5055     public void uploadCallComposerPicture(@NonNull Path pictureToUpload,
5056             @NonNull String contentType,
5057             @CallbackExecutor @NonNull Executor executor,
5058             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
5059         Objects.requireNonNull(pictureToUpload);
5060         Objects.requireNonNull(executor);
5061         Objects.requireNonNull(callback);
5062 
5063         // Do the role check now so that we can quit early if needed -- there's an additional
5064         // permission check on the other side of the binder call as well.
5065         RoleManager rm = mContext.getSystemService(RoleManager.class);
5066         if (!rm.isRoleHeld(RoleManager.ROLE_DIALER)) {
5067             throw new SecurityException("You must hold RoleManager.ROLE_DIALER to do this");
5068         }
5069 
5070         executor.execute(() -> {
5071             try {
5072                 if (Looper.getMainLooper().isCurrentThread()) {
5073                     Log.w(TAG, "Uploading call composer picture on main thread!"
5074                             + " hic sunt dracones!");
5075                 }
5076                 long size = Files.size(pictureToUpload);
5077                 if (size > getMaximumCallComposerPictureSize()) {
5078                     callback.onError(new CallComposerException(
5079                             CallComposerException.ERROR_FILE_TOO_LARGE, null));
5080                     return;
5081                 }
5082                 InputStream fileStream = Files.newInputStream(pictureToUpload);
5083                 try {
5084                     uploadCallComposerPicture(fileStream, contentType, executor,
5085                             new OutcomeReceiver<ParcelUuid, CallComposerException>() {
5086                                 @Override
5087                                 public void onResult(ParcelUuid result) {
5088                                     try {
5089                                         fileStream.close();
5090                                     } catch (IOException e) {
5091                                         // ignore
5092                                         Log.e(TAG, "Error closing file input stream when"
5093                                                 + " uploading call composer pic");
5094                                     }
5095                                     callback.onResult(result);
5096                                 }
5097 
5098                                 @Override
5099                                 public void onError(CallComposerException error) {
5100                                     try {
5101                                         fileStream.close();
5102                                     } catch (IOException e) {
5103                                         // ignore
5104                                         Log.e(TAG, "Error closing file input stream when"
5105                                                 + " uploading call composer pic");
5106                                     }
5107                                     callback.onError(error);
5108                                 }
5109                             });
5110                 } catch (Exception e) {
5111                     Log.e(TAG, "Got exception calling into stream-version of"
5112                             + " uploadCallComposerPicture: " + e);
5113                     try {
5114                         fileStream.close();
5115                     } catch (IOException e1) {
5116                         // ignore
5117                         Log.e(TAG, "Error closing file input stream when uploading"
5118                                 + " call composer pic");
5119                     }
5120                 }
5121             } catch (IOException e) {
5122                 Log.e(TAG, "IOException when uploading call composer pic:" + e);
5123                 callback.onError(
5124                         new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e));
5125             }
5126         });
5127 
5128     }
5129 
5130     /**
5131      * Uploads a picture to the carrier network for use with call composer.
5132      *
5133      * This method allows a dialer app to upload a picture to the carrier network that can then
5134      * later be attached to an outgoing call. In order to attach the picture to a call, use the
5135      * {@link ParcelUuid} returned from {@code callback} upon successful upload as the value to
5136      * {@link TelecomManager#EXTRA_OUTGOING_PICTURE}.
5137      *
5138      * This functionality is only available to the app filling the {@link RoleManager#ROLE_DIALER}
5139      * role on the device.
5140      *
5141      * This functionality is only available when
5142      * {@link CarrierConfigManager#KEY_SUPPORTS_CALL_COMPOSER_BOOL} is set to {@code true} in the
5143      * bundle returned from {@link #getCarrierConfig()}.
5144      *
5145      * @param pictureToUpload An {@link InputStream} that supplies the bytes representing the
5146      *                        picture to upload. The client bears responsibility for closing this
5147      *                        stream after {@code callback} is called with success or failure.
5148      *
5149      *                        Additionally, if the stream supplies more bytes than the return value
5150      *                        of {@link #getMaximumCallComposerPictureSize()}, the upload will be
5151      *                        aborted and the callback will be called with an exception containing
5152      *                        {@link CallComposerException#ERROR_FILE_TOO_LARGE}.
5153      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg). The list
5154      *                    of acceptable content types can be found at 3GPP TS 26.141 sections
5155      *                    4.2 and 4.3.
5156      * @param executor The {@link Executor} on which the {@code pictureToUpload} stream will be
5157      *                 read, as well as on which the callback will be called.
5158      * @param callback A callback called when the upload operation terminates, either in success
5159      *                 or in error.
5160      *
5161      * @throws UnsupportedOperationException If the device does not have
5162      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5163      */
5164     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
uploadCallComposerPicture(@onNull InputStream pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)5165     public void uploadCallComposerPicture(@NonNull InputStream pictureToUpload,
5166             @NonNull String contentType,
5167             @CallbackExecutor @NonNull Executor executor,
5168             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
5169         Objects.requireNonNull(pictureToUpload);
5170         Objects.requireNonNull(executor);
5171         Objects.requireNonNull(callback);
5172 
5173         ITelephony telephony = getITelephony();
5174         if (telephony == null) {
5175             throw new IllegalStateException("Telephony service not available.");
5176         }
5177 
5178         ParcelFileDescriptor writeFd;
5179         ParcelFileDescriptor readFd;
5180         try {
5181             ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
5182             writeFd = pipe[1];
5183             readFd = pipe[0];
5184         } catch (IOException e) {
5185             executor.execute(() -> callback.onError(
5186                     new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e)));
5187             return;
5188         }
5189 
5190         OutputStream output = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
5191 
5192         try {
5193             telephony.uploadCallComposerPicture(getSubId(), mContext.getOpPackageName(),
5194                     contentType, readFd, new ResultReceiver(null) {
5195                         @Override
5196                         protected void onReceiveResult(int resultCode, Bundle result) {
5197                             if (resultCode != CallComposerException.SUCCESS) {
5198                                 executor.execute(() -> callback.onError(
5199                                         new CallComposerException(resultCode, null)));
5200                                 return;
5201                             }
5202                             ParcelUuid resultUuid =
5203                                     result.getParcelable(KEY_CALL_COMPOSER_PICTURE_HANDLE, android.os.ParcelUuid.class);
5204                             if (resultUuid == null) {
5205                                 Log.e(TAG, "Got null uuid without an error"
5206                                         + " while uploading call composer pic");
5207                                 executor.execute(() -> callback.onError(
5208                                         new CallComposerException(
5209                                                 CallComposerException.ERROR_UNKNOWN, null)));
5210                                 return;
5211                             }
5212                             executor.execute(() -> callback.onResult(resultUuid));
5213                         }
5214                     });
5215         } catch (RemoteException e) {
5216             Log.e(TAG, "Remote exception uploading call composer pic:" + e);
5217             e.rethrowAsRuntimeException();
5218         }
5219 
5220         executor.execute(() -> {
5221             if (Looper.getMainLooper().isCurrentThread()) {
5222                 Log.w(TAG, "Uploading call composer picture on main thread!"
5223                         + " hic sunt dracones!");
5224             }
5225 
5226             int totalBytesRead = 0;
5227             byte[] buffer = new byte[16 * 1024];
5228             try {
5229                 while (true) {
5230                     int numRead;
5231                     try {
5232                         numRead = pictureToUpload.read(buffer);
5233                     } catch (IOException e) {
5234                         Log.e(TAG, "IOException reading from input while uploading pic: " + e);
5235                         // Most likely, this was because the stream was closed. We have no way to
5236                         // tell though.
5237                         callback.onError(new CallComposerException(
5238                                 CallComposerException.ERROR_INPUT_CLOSED, e));
5239                         try {
5240                             writeFd.closeWithError("input closed");
5241                         } catch (IOException e1) {
5242                             // log and ignore
5243                             Log.e(TAG, "Error closing fd pipe: " + e1);
5244                         }
5245                         break;
5246                     }
5247 
5248                     if (numRead < 0) {
5249                         break;
5250                     }
5251 
5252                     totalBytesRead += numRead;
5253                     if (totalBytesRead > getMaximumCallComposerPictureSize()) {
5254                         Log.e(TAG, "Read too many bytes from call composer pic stream: "
5255                                 + totalBytesRead);
5256                         try {
5257                             callback.onError(new CallComposerException(
5258                                     CallComposerException.ERROR_FILE_TOO_LARGE, null));
5259                             writeFd.closeWithError("too large");
5260                         } catch (IOException e1) {
5261                             // log and ignore
5262                             Log.e(TAG, "Error closing fd pipe: " + e1);
5263                         }
5264                         break;
5265                     }
5266 
5267                     try {
5268                         output.write(buffer, 0, numRead);
5269                     } catch (IOException e) {
5270                         callback.onError(new CallComposerException(
5271                                 CallComposerException.ERROR_REMOTE_END_CLOSED, e));
5272                         try {
5273                             writeFd.closeWithError("remote end closed");
5274                         } catch (IOException e1) {
5275                             // log and ignore
5276                             Log.e(TAG, "Error closing fd pipe: " + e1);
5277                         }
5278                         break;
5279                     }
5280                 }
5281             } finally {
5282                 try {
5283                     output.close();
5284                 } catch (IOException e) {
5285                     // Ignore -- we might've already closed it.
5286                 }
5287             }
5288         });
5289     }
5290 
5291     /**
5292      * Returns the Group Identifier Level1 for a GSM phone.
5293      * Return null if it is unavailable.
5294      *
5295      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5296      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5297      *
5298      * @throws UnsupportedOperationException If the device does not have
5299      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5300      */
5301     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5302     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5303     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getGroupIdLevel1()5304     public String getGroupIdLevel1() {
5305         try {
5306             IPhoneSubInfo info = getSubscriberInfoService();
5307             if (info == null)
5308                 return null;
5309             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
5310                     mContext.getAttributionTag());
5311         } catch (RemoteException ex) {
5312             return null;
5313         } catch (NullPointerException ex) {
5314             // This could happen before phone restarts due to crashing
5315             return null;
5316         }
5317     }
5318 
5319     /**
5320      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
5321      * Return null if it is unavailable.
5322      *
5323      * @param subId whose subscriber id is returned
5324      * @hide
5325      */
5326     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5327     @UnsupportedAppUsage
getGroupIdLevel1(int subId)5328     public String getGroupIdLevel1(int subId) {
5329         try {
5330             IPhoneSubInfo info = getSubscriberInfoService();
5331             if (info == null)
5332                 return null;
5333             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
5334                     mContext.getAttributionTag());
5335         } catch (RemoteException ex) {
5336             return null;
5337         } catch (NullPointerException ex) {
5338             // This could happen before phone restarts due to crashing
5339             return null;
5340         }
5341     }
5342 
5343     /**
5344      * Returns the Group Identifier Level 2 in hexadecimal format.
5345      * @return the Group Identifier Level 2 for the SIM card.
5346      *         Return null if it is unavailable.
5347      *
5348      * @throws UnsupportedOperationException If the device does not have
5349      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5350      * @hide
5351      */
5352     @FlaggedApi(Flags.FLAG_GET_GROUP_ID_LEVEL2)
5353     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5354     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
5355     @SystemApi
5356     @Nullable
getGroupIdLevel2()5357     public String getGroupIdLevel2() {
5358         try {
5359             IPhoneSubInfo info = getSubscriberInfoService();
5360             if (info == null) {
5361                 return null;
5362             }
5363             return info.getGroupIdLevel2ForSubscriber(getSubId(), mContext.getOpPackageName(),
5364                     mContext.getAttributionTag());
5365         } catch (RemoteException ex) {
5366             return null;
5367         } catch (NullPointerException ex) {
5368             // This could happen before phone restarts due to crashing
5369             return null;
5370         }
5371     }
5372 
5373     /**
5374      * Returns the phone number string for line 1, for example, the MSISDN
5375      * for a GSM phone for a particular subscription. Return null if it is unavailable.
5376      * <p>
5377      * The default SMS app can also use this.
5378      *
5379      * <p>Requires Permission:
5380      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5381      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5382      *     that the caller is the default SMS app,
5383      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5384      *     for any API level.
5385      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5386      *     for apps targeting SDK API level 29 and below.
5387      *
5388      * @throws UnsupportedOperationException If the device does not have
5389      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5390      * @deprecated use {@link SubscriptionManager#getPhoneNumber(int)} instead.
5391      */
5392     @Deprecated
5393     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
5394     @RequiresPermission(anyOf = {
5395             android.Manifest.permission.READ_PHONE_STATE,
5396             android.Manifest.permission.READ_SMS,
5397             android.Manifest.permission.READ_PHONE_NUMBERS
5398     })
5399     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getLine1Number()5400     public String getLine1Number() {
5401         return getLine1Number(getSubId());
5402     }
5403 
5404     /**
5405      * Returns the phone number string for line 1, for example, the MSISDN
5406      * for a GSM phone for a particular subscription. Return null if it is unavailable.
5407      * <p>
5408      * The default SMS app can also use this.
5409      *
5410      * <p>Requires Permission:
5411      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5412      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5413      *     that the caller is the default SMS app,
5414      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5415      *     for any API level.
5416      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5417      *     for apps targeting SDK API level 29 and below.
5418      *
5419      * @param subId whose phone number for line 1 is returned
5420      * @hide
5421      */
5422     @RequiresPermission(anyOf = {
5423             android.Manifest.permission.READ_PHONE_STATE,
5424             android.Manifest.permission.READ_SMS,
5425             android.Manifest.permission.READ_PHONE_NUMBERS
5426     })
5427     @UnsupportedAppUsage
getLine1Number(int subId)5428     public String getLine1Number(int subId) {
5429         String number = null;
5430         try {
5431             ITelephony telephony = getITelephony();
5432             if (telephony != null)
5433                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
5434                          mContext.getAttributionTag());
5435         } catch (RemoteException ex) {
5436         } catch (NullPointerException ex) {
5437         }
5438         if (number != null) {
5439             return number;
5440         }
5441         try {
5442             IPhoneSubInfo info = getSubscriberInfoService();
5443             if (info == null)
5444                 return null;
5445             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
5446                     mContext.getAttributionTag());
5447         } catch (RemoteException ex) {
5448             return null;
5449         } catch (NullPointerException ex) {
5450             // This could happen before phone restarts due to crashing
5451             return null;
5452         }
5453     }
5454 
5455     /**
5456      * Set the line 1 phone number string and its alphatag for the current ICCID
5457      * for display purpose only, for example, displayed in Phone Status. It won't
5458      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
5459      * value.
5460      *
5461      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5462      *
5463      * @param alphaTag alpha-tagging of the dailing nubmer
5464      * @param number The dialing number
5465      * @return true if the operation was executed correctly.
5466      *
5467      * @throws UnsupportedOperationException If the device does not have
5468      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5469      * @deprecated use {@link SubscriptionManager#setCarrierPhoneNumber(int, String)} instead.
5470      */
5471     @Deprecated
5472     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setLine1NumberForDisplay(String alphaTag, String number)5473     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
5474         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
5475     }
5476 
5477     /**
5478      * Set the line 1 phone number string and its alphatag for the current ICCID
5479      * for display purpose only, for example, displayed in Phone Status. It won't
5480      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
5481      * value.
5482      *
5483      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5484      *
5485      * @param subId the subscriber that the alphatag and dialing number belongs to.
5486      * @param alphaTag alpha-tagging of the dailing nubmer
5487      * @param number The dialing number
5488      * @return true if the operation was executed correctly.
5489      * @hide
5490      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)5491     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
5492         try {
5493             // This API is deprecated; call the new API to allow smooth migartion.
5494             // The new API doesn't accept null so convert null to empty string.
5495             mSubscriptionManager.setCarrierPhoneNumber(subId, (number == null ? "" : number));
5496 
5497             ITelephony telephony = getITelephony();
5498             if (telephony != null)
5499                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
5500         } catch (RemoteException ex) {
5501         } catch (NullPointerException ex) {
5502         }
5503         return false;
5504     }
5505 
5506     /**
5507      * Returns the alphabetic identifier associated with the line 1 number.
5508      * Return null if it is unavailable.
5509      * @hide
5510      * nobody seems to call this.
5511      */
5512     @UnsupportedAppUsage
5513     @TestApi
5514     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()5515     public String getLine1AlphaTag() {
5516         return getLine1AlphaTag(getSubId());
5517     }
5518 
5519     /**
5520      * Returns the alphabetic identifier associated with the line 1 number
5521      * for a subscription.
5522      * Return null if it is unavailable.
5523      * @param subId whose alphabetic identifier associated with line 1 is returned
5524      * nobody seems to call this.
5525      * @hide
5526      */
5527     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5528     @UnsupportedAppUsage
getLine1AlphaTag(int subId)5529     public String getLine1AlphaTag(int subId) {
5530         String alphaTag = null;
5531         try {
5532             ITelephony telephony = getITelephony();
5533             if (telephony != null)
5534                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
5535                         getOpPackageName(), getAttributionTag());
5536         } catch (RemoteException ex) {
5537         } catch (NullPointerException ex) {
5538         }
5539         if (alphaTag != null) {
5540             return alphaTag;
5541         }
5542         try {
5543             IPhoneSubInfo info = getSubscriberInfoService();
5544             if (info == null)
5545                 return null;
5546             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
5547                     getAttributionTag());
5548         } catch (RemoteException ex) {
5549             return null;
5550         } catch (NullPointerException ex) {
5551             // This could happen before phone restarts due to crashing
5552             return null;
5553         }
5554     }
5555 
5556     /**
5557      * Return the set of subscriber IDs that should be considered "merged together" for data usage
5558      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
5559      * subscribers are sorted in a deterministic order.
5560      * <p>
5561      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
5562      * TelephonyManager's subId.
5563      *
5564      * This is deprecated and {@link #getMergedImsisFromGroup()} should be used for data
5565      * usage merging purpose.
5566      * TODO: remove this API.
5567      *
5568      * @hide
5569      */
5570     @UnsupportedAppUsage
5571     @Deprecated
getMergedSubscriberIds()5572     public @Nullable String[] getMergedSubscriberIds() {
5573         try {
5574             ITelephony telephony = getITelephony();
5575             if (telephony != null)
5576                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
5577                         getAttributionTag());
5578         } catch (RemoteException ex) {
5579         } catch (NullPointerException ex) {
5580         }
5581         return null;
5582     }
5583 
5584     /**
5585      * Return the set of IMSIs that should be considered "merged together" for data usage
5586      * purposes. This API merges IMSIs based on subscription grouping: IMSI of those in the same
5587      * group will all be returned.
5588      * Return the current IMSI if there is no subscription group, see
5589      * {@link SubscriptionManager#createSubscriptionGroup(List)} for the definition of a group,
5590      * otherwise return an empty array if there is a failure.
5591      *
5592      * @throws UnsupportedOperationException If the device does not have
5593      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
5594      * @hide
5595      */
5596     @SystemApi
5597     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
5598     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getMergedImsisFromGroup()5599     public @NonNull String[] getMergedImsisFromGroup() {
5600         try {
5601             ITelephony telephony = getITelephony();
5602             if (telephony != null) {
5603                 String[] mergedImsisFromGroup =
5604                         telephony.getMergedImsisFromGroup(getSubId(), getOpPackageName());
5605                 if (mergedImsisFromGroup != null) {
5606                     return mergedImsisFromGroup;
5607                 }
5608             }
5609         } catch (RemoteException ex) {
5610         }
5611         return new String[0];
5612     }
5613 
5614     /**
5615      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
5616      *
5617      * <p>Requires Permission:
5618      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5619      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5620      *     that the caller is the default SMS app,
5621      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5622      *     for any API level.
5623      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5624      *     for apps targeting SDK API level 29 and below.
5625      *
5626      * @hide
5627      */
5628     @RequiresPermission(anyOf = {
5629             android.Manifest.permission.READ_PHONE_STATE,
5630             android.Manifest.permission.READ_SMS,
5631             android.Manifest.permission.READ_PHONE_NUMBERS
5632     })
5633     @UnsupportedAppUsage
getMsisdn()5634     public String getMsisdn() {
5635         return getMsisdn(getSubId());
5636     }
5637 
5638     /**
5639      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
5640      *
5641      * @param subId for which msisdn is returned
5642      *
5643      * <p>Requires Permission:
5644      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
5645      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
5646      *     that the caller is the default SMS app,
5647      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
5648      *     for any API level.
5649      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5650      *     for apps targeting SDK API level 29 and below.
5651      *
5652      * @hide
5653      */
5654     @RequiresPermission(anyOf = {
5655             android.Manifest.permission.READ_PHONE_STATE,
5656             android.Manifest.permission.READ_SMS,
5657             android.Manifest.permission.READ_PHONE_NUMBERS
5658     })
5659     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)5660     public String getMsisdn(int subId) {
5661         try {
5662             IPhoneSubInfo info = getSubscriberInfoService();
5663             if (info == null)
5664                 return null;
5665             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
5666         } catch (RemoteException ex) {
5667             return null;
5668         } catch (NullPointerException ex) {
5669             // This could happen before phone restarts due to crashing
5670             return null;
5671         }
5672     }
5673 
5674     /**
5675      * Returns the voice mail number. Return null if it is unavailable.
5676      *
5677      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5678      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5679      *
5680      * @throws UnsupportedOperationException If the device does not have
5681      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5682      */
5683     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5684     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5685     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceMailNumber()5686     public String getVoiceMailNumber() {
5687         return getVoiceMailNumber(getSubId());
5688     }
5689 
5690     /**
5691      * Returns the voice mail number for a subscription.
5692      * Return null if it is unavailable.
5693      * @param subId whose voice mail number is returned
5694      * @hide
5695      */
5696     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5697     @UnsupportedAppUsage
getVoiceMailNumber(int subId)5698     public String getVoiceMailNumber(int subId) {
5699         try {
5700             IPhoneSubInfo info = getSubscriberInfoService();
5701             if (info == null)
5702                 return null;
5703             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
5704                     getAttributionTag());
5705         } catch (RemoteException ex) {
5706             return null;
5707         } catch (NullPointerException ex) {
5708             // This could happen before phone restarts due to crashing
5709             return null;
5710         }
5711     }
5712 
5713     /**
5714      * Sets the voice mail number.
5715      *
5716      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5717      *
5718      * @param alphaTag The alpha tag to display.
5719      * @param number The voicemail number.
5720      *
5721      * @throws UnsupportedOperationException If the device does not have
5722      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5723      */
5724     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoiceMailNumber(String alphaTag, String number)5725     public boolean setVoiceMailNumber(String alphaTag, String number) {
5726         return setVoiceMailNumber(getSubId(), alphaTag, number);
5727     }
5728 
5729     /**
5730      * Sets the voicemail number for the given subscriber.
5731      *
5732      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5733      *
5734      * @param subId The subscription id.
5735      * @param alphaTag The alpha tag to display.
5736      * @param number The voicemail number.
5737      * @hide
5738      */
setVoiceMailNumber(int subId, String alphaTag, String number)5739     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
5740         try {
5741             ITelephony telephony = getITelephony();
5742             if (telephony != null)
5743                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
5744         } catch (RemoteException ex) {
5745         } catch (NullPointerException ex) {
5746         }
5747         return false;
5748     }
5749 
5750     /**
5751      * Enables or disables the visual voicemail client for a phone account.
5752      *
5753      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
5754      * {@link #hasCarrierPrivileges}), or has permission
5755      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
5756      *
5757      * @param phoneAccountHandle the phone account to change the client state
5758      * @param enabled the new state of the client
5759      * @hide
5760      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5761      * be implemented instead.
5762      */
5763     @SystemApi
5764     @Deprecated
5765     @SuppressLint("RequiresPermission")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)5766     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
5767     }
5768 
5769     /**
5770      * Returns whether the visual voicemail client is enabled.
5771      *
5772      * @param phoneAccountHandle the phone account to check for.
5773      * @return {@code true} when the visual voicemail client is enabled for this client
5774      * @hide
5775      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5776      * be implemented instead.
5777      */
5778     @SystemApi
5779     @Deprecated
5780     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5781     @SuppressLint("RequiresPermission")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)5782     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
5783         return false;
5784     }
5785 
5786     /**
5787      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
5788      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
5789      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
5790      * voicemail client in telephony.
5791      *
5792      * <p>Requires the caller to be the system dialer.
5793      *
5794      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
5795      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
5796      *
5797      * @throws UnsupportedOperationException If the device does not have
5798      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5799      * @hide
5800      */
5801     @SystemApi
5802     @SuppressLint("RequiresPermission")
5803     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
5804     @Nullable
getVisualVoicemailSettings()5805     public Bundle getVisualVoicemailSettings(){
5806         try {
5807             ITelephony telephony = getITelephony();
5808             if (telephony != null) {
5809                 return telephony
5810                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
5811             }
5812         } catch (RemoteException ex) {
5813         } catch (NullPointerException ex) {
5814         }
5815         return null;
5816     }
5817 
5818     /**
5819      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
5820      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
5821      * processing visual voicemail for the subscription.
5822      *
5823      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5824      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5825      *
5826      * @see #createForSubscriptionId(int)
5827      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
5828      * @see VisualVoicemailService
5829      *
5830      * @throws UnsupportedOperationException If the device does not have
5831      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5832      */
5833     @Nullable
5834     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5835     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5836     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVisualVoicemailPackageName()5837     public String getVisualVoicemailPackageName() {
5838         try {
5839             ITelephony telephony = getITelephony();
5840             if (telephony != null) {
5841                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
5842                         getAttributionTag(), getSubId());
5843             }
5844         } catch (RemoteException ex) {
5845         } catch (NullPointerException ex) {
5846         }
5847         return null;
5848     }
5849 
5850     /**
5851      * Set the visual voicemail SMS filter settings for the subscription ID pinned
5852      * to the TelephonyManager.
5853      * When the filter is enabled, {@link
5854      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
5855      * called when a SMS matching the settings is received. Caller must be the default dialer,
5856      * system dialer, or carrier visual voicemail app.
5857      *
5858      * @param settings The settings for the filter, or {@code null} to disable the filter.
5859      *
5860      * @see TelecomManager#getDefaultDialerPackage()
5861      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
5862      *
5863      * @throws UnsupportedOperationException If the device does not have
5864      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5865      */
5866     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)5867     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
5868         if (settings == null) {
5869             disableVisualVoicemailSmsFilter(mSubId);
5870         } else {
5871             enableVisualVoicemailSmsFilter(mSubId, settings);
5872         }
5873     }
5874 
5875     /**
5876      * Send a visual voicemail SMS. The caller must be the current default dialer.
5877      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
5878      * visual voicemail server.  Some examples for carriers using the OMTP standard include
5879      * activating and deactivating visual voicemail, or requesting the current visual voicemail
5880      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
5881      * format of these SMS messages.
5882      *
5883      * <p>Requires Permission:
5884      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
5885      *
5886      * @param number The destination number.
5887      * @param port The destination port for data SMS, or 0 for text SMS.
5888      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5889      * @param sentIntent The sent intent passed to the {@link SmsManager}
5890      *
5891      * @throws SecurityException if the caller is not the current default dialer
5892      *
5893      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5894      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5895      *
5896      * @throws UnsupportedOperationException If the device does not have
5897      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
5898      */
5899     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)5900     public void sendVisualVoicemailSms(String number, int port, String text,
5901             PendingIntent sentIntent) {
5902         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
5903     }
5904 
5905     /**
5906      * Enables the visual voicemail SMS filter for a phone account. When the filter is
5907      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
5908      * visual voicemail client with
5909      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
5910      *
5911      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5912      * settings persist through default dialer changes, but the filter will only honor the setting
5913      * set by the current default dialer.
5914      *
5915      *
5916      * @param subId The subscription id of the phone account.
5917      * @param settings The settings for the filter.
5918      */
5919     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)5920     public void enableVisualVoicemailSmsFilter(int subId,
5921             VisualVoicemailSmsFilterSettings settings) {
5922         if(settings == null){
5923             throw new IllegalArgumentException("Settings cannot be null");
5924         }
5925         try {
5926             ITelephony telephony = getITelephony();
5927             if (telephony != null) {
5928                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
5929                         settings);
5930             }
5931         } catch (RemoteException ex) {
5932         } catch (NullPointerException ex) {
5933         }
5934     }
5935 
5936     /**
5937      * Disables the visual voicemail SMS filter for a phone account.
5938      *
5939      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5940      * settings persist through default dialer changes, but the filter will only honor the setting
5941      * set by the current default dialer.
5942      */
5943     /** @hide */
disableVisualVoicemailSmsFilter(int subId)5944     public void disableVisualVoicemailSmsFilter(int subId) {
5945         try {
5946             ITelephony telephony = getITelephony();
5947             if (telephony != null) {
5948                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
5949             }
5950         } catch (RemoteException ex) {
5951         } catch (NullPointerException ex) {
5952         }
5953     }
5954 
5955     /**
5956      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
5957      * if the filter is disabled.
5958      *
5959      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5960      * settings persist through default dialer changes, but the filter will only honor the setting
5961      * set by the current default dialer.
5962      */
5963     /** @hide */
5964     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)5965     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
5966         try {
5967             ITelephony telephony = getITelephony();
5968             if (telephony != null) {
5969                 return telephony
5970                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
5971             }
5972         } catch (RemoteException ex) {
5973         } catch (NullPointerException ex) {
5974         }
5975 
5976         return null;
5977     }
5978 
5979     /**
5980      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
5981      * current active visual voicemail client, or {@code null} if the filter is disabled.
5982      *
5983      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
5984      */
5985     /** @hide */
5986     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)5987     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
5988         try {
5989             ITelephony telephony = getITelephony();
5990             if (telephony != null) {
5991                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
5992             }
5993         } catch (RemoteException ex) {
5994         } catch (NullPointerException ex) {
5995         }
5996 
5997         return null;
5998     }
5999 
6000     /**
6001      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
6002      *
6003      * @param phoneAccountHandle The account to send the SMS with.
6004      * @param number The destination number.
6005      * @param port The destination port for data SMS, or 0 for text SMS.
6006      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
6007      * @param sentIntent The sent intent passed to the {@link SmsManager}
6008      *
6009      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
6010      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
6011      *
6012      * @hide
6013      */
6014     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)6015     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
6016             String text, PendingIntent sentIntent) {
6017         try {
6018             ITelephony telephony = getITelephony();
6019             if (telephony != null) {
6020                 telephony.sendVisualVoicemailSmsForSubscriber(
6021                         mContext.getOpPackageName(), mContext.getAttributionTag(), subId, number,
6022                         port, text, sentIntent);
6023             }
6024         } catch (RemoteException ex) {
6025         }
6026     }
6027 
6028     /**
6029      * Initial SIM activation state, unknown. Not set by any carrier apps.
6030      * @hide
6031      */
6032     @SystemApi
6033     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
6034 
6035     /**
6036      * indicate SIM is under activation procedure now.
6037      * intermediate state followed by another state update with activation procedure result:
6038      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6039      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6040      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6041      * @hide
6042      */
6043     @SystemApi
6044     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
6045 
6046     /**
6047      * Indicate SIM has been successfully activated with full service
6048      * @hide
6049      */
6050     @SystemApi
6051     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
6052 
6053     /**
6054      * Indicate SIM has been deactivated by the carrier so that service is not available
6055      * and requires activation service to enable services.
6056      * Carrier apps could be signalled to set activation state to deactivated if detected
6057      * deactivated sim state and set it back to activated after successfully run activation service.
6058      * @hide
6059      */
6060     @SystemApi
6061     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
6062 
6063     /**
6064      * Restricted state indicate SIM has been activated but service are restricted.
6065      * note this is currently available for data activation state. For example out of byte sim.
6066      * @hide
6067      */
6068     @SystemApi
6069     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
6070 
6071      /**
6072       * Sets the voice activation state
6073       *
6074       * <p>Requires Permission:
6075       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
6076       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6077       *
6078       * @param activationState The voice activation state
6079       * @see #SIM_ACTIVATION_STATE_UNKNOWN
6080       * @see #SIM_ACTIVATION_STATE_ACTIVATING
6081       * @see #SIM_ACTIVATION_STATE_ACTIVATED
6082       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6083       *
6084       * @throws UnsupportedOperationException If the device does not have
6085       *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}
6086       * @hide
6087       */
6088     @SystemApi
6089     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
6090     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoiceActivationState(@imActivationState int activationState)6091     public void setVoiceActivationState(@SimActivationState int activationState) {
6092         setVoiceActivationState(getSubId(), activationState);
6093     }
6094 
6095     /**
6096      * Sets the voice activation state for the given subscriber.
6097      *
6098      * <p>Requires Permission:
6099      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
6100      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6101      *
6102      * @param subId The subscription id.
6103      * @param activationState The voice activation state of the given subscriber.
6104      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6105      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6106      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6107      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6108      * @hide
6109      */
6110     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)6111     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
6112         try {
6113            ITelephony telephony = getITelephony();
6114            if (telephony != null)
6115                telephony.setVoiceActivationState(subId, activationState);
6116        } catch (RemoteException ex) {
6117        } catch (NullPointerException ex) {
6118        }
6119     }
6120 
6121     /**
6122      * Sets the data activation state
6123      *
6124      * <p>Requires Permission:
6125      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
6126      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6127      *
6128      * @param activationState The data activation state
6129      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6130      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6131      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6132      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6133      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6134      *
6135      * @throws UnsupportedOperationException If the device does not have
6136      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6137      * @hide
6138      */
6139     @SystemApi
6140     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
6141     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataActivationState(@imActivationState int activationState)6142     public void setDataActivationState(@SimActivationState int activationState) {
6143         setDataActivationState(getSubId(), activationState);
6144     }
6145 
6146     /**
6147      * Sets the data activation state for the given subscriber.
6148      *
6149      * <p>Requires Permission:
6150      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
6151      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6152      *
6153      * @param subId The subscription id.
6154      * @param activationState The data activation state of the given subscriber.
6155      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6156      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6157      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6158      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6159      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6160      * @hide
6161      */
6162     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)6163     public void setDataActivationState(int subId, @SimActivationState int activationState) {
6164         try {
6165             ITelephony telephony = getITelephony();
6166             if (telephony != null)
6167                 telephony.setDataActivationState(subId, activationState);
6168         } catch (RemoteException ex) {
6169         } catch (NullPointerException ex) {
6170         }
6171     }
6172 
6173     /**
6174      * Returns the voice activation state
6175      *
6176      * <p>Requires Permission:
6177      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6178      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6179      *
6180      * @return voiceActivationState
6181      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6182      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6183      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6184      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6185      *
6186      * @throws UnsupportedOperationException If the device does not have
6187      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6188      * @hide
6189      */
6190     @SystemApi
6191     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6192     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceActivationState()6193     public @SimActivationState int getVoiceActivationState() {
6194         return getVoiceActivationState(getSubId());
6195     }
6196 
6197     /**
6198      * Returns the voice activation state for the given subscriber.
6199      *
6200      * <p>Requires Permission:
6201      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6202      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6203      *
6204      * @param subId The subscription id.
6205      *
6206      * @return voiceActivationState for the given subscriber
6207      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6208      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6209      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6210      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6211      * @hide
6212      */
6213     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)6214     public @SimActivationState int getVoiceActivationState(int subId) {
6215         try {
6216             ITelephony telephony = getITelephony();
6217             if (telephony != null)
6218                 return telephony.getVoiceActivationState(subId, getOpPackageName());
6219         } catch (RemoteException ex) {
6220         } catch (NullPointerException ex) {
6221         }
6222         return SIM_ACTIVATION_STATE_UNKNOWN;
6223     }
6224 
6225     /**
6226      * Returns the data activation state
6227      *
6228      * <p>Requires Permission:
6229      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6230      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6231      *
6232      * @return dataActivationState for the given subscriber
6233      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6234      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6235      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6236      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6237      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6238      *
6239      * @throws UnsupportedOperationException If the device does not have
6240      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6241      * @hide
6242      */
6243     @SystemApi
6244     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6245     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataActivationState()6246     public @SimActivationState int getDataActivationState() {
6247         return getDataActivationState(getSubId());
6248     }
6249 
6250     /**
6251      * Returns the data activation state for the given subscriber.
6252      *
6253      * <p>Requires Permission:
6254      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6255      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6256      *
6257      * @param subId The subscription id.
6258      *
6259      * @return dataActivationState for the given subscriber
6260      * @see #SIM_ACTIVATION_STATE_UNKNOWN
6261      * @see #SIM_ACTIVATION_STATE_ACTIVATING
6262      * @see #SIM_ACTIVATION_STATE_ACTIVATED
6263      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
6264      * @see #SIM_ACTIVATION_STATE_RESTRICTED
6265      * @hide
6266      */
6267     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)6268     public @SimActivationState int getDataActivationState(int subId) {
6269         try {
6270             ITelephony telephony = getITelephony();
6271             if (telephony != null)
6272                 return telephony.getDataActivationState(subId, getOpPackageName());
6273         } catch (RemoteException ex) {
6274         } catch (NullPointerException ex) {
6275         }
6276         return SIM_ACTIVATION_STATE_UNKNOWN;
6277     }
6278 
6279     /**
6280      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
6281      * but the count is unknown.
6282      * @hide
6283      */
6284     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6285     @UnsupportedAppUsage
getVoiceMessageCount()6286     public int getVoiceMessageCount() {
6287         return getVoiceMessageCount(getSubId());
6288     }
6289 
6290     /**
6291      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
6292      * not have the READ_PHONE_STATE permission.
6293      * @param subId whose voice message count is returned
6294      * @hide
6295      */
6296     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6297     @UnsupportedAppUsage
getVoiceMessageCount(int subId)6298     public int getVoiceMessageCount(int subId) {
6299         try {
6300             ITelephony telephony = getITelephony();
6301             if (telephony == null)
6302                 return 0;
6303             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
6304                     getAttributionTag());
6305         } catch (RemoteException ex) {
6306             return 0;
6307         } catch (NullPointerException ex) {
6308             // This could happen before phone restarts due to crashing
6309             return 0;
6310         }
6311     }
6312 
6313     /**
6314      * Retrieves the alphabetic identifier associated with the voice
6315      * mail number.
6316      *
6317      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
6318      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
6319      *
6320      * @throws UnsupportedOperationException If the device does not have
6321      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6322      */
6323     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
6324     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6325     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoiceMailAlphaTag()6326     public String getVoiceMailAlphaTag() {
6327         return getVoiceMailAlphaTag(getSubId());
6328     }
6329 
6330     /**
6331      * Retrieves the alphabetic identifier associated with the voice
6332      * mail number for a subscription.
6333      * @param subId whose alphabetic identifier associated with the
6334      * voice mail number is returned
6335      * @hide
6336      */
6337     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6338     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)6339     public String getVoiceMailAlphaTag(int subId) {
6340         try {
6341             IPhoneSubInfo info = getSubscriberInfoService();
6342             if (info == null)
6343                 return null;
6344             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
6345                     getAttributionTag());
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      * Send the special dialer code. The IPC caller must be the current default dialer or have
6356      * carrier privileges (see {@link #hasCarrierPrivileges}).
6357      *
6358      * @param inputCode The special dialer code to send
6359      *
6360      * @throws SecurityException if the caller does not have carrier privileges or is not the
6361      *         current default dialer
6362      * @throws UnsupportedOperationException If the device does not have
6363      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6364      */
6365     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
sendDialerSpecialCode(String inputCode)6366     public void sendDialerSpecialCode(String inputCode) {
6367         try {
6368             final ITelephony telephony = getITelephony();
6369             if (telephony == null) {
6370                 return;
6371             }
6372             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
6373         } catch (RemoteException ex) {
6374             Rlog.e(TAG, "Telephony#sendDialerSpecialCode RemoteException" + ex);
6375         }
6376     }
6377 
6378     /**
6379      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
6380      * @return the IMPI, or null if not present or not loaded
6381      * @hide
6382      * @deprecated use {@link #getImsPrivateUserIdentity()}
6383      */
6384     @UnsupportedAppUsage
6385     @Deprecated
getIsimImpi()6386     public String getIsimImpi() {
6387         try {
6388             IPhoneSubInfo info = getSubscriberInfoService();
6389             if (info == null)
6390                 return null;
6391             //get the Isim Impi based on subId
6392             return info.getIsimImpi(getSubId());
6393         } catch (RemoteException ex) {
6394             return null;
6395         } catch (NullPointerException ex) {
6396             // This could happen before phone restarts due to crashing
6397             return null;
6398         }
6399     }
6400 
6401     /**
6402      * Returns the IMS private user identity (IMPI) of the subscription that was loaded from the
6403      * ISIM records {@link #APPTYPE_ISIM}. This value is fetched from the Elementary file EF_IMPI.
6404      * The contents of the file is a <b>Ip Multimedia Service Private User Identity</b> of the user
6405      * as defined in the section 4.2.2 of 3GPP TS 131 103.
6406      *
6407      * @return IMPI (IMS private user identity) of type string or null if the IMPI isn't present
6408      *         on the ISIM.
6409      * @throws IllegalStateException in case the ISIM has’t been loaded
6410      * @throws SecurityException if the caller does not have the required permission/privileges
6411      * @hide
6412      */
6413     @FlaggedApi(Flags.FLAG_SUPPORT_ISIM_RECORD)
6414     @SystemApi
6415     @RequiresPermission(android.Manifest.permission.USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER)
6416     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
6417     @Nullable
getImsPrivateUserIdentity()6418     public String getImsPrivateUserIdentity() {
6419         try {
6420             IPhoneSubInfo info = getSubscriberInfoService();
6421             if (info == null) {
6422                 Rlog.e(TAG, "getImsPrivateUserIdentity(): IPhoneSubInfo instance is NULL");
6423                 throw new RuntimeException("IMPI error: Subscriber Info is null");
6424             }
6425             return info.getImsPrivateUserIdentity(getSubId(), getOpPackageName(),
6426                     getAttributionTag());
6427         } catch (RemoteException | NullPointerException | IllegalArgumentException ex) {
6428             Rlog.e(TAG, "getImsPrivateUserIdentity() Exception = " + ex);
6429             throw new RuntimeException(ex.getMessage());
6430         }
6431     }
6432 
6433     /**
6434      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
6435      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
6436      * hasn't been loaded or isn't present on the ISIM.
6437      *
6438      * <p>Requires Permission:
6439      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
6440      *
6441      * @throws UnsupportedOperationException If the device does not have
6442      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
6443      * @hide
6444      */
6445     @Nullable
6446     @SystemApi
6447     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6448     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIsimDomain()6449     public String getIsimDomain() {
6450         try {
6451             IPhoneSubInfo info = getSubscriberInfoService();
6452             if (info == null)
6453                 return null;
6454             //get the Isim Domain based on subId
6455             return info.getIsimDomain(getSubId());
6456         } catch (RemoteException ex) {
6457             return null;
6458         } catch (NullPointerException ex) {
6459             // This could happen before phone restarts due to crashing
6460             return null;
6461         }
6462     }
6463 
6464     /**
6465      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
6466      * @return an array of IMPU strings, with one IMPU per string, or null if
6467      *      not present or not loaded
6468      *
6469      * @throws UnsupportedOperationException If the device does not have
6470      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
6471      * @hide
6472      * @deprecated use {@link #getImsPublicUserIdentities()}
6473      */
6474     @UnsupportedAppUsage
6475     @Deprecated
6476     @Nullable
6477     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()6478     public String[] getIsimImpu() {
6479         try {
6480             IPhoneSubInfo info = getSubscriberInfoService();
6481             if (info == null)
6482                 return null;
6483             //get the Isim Impu based on subId
6484             return info.getIsimImpu(getSubId());
6485         } catch (RemoteException ex) {
6486             return null;
6487         } catch (NullPointerException ex) {
6488             // This could happen before phone restarts due to crashing
6489             return null;
6490         }
6491     }
6492 
6493     /**
6494      * Returns the IMS public user identities (IMPU) of the subscription that was loaded from the
6495      * ISIM records {@link #APPTYPE_ISIM}. This value is fetched from the Elementary file EF_IMPU.
6496      * The contents of the file are <b>Ip Multimedia Service Public User Identities</b> of the user
6497      * as defined in the section 4.2.4 of 3GPP TS 131 103. It contains one or more records.
6498      *
6499      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission or carrier
6500      * privileges.
6501      *
6502      * @return List of public user identities of type android.net.Uri or empty list  if
6503      *         EF_IMPU is not available.
6504      * @throws IllegalStateException in case the ISIM hasn’t been loaded
6505      * @throws SecurityException if the caller does not have the required permission/privilege
6506      * @throws UnsupportedOperationException If the device does not have
6507      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
6508      * @hide
6509      */
6510     @FlaggedApi(Flags.FLAG_SUPPORT_ISIM_RECORD)
6511     @SystemApi
6512     @RequiresPermission(value = Manifest.permission.READ_PRIVILEGED_PHONE_STATE, conditional = true)
6513     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
6514     @NonNull
getImsPublicUserIdentities()6515     public List<Uri> getImsPublicUserIdentities() {
6516         try {
6517             IPhoneSubInfo info = getSubscriberInfoService();
6518             if (info == null) {
6519                 throw new RuntimeException("IMPU error: Subscriber Info is null");
6520             }
6521             return info.getImsPublicUserIdentities(getSubId(), getOpPackageName());
6522         } catch (IllegalArgumentException | NullPointerException ex) {
6523             Rlog.e(TAG, "getImsPublicUserIdentities Exception = " + ex);
6524         } catch (RemoteException ex) {
6525             Rlog.e(TAG, "getImsPublicUserIdentities Exception = " + ex);
6526             ex.rethrowAsRuntimeException();
6527         }
6528         return Collections.EMPTY_LIST;
6529     }
6530 
6531     /**
6532      * Device call state: No activity.
6533      */
6534     public static final int CALL_STATE_IDLE = 0;
6535     /**
6536      * Device call state: Ringing. A new call arrived and is
6537      *  ringing or waiting. In the latter case, another call is
6538      *  already active.
6539      */
6540     public static final int CALL_STATE_RINGING = 1;
6541     /**
6542      * Device call state: Off-hook. At least one call exists
6543      * that is dialing, active, or on hold, and no calls are ringing
6544      * or waiting.
6545      */
6546     public static final int CALL_STATE_OFFHOOK = 2;
6547 
6548     /**
6549      * Returns the state of all calls on the device.
6550      * <p>
6551      * This method considers not only calls in the Telephony stack, but also calls via other
6552      * {@link android.telecom.ConnectionService} implementations.
6553      * <p>
6554      * Note: The call state returned via this method may differ from what is reported by {@link
6555      * TelephonyCallback.CallStateListener#onCallStateChanged(int)}, as that callback only considers
6556      * Telephony (mobile) calls.
6557      * <p>
6558      * Requires Permission:
6559      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
6560      * targeting API level 31+.
6561      *
6562      * @return the current call state.
6563      * @deprecated Use {@link #getCallStateForSubscription} to retrieve the call state for a
6564      * specific telephony subscription (which allows carrier privileged apps),
6565      * {@link TelephonyCallback.CallStateListener} for real-time call state updates, or
6566      * {@link TelecomManager#isInCall()}, which supplies an aggregate "in call" state for the entire
6567      * device.
6568      */
6569     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
6570     @Deprecated
getCallState()6571     public @CallState int getCallState() {
6572         if (mContext != null) {
6573             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
6574             if (telecomManager != null) {
6575                 return telecomManager.getCallState();
6576             }
6577         }
6578         return CALL_STATE_IDLE;
6579     }
6580 
6581     /**
6582      * Retrieve the call state for a specific subscription that was specified when this
6583      * TelephonyManager instance was created.
6584      * <p>Requires Permission:
6585      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the calling
6586      * application has carrier privileges (see {@link #hasCarrierPrivileges}).
6587      * @see TelephonyManager#createForSubscriptionId(int)
6588      * @see TelephonyManager#createForPhoneAccountHandle(PhoneAccountHandle)
6589      * @return The call state of the subscription associated with this TelephonyManager instance.
6590      *
6591      * @throws UnsupportedOperationException If the device does not have
6592      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
6593      */
6594     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6595     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallStateForSubscription()6596     public @CallState int getCallStateForSubscription() {
6597         return getCallState(getSubId());
6598     }
6599 
6600     /**
6601      * Returns the Telephony call state for calls on a specific subscription.
6602      * <p>
6603      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
6604      * considers the state of calls from other {@link android.telecom.ConnectionService}
6605      * implementations.
6606      * <p>
6607      * Requires Permission:
6608      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
6609      * targeting API level 31+ or that the calling application has carrier privileges
6610      * (see {@link #hasCarrierPrivileges()}).
6611      *
6612      * @param subId the subscription to check call state for.
6613      * @hide
6614      */
6615     @UnsupportedAppUsage
6616     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
getCallState(int subId)6617     public @CallState int getCallState(int subId) {
6618         ITelephony telephony = getITelephony();
6619         if (telephony == null) {
6620             return CALL_STATE_IDLE;
6621         }
6622         try {
6623             return telephony.getCallStateForSubscription(subId, mContext.getPackageName(),
6624                     mContext.getAttributionTag());
6625         } catch (RemoteException e) {
6626             return CALL_STATE_IDLE;
6627         }
6628     }
6629 
6630     /** Data connection activity: No traffic. */
6631     public static final int DATA_ACTIVITY_NONE = 0x00000000;
6632     /** Data connection activity: Currently receiving IP PPP traffic. */
6633     public static final int DATA_ACTIVITY_IN = 0x00000001;
6634     /** Data connection activity: Currently sending IP PPP traffic. */
6635     public static final int DATA_ACTIVITY_OUT = 0x00000002;
6636     /** Data connection activity: Currently both sending and receiving
6637      *  IP PPP traffic. */
6638     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
6639     /**
6640      * Data connection is active, but physical link is down
6641      */
6642     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
6643 
6644     /**
6645      * Returns a constant indicating the type of activity on a data connection
6646      * (cellular).
6647      *
6648      * @see #DATA_ACTIVITY_NONE
6649      * @see #DATA_ACTIVITY_IN
6650      * @see #DATA_ACTIVITY_OUT
6651      * @see #DATA_ACTIVITY_INOUT
6652      * @see #DATA_ACTIVITY_DORMANT
6653      *
6654      * @throws UnsupportedOperationException If the device does not have
6655      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6656      */
6657     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataActivity()6658     public int getDataActivity() {
6659         try {
6660             ITelephony telephony = getITelephony();
6661             if (telephony == null)
6662                 return DATA_ACTIVITY_NONE;
6663             return telephony.getDataActivityForSubId(
6664                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
6665         } catch (RemoteException ex) {
6666             // the phone process is restarting.
6667             return DATA_ACTIVITY_NONE;
6668         } catch (NullPointerException ex) {
6669           // the phone process is restarting.
6670           return DATA_ACTIVITY_NONE;
6671       }
6672     }
6673 
6674     /** @hide */
6675     @IntDef(prefix = {"DATA_"}, value = {
6676             DATA_UNKNOWN,
6677             DATA_DISCONNECTED,
6678             DATA_CONNECTING,
6679             DATA_CONNECTED,
6680             DATA_SUSPENDED,
6681             DATA_DISCONNECTING,
6682             DATA_HANDOVER_IN_PROGRESS,
6683     })
6684     @Retention(RetentionPolicy.SOURCE)
6685     public @interface DataState{}
6686 
6687     /** Data connection state: Unknown.  Used before we know the state. */
6688     public static final int DATA_UNKNOWN        = -1;
6689     /** Data connection state: Disconnected. IP traffic not available. */
6690     public static final int DATA_DISCONNECTED   = 0;
6691     /** Data connection state: Currently setting up a data connection. */
6692     public static final int DATA_CONNECTING     = 1;
6693     /** Data connection state: Connected. IP traffic should be available. */
6694     public static final int DATA_CONNECTED      = 2;
6695     /** Data connection state: Suspended. The connection is up, but IP
6696      * traffic is temporarily unavailable. For example, in a 2G network,
6697      * data activity may be suspended when a voice call arrives. */
6698     public static final int DATA_SUSPENDED      = 3;
6699     /**
6700      * Data connection state: Disconnecting.
6701      *
6702      * IP traffic may be available but will cease working imminently.
6703      */
6704     public static final int DATA_DISCONNECTING = 4;
6705 
6706     /**
6707      * Data connection state: Handover in progress. The connection is being transited from cellular
6708      * network to IWLAN, or from IWLAN to cellular network.
6709      */
6710     public static final int DATA_HANDOVER_IN_PROGRESS = 5;
6711 
6712     /**
6713      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
6714      */
6715     @ChangeId
6716     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
6717     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
6718 
6719     /**
6720      * Returns a constant indicating the current data connection state
6721      * (cellular).
6722      *
6723      * @see #DATA_DISCONNECTED
6724      * @see #DATA_CONNECTING
6725      * @see #DATA_CONNECTED
6726      * @see #DATA_SUSPENDED
6727      * @see #DATA_DISCONNECTING
6728      * @see #DATA_HANDOVER_IN_PROGRESS
6729      *
6730      * @throws UnsupportedOperationException If the device does not have
6731      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
6732      */
6733     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataState()6734     public int getDataState() {
6735         try {
6736             ITelephony telephony = getITelephony();
6737             if (telephony == null)
6738                 return DATA_DISCONNECTED;
6739             int state = telephony.getDataStateForSubId(
6740                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
6741             if (state == TelephonyManager.DATA_DISCONNECTING
6742                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
6743                 return TelephonyManager.DATA_CONNECTED;
6744             }
6745 
6746             return state;
6747         } catch (RemoteException ex) {
6748             // the phone process is restarting.
6749             return DATA_DISCONNECTED;
6750         } catch (NullPointerException ex) {
6751             return DATA_DISCONNECTED;
6752         }
6753     }
6754 
getITelephony()6755     private static ITelephony getITelephony() {
6756         // Keeps cache disabled until test fixes are checked into AOSP.
6757         if (!sServiceHandleCacheEnabled) {
6758             return ITelephony.Stub.asInterface(
6759                     TelephonyFrameworkInitializer
6760                             .getTelephonyServiceManager()
6761                             .getTelephonyServiceRegisterer()
6762                             .get());
6763         }
6764 
6765         if (sITelephony == null) {
6766             ITelephony temp = ITelephony.Stub.asInterface(
6767                     TelephonyFrameworkInitializer
6768                             .getTelephonyServiceManager()
6769                             .getTelephonyServiceRegisterer()
6770                             .get());
6771             synchronized (sCacheLock) {
6772                 if (sITelephony == null && temp != null) {
6773                     try {
6774                         sITelephony = temp;
6775                         sITelephony.asBinder().linkToDeath(sServiceDeath, 0);
6776                     } catch (Exception e) {
6777                         // something has gone horribly wrong
6778                         sITelephony = null;
6779                     }
6780                 }
6781             }
6782         }
6783         return sITelephony;
6784     }
6785 
getIOns()6786     private IOns getIOns() {
6787         return IOns.Stub.asInterface(
6788                 TelephonyFrameworkInitializer
6789                         .getTelephonyServiceManager()
6790                         .getOpportunisticNetworkServiceRegisterer()
6791                         .get());
6792     }
6793 
6794     //
6795     //
6796     // PhoneStateListener
6797     //
6798     //
6799 
6800     /**
6801      * Registers a listener object to receive notification of changes
6802      * in specified telephony states.
6803      * <p>
6804      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
6805      * state of interest in the events argument.
6806      *
6807      * At registration, and when a specified telephony state changes, the telephony manager invokes
6808      * the appropriate callback method on the listener object and passes the current (updated)
6809      * values.
6810      * <p>
6811      * To un-register a listener, pass the listener object and set the events argument to
6812      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
6813      *
6814      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
6815      * applies to the given subId. Otherwise, applies to
6816      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
6817      * pass a separate listener object to each TelephonyManager object created with
6818      * {@link #createForSubscriptionId}.
6819      *
6820      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
6821      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
6822      * {@link SecurityException} will be thrown otherwise.
6823      *
6824      * This API should be used sparingly -- large numbers of listeners will cause system
6825      * instability. If a process has registered too many listeners without unregistering them, it
6826      * may encounter an {@link IllegalStateException} when trying to register more listeners.
6827      *
6828      * @param listener The {@link PhoneStateListener} object to register
6829      *                 (or unregister)
6830      * @param events The telephony state(s) of interest to the listener,
6831      *               as a bitwise-OR combination of {@link PhoneStateListener}
6832      *               LISTEN_ flags.
6833      * @deprecated Use {@link #registerTelephonyCallback(Executor, TelephonyCallback)}.
6834      */
6835     @Deprecated
listen(PhoneStateListener listener, int events)6836     public void listen(PhoneStateListener listener, int events) {
6837         if (mContext == null) return;
6838         boolean notifyNow = (getITelephony() != null);
6839         TelephonyRegistryManager telephonyRegistry =
6840                 (TelephonyRegistryManager)
6841                         mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
6842         if (telephonyRegistry != null) {
6843             Set<String> renouncedPermissions = getRenouncedPermissions();
6844             boolean renounceFineLocationAccess = renouncedPermissions
6845                     .contains(Manifest.permission.ACCESS_FINE_LOCATION);
6846             boolean renounceCoarseLocationAccess = renouncedPermissions
6847                     .contains(Manifest.permission.ACCESS_COARSE_LOCATION);
6848             telephonyRegistry.listenFromListener(mSubId, renounceFineLocationAccess,
6849                     renounceCoarseLocationAccess, getOpPackageName(), getAttributionTag(),
6850                     listener, events, notifyNow);
6851         } else {
6852             Rlog.w(TAG, "telephony registry not ready.");
6853         }
6854     }
6855 
6856     /** @hide
6857      * @deprecated Legacy CDMA is unsupported.
6858      */
6859     @Deprecated
6860     @Retention(RetentionPolicy.SOURCE)
6861     @IntDef(prefix = {"ERI_"}, value = {
6862             -1,
6863             ERI_ON,
6864             ERI_OFF,
6865             ERI_FLASH
6866     })
6867     public @interface EriIconIndex {}
6868 
6869     /**
6870      * ERI (Enhanced Roaming Indicator) is ON i.e value 0 defined by
6871      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6872      * @deprecated Legacy CDMA is unsupported.
6873      */
6874     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
6875     @Deprecated
6876     public static final int ERI_ON = 0;
6877 
6878     /**
6879      * ERI (Enhanced Roaming Indicator) is OFF i.e value 1 defined by
6880      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6881      * @deprecated Legacy CDMA is unsupported.
6882      */
6883     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
6884     @Deprecated
6885     public static final int ERI_OFF = 1;
6886 
6887     /**
6888      * ERI (Enhanced Roaming Indicator) is FLASH i.e value 2 defined by
6889      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6890      * @deprecated Legacy CDMA is unsupported.
6891      */
6892     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
6893     @Deprecated
6894     public static final int ERI_FLASH = 2;
6895 
6896     /** @hide
6897      * @deprecated Legacy CDMA is unsupported.
6898      */
6899     @Deprecated
6900     @Retention(RetentionPolicy.SOURCE)
6901     @IntDef(prefix = {"ERI_ICON_MODE_"}, value = {
6902             -1,
6903             ERI_ICON_MODE_NORMAL,
6904             ERI_ICON_MODE_FLASH
6905     })
6906     public @interface EriIconMode {}
6907 
6908     /**
6909      * ERI (Enhanced Roaming Indicator) icon mode is normal. This constant represents that
6910      * the ERI icon should be displayed normally.
6911      *
6912      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6913      * @hide
6914      * @deprecated Legacy CDMA is unsupported.
6915      */
6916     @Deprecated
6917     public static final int ERI_ICON_MODE_NORMAL = 0;
6918 
6919     /**
6920      * ERI (Enhanced Roaming Indicator) icon mode flash. This constant represents that
6921      * the ERI icon should be flashing.
6922      *
6923      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6924      * @hide
6925      * @deprecated Legacy CDMA is unsupported.
6926      */
6927     @Deprecated
6928     public static final int ERI_ICON_MODE_FLASH = 1;
6929 
6930     /**
6931      * Returns the CDMA ERI icon display number. The number is assigned by
6932      * 3GPP2 C.R1001-H v1.0 Table 8.1-1. Additionally carriers define their own ERI display numbers.
6933      * Defined values are {@link #ERI_ON}, {@link #ERI_OFF}, and {@link #ERI_FLASH}.
6934      *
6935      * @deprecated Legacy CDMA is unsupported.
6936      * @throws UnsupportedOperationException If the device does not have
6937      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
6938      * @hide
6939      */
6940     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
6941     @Deprecated
6942     @SystemApi
6943     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6944     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaEnhancedRoamingIndicatorDisplayNumber()6945     public @EriIconIndex int getCdmaEnhancedRoamingIndicatorDisplayNumber() {
6946         if (Flags.cleanupCdma()) return -1;
6947         return getCdmaEriIconIndex(getSubId());
6948     }
6949 
6950     /**
6951      * Returns the CDMA ERI icon index to display for a subscription.
6952      * @deprecated Legacy CDMA is unsupported.
6953      * @hide
6954      */
6955     @Deprecated
6956     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6957     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)6958     public @EriIconIndex int getCdmaEriIconIndex(int subId) {
6959         if (Flags.cleanupCdma()) return -1;
6960         try {
6961             ITelephony telephony = getITelephony();
6962             if (telephony == null)
6963                 return -1;
6964             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
6965                     getAttributionTag());
6966         } catch (RemoteException ex) {
6967             // the phone process is restarting.
6968             return -1;
6969         } catch (NullPointerException ex) {
6970             return -1;
6971         }
6972     }
6973 
6974     /**
6975      * Returns the CDMA ERI icon mode for a subscription.
6976      * 0 - ON
6977      * 1 - FLASHING
6978      *
6979      * @deprecated Legacy CDMA is unsupported.
6980      * @hide
6981      */
6982     @Deprecated
6983     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6984     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)6985     public @EriIconMode int getCdmaEriIconMode(int subId) {
6986         if (Flags.cleanupCdma()) return -1;
6987         try {
6988             ITelephony telephony = getITelephony();
6989             if (telephony == null)
6990                 return -1;
6991             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
6992                     getAttributionTag());
6993         } catch (RemoteException ex) {
6994             // the phone process is restarting.
6995             return -1;
6996         } catch (NullPointerException ex) {
6997             return -1;
6998         }
6999     }
7000 
7001     /**
7002      * Returns the CDMA ERI text,
7003      *
7004      * @deprecated Legacy CDMA is unsupported.
7005      * @hide
7006      */
7007     @Deprecated
7008     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()7009     public String getCdmaEriText() {
7010         if (Flags.cleanupCdma()) return null;
7011         return getCdmaEriText(getSubId());
7012     }
7013 
7014     /**
7015      * Returns the CDMA ERI text, of a subscription
7016      *
7017      * @deprecated Legacy CDMA is unsupported.
7018      * @hide
7019      */
7020     @Deprecated
7021     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
7022     @UnsupportedAppUsage
getCdmaEriText(int subId)7023     public String getCdmaEriText(int subId) {
7024         if (Flags.cleanupCdma()) return null;
7025         try {
7026             ITelephony telephony = getITelephony();
7027             if (telephony == null)
7028                 return null;
7029             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
7030                     getAttributionTag());
7031         } catch (RemoteException ex) {
7032             // the phone process is restarting.
7033             return null;
7034         } catch (NullPointerException ex) {
7035             return null;
7036         }
7037     }
7038 
7039     // Suppressing AndroidFrameworkCompatChange because we're querying vendor
7040     // partition SDK level, not application's target SDK version.
7041     @SuppressWarnings("AndroidFrameworkCompatChange")
hasCapability(@onNull String feature, @BoolRes int legacySetting)7042     private boolean hasCapability(@NonNull String feature, @BoolRes int legacySetting) {
7043         if (mContext == null) return true;
7044 
7045         if (mContext.getPackageManager().hasSystemFeature(feature)) return true;
7046 
7047         // Check SDK version of the vendor partition.
7048         final int vendorApiLevel = SystemProperties.getInt(
7049                 "ro.vendor.api_level", Build.VERSION.DEVICE_INITIAL_SDK_INT);
7050         // Devices shipped with 2024Q2 or later are required to declare FEATURE_TELEPHONY_*
7051         // for individual sub-features (calling, messaging, data), so there's no need to check
7052         // the legacy setting.
7053         if (vendorApiLevel < Build.VENDOR_API_2024_Q2) {
7054             return mContext.getResources().getBoolean(legacySetting);
7055         }
7056         return false;
7057     }
7058 
7059     /**
7060      * @return true if the current device is "voice capable".
7061      * <p>
7062      * "Voice capable" means that this device supports circuit-switched
7063      * (i.e. voice) phone calls over the telephony network, and is allowed
7064      * to display the in-call UI while a cellular voice call is active.
7065      * This will be false on "data only" devices which can't make voice
7066      * calls and don't support any in-call UI.
7067      * <p>
7068      * Note: the meaning of this flag is subtly different from the
7069      * PackageManager.FEATURE_TELEPHONY system feature, which is available
7070      * on any device with a telephony radio, even if the device is
7071      * data-only.
7072      * @deprecated Replaced by {@link #isDeviceVoiceCapable()}. Starting from Android 15, voice
7073      * capability may also be overridden by carriers for a given subscription. For voice capable
7074      * device (when {@link #isDeviceVoiceCapable} return {@code true}), caller should check for
7075      * subscription-level voice capability as well. See {@link #isDeviceVoiceCapable} for details.
7076      */
7077     @Deprecated
isVoiceCapable()7078     public boolean isVoiceCapable() {
7079         if (mContext == null) return true;
7080         return mContext.getResources().getBoolean(
7081                 com.android.internal.R.bool.config_voice_capable);
7082     }
7083 
7084     /**
7085      * @return true if the current device is "voice capable".
7086      * <p>
7087      * "Voice capable" means that this device supports circuit-switched or IMS packet switched
7088      * (i.e. voice) phone calls over the telephony network, and is allowed to display the in-call
7089      * UI while a cellular voice call is active. This will be false on "data only" devices which
7090      * can't make voice calls and don't support any in-call UI.
7091      * <p>
7092      * Note: the meaning of this flag is subtly different from the PackageManager
7093      * .FEATURE_TELEPHONY system feature, which is available on any device with a telephony
7094      * radio, even if the device is data-only.
7095      * <p>
7096      * Starting from Android 15, voice capability may also be overridden by carrier for a given
7097      * subscription on a voice capable device. To check if a subscription is "voice capable",
7098      * call method {@link SubscriptionInfo#getServiceCapabilities()} and check if
7099      * {@link SubscriptionManager#SERVICE_CAPABILITY_VOICE} is included.
7100      *
7101      * @see SubscriptionInfo#getServiceCapabilities()
7102      */
isDeviceVoiceCapable()7103     public boolean isDeviceVoiceCapable() {
7104         return hasCapability(PackageManager.FEATURE_TELEPHONY_CALLING,
7105                 com.android.internal.R.bool.config_voice_capable);
7106     }
7107 
7108     /**
7109      * @return true if the current device supports sms service.
7110      * <p>
7111      * If true, this means that the device supports both sending and
7112      * receiving sms via the telephony network.
7113      * <p>
7114      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
7115      *       disabled when device doesn't support sms.
7116      * @deprecated Replaced by {@link #isDeviceSmsCapable()}. Starting from Android 15, SMS
7117      * capability may also be overridden by carriers for a given subscription. For SMS capable
7118      * device (when {@link #isDeviceSmsCapable} return {@code true}), caller should check for
7119      * subscription-level SMS capability as well. See {@link #isDeviceSmsCapable} for details.
7120      */
7121     @Deprecated
isSmsCapable()7122     public boolean isSmsCapable() {
7123         return hasCapability(PackageManager.FEATURE_TELEPHONY_MESSAGING,
7124                 com.android.internal.R.bool.config_sms_capable);
7125     }
7126 
7127     /**
7128      * @return true if the current device supports SMS service.
7129      * <p>
7130      * If true, this means that the device supports both sending and
7131      * receiving SMS via the telephony network.
7132      * <p>
7133      * Note: Voicemail waiting SMS, cell broadcasting SMS, and MMS are
7134      *       disabled when device doesn't support SMS.
7135      * <p>
7136      * Starting from Android 15, SMS capability may also be overridden by carriers for a given
7137      * subscription on an SMS capable device. To check if a subscription is "SMS capable",
7138      * call method {@link SubscriptionInfo#getServiceCapabilities()} and check if
7139      * {@link SubscriptionManager#SERVICE_CAPABILITY_SMS} is included.
7140      *
7141      * @see SubscriptionInfo#getServiceCapabilities()
7142      */
isDeviceSmsCapable()7143     public boolean isDeviceSmsCapable() {
7144         return isSmsCapable();
7145     }
7146 
7147     /**
7148      * Requests all available cell information from all radios on the device including the
7149      * camped/registered, serving, and neighboring cells.
7150      *
7151      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
7152      * {@link android.telephony.CellInfoCdma CellInfoCdma},
7153      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
7154      * {@link android.telephony.CellInfoLte CellInfoLte}, and
7155      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
7156      * It is typical to see instances of one or more of any these in the list. In addition, zero
7157      * or more of the returned objects may be considered registered; that is, their
7158      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
7159      * methods may return true, indicating that the cell is being used or would be used for
7160      * signaling communication if necessary.
7161      *
7162      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
7163      * if this API results in a change of the cached CellInfo, that change will be reported via
7164      * {@link TelephonyCallback.CellInfoListener#onCellInfoChanged(List) onCellInfoChanged()}.
7165      *
7166      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
7167      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
7168      * will receive the latest cached results, which may not be current. Apps targeting
7169      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
7170      * CellInfo should call
7171      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
7172      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
7173      * recency of CellInfo data, callers should check
7174      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
7175      *
7176      * <p>This method returns valid data for devices with
7177      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
7178      * where only partial information is available for a particular CellInfo entry, unavailable
7179      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
7180      * cells will include at least a valid set of technology-specific identification info and a
7181      * power level measurement.
7182      *
7183      * <p>This method is preferred over using {@link
7184      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
7185      *
7186      * @return List of {@link android.telephony.CellInfo}; null if cell
7187      * information is unavailable.
7188      *
7189      * @throws UnsupportedOperationException If the device does not have
7190      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
7191      */
7192     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
7193     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getAllCellInfo()7194     public List<CellInfo> getAllCellInfo() {
7195         try {
7196             ITelephony telephony = getITelephony();
7197             if (telephony == null)
7198                 return null;
7199             return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
7200         } catch (RemoteException ex) {
7201         } catch (NullPointerException ex) {
7202         }
7203         return null;
7204     }
7205 
7206     /** Callback for providing asynchronous {@link CellInfo} on request */
7207     public abstract static class CellInfoCallback {
7208         /**
7209          * Success response to
7210          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
7211          *
7212          * Invoked when there is a response to
7213          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
7214          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
7215          * list will be provided. If an error occurs, null will be provided unless the onError
7216          * callback is overridden.
7217          *
7218          * @param cellInfo a list of {@link CellInfo} or an empty list.
7219          *
7220          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
7221          */
onCellInfo(@onNull List<CellInfo> cellInfo)7222         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
7223 
7224         /** @hide */
7225         @Retention(RetentionPolicy.SOURCE)
7226         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
7227         public @interface CellInfoCallbackError {}
7228 
7229         /**
7230          * The system timed out waiting for a response from the Radio.
7231          */
7232         public static final int ERROR_TIMEOUT = 1;
7233 
7234         /**
7235          * The modem returned a failure.
7236          */
7237         public static final int ERROR_MODEM_ERROR = 2;
7238 
7239         /**
7240          * Error response to
7241          * {@link TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
7242          *
7243          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
7244          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
7245          * function to receive detailed status information in the event of an error. By default,
7246          * this function will invoke onCellInfo() with null.
7247          *
7248          * @param errorCode an error code indicating the type of failure.
7249          * @param detail a Throwable object with additional detail regarding the failure if
7250          *     available, otherwise null.
7251          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)7252         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
7253             // By default, simply invoke the success callback with an empty list.
7254             onCellInfo(new ArrayList<CellInfo>());
7255         }
7256     };
7257 
7258     /**
7259      * Used for checking if the target SDK version for the current process is S or above.
7260      *
7261      * <p> Applies to the following methods:
7262      * {@link #requestCellInfoUpdate},
7263      * {@link #setPreferredOpportunisticDataSubscription},
7264      * {@link #updateAvailableNetworks},
7265      * requestNumberVerification(),
7266      * setSimPowerStateForSlot(),
7267      */
7268     @ChangeId
7269     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.R)
7270     private static final long NULL_TELEPHONY_THROW_NO_CB = 182185642L;
7271 
7272     /**
7273      * Requests all available cell information from the current subscription for observed
7274      * camped/registered, serving, and neighboring cells.
7275      *
7276      * <p>Any available results from this request will be provided by calls to
7277      * {@link TelephonyCallback.CellInfoListener#onCellInfoChanged(List) onCellInfoChanged()}
7278      * for each active subscription.
7279      *
7280      * <p>This method returns valid data for devices with
7281      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
7282      * that do not implement this feature, the behavior is not reliable.
7283      *
7284      * @param executor the executor on which callback will be invoked.
7285      * @param callback a callback to receive CellInfo.
7286      *
7287      * @throws UnsupportedOperationException If the device does not have
7288      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
7289      */
7290     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
7291     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)7292     public void requestCellInfoUpdate(
7293             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
7294         try {
7295             ITelephony telephony = getITelephony();
7296             if (telephony == null) {
7297                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
7298                     throw new IllegalStateException("Telephony is null");
7299                 } else {
7300                     return;
7301                 }
7302             }
7303 
7304             telephony.requestCellInfoUpdate(
7305                     getSubId(),
7306                     new ICellInfoCallback.Stub() {
7307                         @Override
7308                         public void onCellInfo(List<CellInfo> cellInfo) {
7309                             final long identity = Binder.clearCallingIdentity();
7310                             try {
7311                                 executor.execute(() -> callback.onCellInfo(cellInfo));
7312                             } finally {
7313                                 Binder.restoreCallingIdentity(identity);
7314                             }
7315                         }
7316 
7317                         @Override
7318                         public void onError(int errorCode, String exceptionName, String message) {
7319                             final long identity = Binder.clearCallingIdentity();
7320                             try {
7321                                 executor.execute(() -> callback.onError(
7322                                         errorCode,
7323                                         createThrowableByClassName(exceptionName, message)));
7324                             } finally {
7325                                 Binder.restoreCallingIdentity(identity);
7326                             }
7327                         }
7328                     }, getOpPackageName(), getAttributionTag());
7329         } catch (RemoteException ex) {
7330             runOnBackgroundThread(() -> executor.execute(
7331                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
7332         }
7333     }
7334 
7335     /**
7336      * Requests all available cell information from the current subscription for observed
7337      * camped/registered, serving, and neighboring cells.
7338      *
7339      * <p>Any available results from this request will be provided by calls to
7340      * {@link TelephonyCallback.CellInfoListener#onCellInfoChanged(List) onCellInfoChanged()}
7341      * for each active subscription.
7342      *
7343      * <p>This method returns valid data for devices with
7344      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
7345      * that do not implement this feature, the behavior is not reliable.
7346      *
7347      * @param workSource the requestor to whom the power consumption for this should be attributed.
7348      * @param executor the executor on which callback will be invoked.
7349      * @param callback a callback to receive CellInfo.
7350      *
7351      * @throws UnsupportedOperationException If the device does not have
7352      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
7353      * @hide
7354      */
7355     @SystemApi
7356     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
7357             android.Manifest.permission.MODIFY_PHONE_STATE})
7358     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)7359     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
7360             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
7361         try {
7362             ITelephony telephony = getITelephony();
7363             if (telephony == null) {
7364                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
7365                     throw new IllegalStateException("Telephony is null");
7366                 } else {
7367                     return;
7368                 }
7369             }
7370 
7371             telephony.requestCellInfoUpdateWithWorkSource(
7372                     getSubId(),
7373                     new ICellInfoCallback.Stub() {
7374                         @Override
7375                         public void onCellInfo(List<CellInfo> cellInfo) {
7376                             final long identity = Binder.clearCallingIdentity();
7377                             try {
7378                                 executor.execute(() -> callback.onCellInfo(cellInfo));
7379                             } finally {
7380                                 Binder.restoreCallingIdentity(identity);
7381                             }
7382 
7383                         }
7384 
7385                         @Override
7386                         public void onError(int errorCode, String exceptionName, String message) {
7387                             final long identity = Binder.clearCallingIdentity();
7388                             try {
7389                                 executor.execute(() -> callback.onError(
7390                                         errorCode,
7391                                         createThrowableByClassName(exceptionName, message)));
7392                             } finally {
7393                                 Binder.restoreCallingIdentity(identity);
7394                             }
7395                         }
7396                     }, getOpPackageName(), getAttributionTag(), workSource);
7397         } catch (RemoteException ex) {
7398             runOnBackgroundThread(() -> executor.execute(
7399                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
7400         }
7401     }
7402 
createThrowableByClassName(String className, String message)7403     private static Throwable createThrowableByClassName(String className, String message) {
7404         if (className == null) {
7405             return null;
7406         }
7407         try {
7408             Class<?> c = Class.forName(className);
7409             return (Throwable) c.getConstructor(String.class).newInstance(message);
7410         } catch (ReflectiveOperationException | ClassCastException e) {
7411         }
7412         return new RuntimeException(className + ": " + message);
7413     }
7414 
7415     /**
7416      * Sets the minimum time in milli-seconds between {@link
7417      * TelephonyCallback.CellInfoListener#onCellInfoChanged(List)} will be invoked.
7418      *<p>
7419      * The default, 0, means invoke onCellInfoChanged when any of the reported
7420      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
7421      * A onCellInfoChanged.
7422      *<p>
7423      * @param rateInMillis the rate
7424      *
7425      * @hide
7426      */
setCellInfoListRate(int rateInMillis, int subId)7427     public void setCellInfoListRate(int rateInMillis, int subId) {
7428         try {
7429             ITelephony telephony = getITelephony();
7430             if (telephony != null)
7431                 telephony.setCellInfoListRate(rateInMillis, subId);
7432         } catch (RemoteException ex) {
7433         } catch (NullPointerException ex) {
7434         }
7435     }
7436 
7437     /**
7438      * Returns the MMS user agent.
7439      *
7440      * @throws UnsupportedOperationException If the device does not have
7441      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
7442      */
7443     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getMmsUserAgent()7444     public String getMmsUserAgent() {
7445         try {
7446             ITelephony telephony = getITelephony();
7447             if (telephony != null) {
7448                 return telephony.getMmsUserAgent(getSubId());
7449             }
7450         } catch (RemoteException ex) {
7451         } catch (NullPointerException ex) {
7452         }
7453         return null;
7454     }
7455 
7456     /**
7457      * Returns the MMS user agent profile URL.
7458      *
7459      * @throws UnsupportedOperationException If the device does not have
7460      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
7461      */
7462     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getMmsUAProfUrl()7463     public String getMmsUAProfUrl() {
7464         try {
7465             ITelephony telephony = getITelephony();
7466             if (telephony != null) {
7467                 return telephony.getMmsUAProfUrl(getSubId());
7468             }
7469         } catch (RemoteException ex) {
7470         } catch (NullPointerException ex) {
7471         }
7472         return null;
7473     }
7474 
7475     /**
7476      * Get the first active portIndex from the corresponding physical slot index.
7477      * @param physicalSlotIndex physical slot index
7478      * @return first active port index or INVALID_PORT_INDEX if no port is active
7479      */
getFirstActivePortIndex(int physicalSlotIndex)7480     private int getFirstActivePortIndex(int physicalSlotIndex) {
7481         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
7482         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length
7483                 && slotInfos[physicalSlotIndex] != null) {
7484             Optional<UiccPortInfo> result =  slotInfos[physicalSlotIndex].getPorts().stream()
7485                     .filter(portInfo -> portInfo.isActive()).findFirst();
7486             if (result.isPresent()) {
7487                 return result.get().getPortIndex();
7488             }
7489         }
7490         return INVALID_PORT_INDEX;
7491     }
7492 
7493     /**
7494      * Opens a logical channel to the ICC card.
7495      *
7496      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7497      *
7498      * <p>Requires Permission:
7499      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7500      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7501      *
7502      * @param AID Application id. See ETSI 102.221 and 101.220.
7503      * @return an IccOpenLogicalChannelResponse object.
7504      *
7505      * @throws UnsupportedOperationException If the device does not have
7506      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7507      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
7508      */
7509     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7510     @Deprecated
iccOpenLogicalChannel(String AID)7511     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
7512         return iccOpenLogicalChannel(getSubId(), AID, -1);
7513     }
7514 
7515     /**
7516      * Opens a logical channel to the ICC card using the physical slot index.
7517      *
7518      * Use this method when no subscriptions are available on the SIM and the operation must be
7519      * performed using the physical slot index.
7520      *
7521      * This operation wraps two APDU instructions:
7522      * <ul>
7523      *     <li>MANAGE CHANNEL to open a logical channel</li>
7524      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7525      * </ul>
7526      *
7527      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7528      * and 0x0C are guaranteed to be supported.
7529      *
7530      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7531      * considered an error and the channel shall not be opened.
7532      *
7533      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7534      *
7535      * <p>Requires Permission:
7536      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7537      *
7538      * @param slotIndex the physical slot index of the ICC card
7539      * @param aid Application id. See ETSI 102.221 and 101.220.
7540      * @param p2 P2 parameter (described in ISO 7816-4).
7541      * @return an IccOpenLogicalChannelResponse object.
7542      * @throws UnsupportedOperationException If the device does not have
7543      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7544      * @hide
7545      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7546      * instead use {@link #iccOpenLogicalChannelByPort(int, int, String, int)}
7547      */
7548     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7549     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7550     @SystemApi
7551     @Nullable
7552     @Deprecated
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)7553     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
7554             @Nullable String aid, int p2) {
7555         try {
7556             ITelephony telephony = getITelephony();
7557             if (telephony != null) {
7558                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7559                 request.slotIndex = slotIndex;
7560                 request.portIndex = getFirstActivePortIndex(slotIndex);
7561                 request.aid = aid;
7562                 request.p2 = p2;
7563                 request.callingPackage = getOpPackageName();
7564                 request.binder = new Binder();
7565                 return telephony.iccOpenLogicalChannel(request);
7566             }
7567         } catch (RemoteException ex) {
7568         } catch (NullPointerException ex) {
7569         }
7570         return null;
7571     }
7572 
7573     /**
7574      * Opens a logical channel to the ICC card using the physical slot index and port index.
7575      *
7576      * Use this method when no subscriptions are available on the SIM and the operation must be
7577      * performed using the physical slot index and port index.
7578      *
7579      * This operation wraps two APDU instructions:
7580      * <ul>
7581      *     <li>MANAGE CHANNEL to open a logical channel</li>
7582      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7583      * </ul>
7584      *
7585      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7586      * and 0x0C are guaranteed to be supported.
7587      *
7588      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7589      * considered an error and the channel shall not be opened.
7590      *
7591      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7592      *
7593      * @param slotIndex the physical slot index of the ICC card
7594      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7595      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7596      * @param aid Application id. See ETSI 102.221 and 101.220.
7597      * @param p2 P2 parameter (described in ISO 7816-4).
7598      * @return an IccOpenLogicalChannelResponse object.
7599      *
7600      * @throws UnsupportedOperationException If the device does not have
7601      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7602      * @hide
7603      */
7604     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7605     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7606     @SystemApi
7607     @NonNull
iccOpenLogicalChannelByPort(int slotIndex, int portIndex, @Nullable String aid, int p2)7608     public IccOpenLogicalChannelResponse iccOpenLogicalChannelByPort(int slotIndex,
7609             int portIndex, @Nullable String aid, int p2) {
7610         try {
7611             ITelephony telephony = getITelephony();
7612             if (telephony != null) {
7613                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7614                 request.slotIndex = slotIndex;
7615                 request.portIndex = portIndex;
7616                 request.aid = aid;
7617                 request.p2 = p2;
7618                 request.callingPackage = getOpPackageName();
7619                 request.binder = new Binder();
7620                 return telephony.iccOpenLogicalChannel(request);
7621             } else {
7622                 throw new IllegalStateException("telephony service is null.");
7623             }
7624         } catch (RemoteException ex) {
7625             throw ex.rethrowAsRuntimeException();
7626         }
7627     }
7628 
7629     /**
7630      * Opens a logical channel to the ICC card.
7631      *
7632      * This operation wraps two APDU instructions:
7633      * <ul>
7634      *     <li>MANAGE CHANNEL to open a logical channel</li>
7635      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7636      * </ul>
7637      *
7638      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7639      * and 0x0C are guaranteed to be supported.
7640      *
7641      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7642      * considered an error and the channel shall not be opened.
7643      *
7644      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7645      *
7646      * It is strongly recommended that callers of this should firstly create a new TelephonyManager
7647      * instance by calling {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so
7648      * can result in unpredictable and detrimental behavior like callers can end up talking to the
7649      * wrong SIM card.
7650      *
7651      * <p>Requires Permission:
7652      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7653      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7654      *
7655      * @param AID Application id. See ETSI 102.221 and 101.220.
7656      * @param p2 P2 parameter (described in ISO 7816-4).
7657      * @return an IccOpenLogicalChannelResponse object.
7658      *
7659      * @throws UnsupportedOperationException If the device does not have
7660      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7661      */
7662     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccOpenLogicalChannel(String AID, int p2)7663     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
7664         return iccOpenLogicalChannel(getSubId(), AID, p2);
7665     }
7666 
7667     /**
7668      * Opens a logical channel to the ICC card.
7669      *
7670      * This operation wraps two APDU instructions:
7671      * <ul>
7672      *     <li>MANAGE CHANNEL to open a logical channel</li>
7673      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
7674      * </ul>
7675      *
7676      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
7677      * and 0x0C are guaranteed to be supported.
7678      *
7679      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
7680      * considered an error and the channel shall not be opened.
7681      *
7682      * Input parameters equivalent to TS 27.007 AT+CCHO command.
7683      *
7684      * <p>Requires Permission:
7685      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7686      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7687      *
7688      * @param subId The subscription to use.
7689      * @param AID Application id. See ETSI 102.221 and 101.220.
7690      * @param p2 P2 parameter (described in ISO 7816-4).
7691      * @return an IccOpenLogicalChannelResponse object.
7692      * @hide
7693      */
iccOpenLogicalChannel(int subId, String AID, int p2)7694     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
7695         try {
7696             ITelephony telephony = getITelephony();
7697             if (telephony != null) {
7698                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7699                 request.subId = subId;
7700                 request.callingPackage = getOpPackageName();
7701                 request.aid = AID;
7702                 request.p2 = p2;
7703                 request.binder = new Binder();
7704                 return telephony.iccOpenLogicalChannel(request);
7705             }
7706         } catch (RemoteException ex) {
7707         } catch (NullPointerException ex) {
7708         }
7709         return null;
7710     }
7711 
7712     /**
7713      * Closes a previously opened logical channel to the ICC card using the physical slot index.
7714      *
7715      * Use this method when no subscriptions are available on the SIM and the operation must be
7716      * performed using the physical slot index.
7717      *
7718      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7719      *
7720      * <p>Requires Permission:
7721      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7722      *
7723      * @param slotIndex the physical slot index of the ICC card
7724      * @param channel is the channel id to be closed as returned by a successful
7725      *            iccOpenLogicalChannel.
7726      * @return true if the channel was closed successfully.
7727      *
7728      * @throws UnsupportedOperationException If the device does not have
7729      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7730      * @hide
7731      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7732      * instead use {@link #iccCloseLogicalChannelByPort(int, int, int)}
7733      */
7734     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7735     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7736     @SystemApi
7737     @Deprecated
iccCloseLogicalChannelBySlot(int slotIndex, int channel)7738     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
7739         try {
7740             ITelephony telephony = getITelephony();
7741             if (telephony != null) {
7742                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7743                 request.slotIndex = slotIndex;
7744                 request.portIndex = getFirstActivePortIndex(slotIndex);
7745                 request.channel = channel;
7746                 return telephony.iccCloseLogicalChannel(request);
7747             }
7748         } catch (RemoteException ex) {
7749         } catch (NullPointerException ex) {
7750         } catch (IllegalStateException ex) {
7751             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7752         }
7753         return false;
7754     }
7755 
7756     /**
7757      * Closes a previously opened logical channel to the ICC card using the physical slot index and
7758      * port index.
7759      *
7760      * Use this method when no subscriptions are available on the SIM and the operation must be
7761      * performed using the physical slot index and port index.
7762      *
7763      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7764      *
7765      * @param slotIndex the physical slot index of the ICC card
7766      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7767      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7768      * @param channel is the channel id to be closed as returned by a successful
7769      *            iccOpenLogicalChannel.
7770      *
7771      * @throws IllegalStateException if the Telephony process is not currently available or modem
7772      *                               currently can't process this command.
7773      * @throws IllegalArgumentException if invalid arguments are passed.
7774      * @throws UnsupportedOperationException If the device does not have
7775      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7776      * @hide
7777      */
7778     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7779     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7780     @SystemApi
iccCloseLogicalChannelByPort(int slotIndex, int portIndex, int channel)7781     public void iccCloseLogicalChannelByPort(int slotIndex, int portIndex, int channel) {
7782         try {
7783             ITelephony telephony = getITelephony();
7784             if (telephony != null) {
7785                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7786                 request.slotIndex = slotIndex;
7787                 request.portIndex = portIndex;
7788                 request.channel = channel;
7789                 telephony.iccCloseLogicalChannel(request);
7790             } else {
7791                 throw new IllegalStateException("telephony service is null.");
7792             }
7793         } catch (RemoteException ex) {
7794             throw ex.rethrowAsRuntimeException();
7795         }
7796     }
7797 
7798     /**
7799      * Closes a previously opened logical channel to the ICC card.
7800      *
7801      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7802      * It is strongly recommended that callers of this API should firstly create
7803      * new TelephonyManager instance by calling
7804      * {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so can result in
7805      * unpredictable and detrimental behavior like callers can end up talking to the wrong SIM card.
7806      *
7807      * <p>Requires Permission:
7808      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7809      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7810      *
7811      * @param channel is the channel id to be closed as returned by a successful
7812      *            iccOpenLogicalChannel.
7813      * @return true if the channel was closed successfully.
7814      * @throws IllegalArgumentException if input parameters are wrong. e.g., invalid channel
7815      * @throws UnsupportedOperationException If the device does not have
7816      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7817      */
7818     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccCloseLogicalChannel(int channel)7819     public boolean iccCloseLogicalChannel(int channel) {
7820         try {
7821             return iccCloseLogicalChannel(getSubId(), channel);
7822         } catch (IllegalStateException ex) {
7823             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7824         }
7825         return false;
7826     }
7827 
7828     /**
7829      * Closes a previously opened logical channel to the ICC card.
7830      *
7831      * Input parameters equivalent to TS 27.007 AT+CCHC command.
7832      *
7833      * <p>Requires Permission:
7834      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7835      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7836      *
7837      * @param subId The subscription to use.
7838      * @param channel is the channel id to be closed as returned by a successful
7839      *            iccOpenLogicalChannel.
7840      * @return true if the channel was closed successfully.
7841      * @hide
7842      */
iccCloseLogicalChannel(int subId, int channel)7843     public boolean iccCloseLogicalChannel(int subId, int channel) {
7844         try {
7845             ITelephony telephony = getITelephony();
7846             if (telephony != null) {
7847                 IccLogicalChannelRequest request = new IccLogicalChannelRequest();
7848                 request.subId = subId;
7849                 request.channel = channel;
7850                 return telephony.iccCloseLogicalChannel(request);
7851             }
7852         } catch (RemoteException ex) {
7853         } catch (NullPointerException ex) {
7854         } catch (IllegalStateException ex) {
7855             Rlog.e(TAG, "iccCloseLogicalChannel IllegalStateException", ex);
7856         }
7857         return false;
7858     }
7859 
7860     /**
7861      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
7862      *
7863      * Use this method when no subscriptions are available on the SIM and the operation must be
7864      * performed using the physical slot index.
7865      *
7866      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7867      *
7868      * <p>Requires Permission:
7869      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
7870      *
7871      * @param slotIndex the physical slot index of the ICC card
7872      * @param channel is the channel id to be closed as returned by a successful
7873      *            iccOpenLogicalChannel.
7874      * @param cla Class of the APDU command.
7875      * @param instruction Instruction of the APDU command.
7876      * @param p1 P1 value of the APDU command.
7877      * @param p2 P2 value of the APDU command.
7878      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7879      *            is sent to the SIM.
7880      * @param data Data to be sent with the APDU.
7881      * @return The APDU response from the ICC card with the status appended at the end, or null if
7882      * there is an issue connecting to the Telephony service.
7883      * @throws UnsupportedOperationException If the device does not have
7884      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7885      * @hide
7886      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
7887      * instead use
7888      * {@link #iccTransmitApduLogicalChannelByPort(int, int, int, int, int, int, int, int, String)}
7889      */
7890     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7891     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7892     @SystemApi
7893     @Nullable
7894     @Deprecated
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7895     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
7896             int instruction, int p1, int p2, int p3, @Nullable String data) {
7897         try {
7898             ITelephony telephony = getITelephony();
7899             if (telephony != null) {
7900                 return telephony.iccTransmitApduLogicalChannelByPort(slotIndex,
7901                         getFirstActivePortIndex(slotIndex), channel, cla, instruction,
7902                         p1, p2, p3, data);
7903             }
7904         } catch (RemoteException ex) {
7905         } catch (NullPointerException ex) {
7906         }
7907         return null;
7908     }
7909 
7910     /**
7911      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
7912      *
7913      * Use this method when no subscriptions are available on the SIM and the operation must be
7914      * performed using the physical slot index.
7915      *
7916      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7917      *
7918      * @param slotIndex the physical slot index of the ICC card
7919      * @param portIndex The port index is an enumeration of the ports available on the UICC.
7920      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
7921      * @param channel is the channel id to be closed as returned by a successful
7922      *            iccOpenLogicalChannel.
7923      * @param cla Class of the APDU command.
7924      * @param instruction Instruction of the APDU command.
7925      * @param p1 P1 value of the APDU command.
7926      * @param p2 P2 value of the APDU command.
7927      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7928      *            is sent to the SIM.
7929      * @param data Data to be sent with the APDU.
7930      * @return The APDU response from the ICC card with the status appended at the end, or null if
7931      * there is an issue connecting to the Telephony service.
7932      *
7933      * @throws UnsupportedOperationException If the device does not have
7934      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7935      * @hide
7936      */
7937     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7938     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
7939     @SystemApi
7940     @NonNull
iccTransmitApduLogicalChannelByPort(int slotIndex, int portIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)7941     public String iccTransmitApduLogicalChannelByPort(int slotIndex, int portIndex, int channel,
7942             int cla, int instruction, int p1, int p2, int p3, @Nullable String data) {
7943         String response;
7944         try {
7945             ITelephony telephony = getITelephony();
7946             if (telephony != null) {
7947                 response = telephony.iccTransmitApduLogicalChannelByPort(slotIndex, portIndex,
7948                         channel, cla, instruction, p1, p2, p3, data);
7949             } else {
7950                 throw new IllegalStateException("telephony service is null.");
7951             }
7952         } catch (RemoteException ex) {
7953             throw ex.rethrowAsRuntimeException();
7954         }
7955         return response;
7956     }
7957 
7958     /**
7959      * Transmit an APDU to the ICC card over a logical channel.
7960      *
7961      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7962      *
7963      * It is strongly recommended that callers of this API should firstly create a new
7964      * TelephonyManager instance by calling
7965      * {@link TelephonyManager#createForSubscriptionId(int)}. Failure to do so can result in
7966      * unpredictable and detrimental behavior like callers can end up talking to the wrong SIM card.
7967      *
7968      * <p>Requires Permission:
7969      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7970      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7971      *
7972      * @param channel is the channel id to be closed as returned by a successful
7973      *            iccOpenLogicalChannel.
7974      * @param cla Class of the APDU command.
7975      * @param instruction Instruction of the APDU command.
7976      * @param p1 P1 value of the APDU command.
7977      * @param p2 P2 value of the APDU command.
7978      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
7979      *            is sent to the SIM.
7980      * @param data Data to be sent with the APDU.
7981      * @return The APDU response from the ICC card with the status appended at
7982      *            the end.
7983      *
7984      * @throws UnsupportedOperationException If the device does not have
7985      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
7986      */
7987     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)7988     public String iccTransmitApduLogicalChannel(int channel, int cla,
7989             int instruction, int p1, int p2, int p3, String data) {
7990         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
7991                     instruction, p1, p2, p3, data);
7992     }
7993 
7994     /**
7995      * Transmit an APDU to the ICC card over a logical channel.
7996      *
7997      * Input parameters equivalent to TS 27.007 AT+CGLA command.
7998      *
7999      * <p>Requires Permission:
8000      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8001      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8002      *
8003      * @param subId The subscription to use.
8004      * @param channel is the channel id to be closed as returned by a successful
8005      *            iccOpenLogicalChannel.
8006      * @param cla Class of the APDU command.
8007      * @param instruction Instruction of the APDU command.
8008      * @param p1 P1 value of the APDU command.
8009      * @param p2 P2 value of the APDU command.
8010      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
8011      *            is sent to the SIM.
8012      * @param data Data to be sent with the APDU.
8013      * @return The APDU response from the ICC card with the status appended at
8014      *            the end.
8015      * @hide
8016      */
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)8017     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
8018             int instruction, int p1, int p2, int p3, String data) {
8019         try {
8020             ITelephony telephony = getITelephony();
8021             if (telephony != null)
8022                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
8023                     instruction, p1, p2, p3, data);
8024         } catch (RemoteException ex) {
8025         } catch (NullPointerException ex) {
8026         }
8027         return "";
8028     }
8029 
8030     /**
8031      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
8032      *
8033      * Use this method when no subscriptions are available on the SIM and the operation must be
8034      * performed using the physical slot index.
8035      *
8036      * Input parameters equivalent to TS 27.007 AT+CSIM command.
8037      *
8038      * <p>Requires Permission:
8039      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
8040      *
8041      * @param slotIndex the physical slot index of the ICC card to target
8042      * @param cla Class of the APDU command.
8043      * @param instruction Instruction of the APDU command.
8044      * @param p1 P1 value of the APDU command.
8045      * @param p2 P2 value of the APDU command.
8046      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
8047      *            is sent to the SIM.
8048      * @param data Data to be sent with the APDU.
8049      * @return The APDU response from the ICC card with the status appended at
8050      *            the end.
8051      *
8052      * @throws UnsupportedOperationException If the device does not have
8053      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8054      * @hide
8055      * @deprecated This API is not compatible on eUICC supporting Multiple Enabled Profile(MEP),
8056      * instead use
8057      * {@link #iccTransmitApduBasicChannelByPort(int, int, int, int, int, int, int, String)}
8058      */
8059     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8060     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
8061     @SystemApi
8062     @NonNull
8063     @Deprecated
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)8064     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
8065             int p2, int p3, @Nullable String data) {
8066         try {
8067             ITelephony telephony = getITelephony();
8068             if (telephony != null) {
8069                 return telephony.iccTransmitApduBasicChannelByPort(slotIndex,
8070                         getFirstActivePortIndex(slotIndex), getOpPackageName(),
8071                         cla, instruction, p1, p2, p3, data);
8072             }
8073         } catch (RemoteException ex) {
8074         } catch (NullPointerException ex) {
8075         }
8076         return null;
8077     }
8078 
8079     /**
8080      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
8081      *
8082      * Use this method when no subscriptions are available on the SIM and the operation must be
8083      * performed using the physical slot index.
8084      *
8085      * Input parameters equivalent to TS 27.007 AT+CSIM command.
8086      *
8087      * @param slotIndex the physical slot index of the ICC card to target
8088      * @param portIndex The port index is an enumeration of the ports available on the UICC.
8089      *                  Use {@link UiccPortInfo#getPortIndex()} to get portIndex.
8090      * @param cla Class of the APDU command.
8091      * @param instruction Instruction of the APDU command.
8092      * @param p1 P1 value of the APDU command.
8093      * @param p2 P2 value of the APDU command.
8094      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
8095      *            is sent to the SIM.
8096      * @param data Data to be sent with the APDU.
8097      * @return The APDU response from the ICC card with the status appended at
8098      *            the end.
8099      *
8100      * @throws UnsupportedOperationException If the device does not have
8101      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8102      * @hide
8103      */
8104     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8105     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
8106     @SystemApi
8107     @NonNull
iccTransmitApduBasicChannelByPort(int slotIndex, int portIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)8108     public String iccTransmitApduBasicChannelByPort(int slotIndex, int portIndex, int cla,
8109             int instruction, int p1, int p2, int p3, @Nullable String data) {
8110         String response;
8111         try {
8112             ITelephony telephony = getITelephony();
8113             if (telephony != null) {
8114                 response = telephony.iccTransmitApduBasicChannelByPort(slotIndex, portIndex,
8115                         getOpPackageName(), cla, instruction, p1, p2, p3, data);
8116             } else {
8117                 throw new IllegalStateException("telephony service is null.");
8118             }
8119         } catch (RemoteException ex) {
8120             throw ex.rethrowAsRuntimeException();
8121         }
8122         return response;
8123     }
8124     /**
8125      * Transmit an APDU to the ICC card over the basic channel.
8126      *
8127      * Input parameters equivalent to TS 27.007 AT+CSIM command.
8128      *
8129      * <p>Requires Permission:
8130      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8131      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8132      *
8133      * @param cla Class of the APDU command.
8134      * @param instruction Instruction of the APDU command.
8135      * @param p1 P1 value of the APDU command.
8136      * @param p2 P2 value of the APDU command.
8137      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
8138      *            is sent to the SIM.
8139      * @param data Data to be sent with the APDU.
8140      * @return The APDU response from the ICC card with the status appended at
8141      *            the end.
8142      *
8143      * @throws UnsupportedOperationException If the device does not have
8144      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8145      */
8146     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)8147     public String iccTransmitApduBasicChannel(int cla,
8148             int instruction, int p1, int p2, int p3, String data) {
8149         return iccTransmitApduBasicChannel(getSubId(), cla,
8150                     instruction, p1, p2, p3, data);
8151     }
8152 
8153     /**
8154      * Transmit an APDU to the ICC card over the basic channel.
8155      *
8156      * Input parameters equivalent to TS 27.007 AT+CSIM command.
8157      *
8158      * <p>Requires Permission:
8159      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8160      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8161      *
8162      * @param subId The subscription to use.
8163      * @param cla Class of the APDU command.
8164      * @param instruction Instruction of the APDU command.
8165      * @param p1 P1 value of the APDU command.
8166      * @param p2 P2 value of the APDU command.
8167      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
8168      *            is sent to the SIM.
8169      * @param data Data to be sent with the APDU.
8170      * @return The APDU response from the ICC card with the status appended at
8171      *            the end.
8172      * @hide
8173      */
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)8174     public String iccTransmitApduBasicChannel(int subId, int cla,
8175             int instruction, int p1, int p2, int p3, String data) {
8176         try {
8177             ITelephony telephony = getITelephony();
8178             if (telephony != null)
8179                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
8180                     instruction, p1, p2, p3, data);
8181         } catch (RemoteException ex) {
8182         } catch (NullPointerException ex) {
8183         }
8184         return "";
8185     }
8186 
8187     /**
8188      * Returns the response APDU for a command APDU sent through SIM_IO.
8189      *
8190      * <p>Requires Permission:
8191      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8192      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8193      *
8194      * @param fileID
8195      * @param command
8196      * @param p1 P1 value of the APDU command.
8197      * @param p2 P2 value of the APDU command.
8198      * @param p3 P3 value of the APDU command.
8199      * @param filePath
8200      * @return The APDU response.
8201      *
8202      * @throws UnsupportedOperationException If the device does not have
8203      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8204      */
8205     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)8206     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
8207             String filePath) {
8208         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
8209     }
8210 
8211     /**
8212      * Returns the response APDU for a command APDU sent through SIM_IO.
8213      *
8214      * <p>Requires Permission:
8215      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8216      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8217      *
8218      * @param subId The subscription to use.
8219      * @param fileID
8220      * @param command
8221      * @param p1 P1 value of the APDU command.
8222      * @param p2 P2 value of the APDU command.
8223      * @param p3 P3 value of the APDU command.
8224      * @param filePath
8225      * @return The APDU response.
8226      * @hide
8227      */
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)8228     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
8229             int p3, String filePath) {
8230         try {
8231             ITelephony telephony = getITelephony();
8232             if (telephony != null)
8233                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
8234         } catch (RemoteException ex) {
8235         } catch (NullPointerException ex) {
8236         }
8237         return null;
8238     }
8239 
8240     /**
8241      * Send ENVELOPE to the SIM and return the response.
8242      *
8243      * <p>Requires Permission:
8244      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8245      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8246      *
8247      * @param content String containing SAT/USAT response in hexadecimal
8248      *                format starting with command tag. See TS 102 223 for
8249      *                details.
8250      * @return The APDU response from the ICC card in hexadecimal format
8251      *         with the last 4 bytes being the status word. If the command fails,
8252      *         returns an empty string.
8253      *
8254      * @throws UnsupportedOperationException If the device does not have
8255      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8256      */
8257     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
sendEnvelopeWithStatus(String content)8258     public String sendEnvelopeWithStatus(String content) {
8259         return sendEnvelopeWithStatus(getSubId(), content);
8260     }
8261 
8262     /**
8263      * Send ENVELOPE to the SIM and return the response.
8264      *
8265      * <p>Requires Permission:
8266      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8267      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8268      *
8269      * @param subId The subscription to use.
8270      * @param content String containing SAT/USAT response in hexadecimal
8271      *                format starting with command tag. See TS 102 223 for
8272      *                details.
8273      * @return The APDU response from the ICC card in hexadecimal format
8274      *         with the last 4 bytes being the status word. If the command fails,
8275      *         returns an empty string.
8276      * @hide
8277      */
sendEnvelopeWithStatus(int subId, String content)8278     public String sendEnvelopeWithStatus(int subId, String content) {
8279         try {
8280             ITelephony telephony = getITelephony();
8281             if (telephony != null)
8282                 return telephony.sendEnvelopeWithStatus(subId, content);
8283         } catch (RemoteException ex) {
8284         } catch (NullPointerException ex) {
8285         }
8286         return "";
8287     }
8288 
8289     /**
8290      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
8291      * Used for device configuration by some CDMA operators.
8292      *
8293      * <p>Requires Permission:
8294      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8295      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8296      *
8297      * @param itemID the ID of the item to read.
8298      * @return the NV item as a String, or null on any failure.
8299      *
8300      * @deprecated Legacy CDMA is unsupported.
8301      * @hide
8302      */
8303     @Deprecated
8304     @UnsupportedAppUsage
nvReadItem(int itemID)8305     public String nvReadItem(int itemID) {
8306         if (Flags.cleanupCdma()) return "";
8307         try {
8308             ITelephony telephony = getITelephony();
8309             if (telephony != null)
8310                 return telephony.nvReadItem(itemID);
8311         } catch (RemoteException ex) {
8312             Rlog.e(TAG, "nvReadItem RemoteException", ex);
8313         } catch (NullPointerException ex) {
8314             Rlog.e(TAG, "nvReadItem NPE", ex);
8315         }
8316         return "";
8317     }
8318 
8319     /**
8320      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
8321      * Used for device configuration by some CDMA operators.
8322      *
8323      * <p>Requires Permission:
8324      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8325      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8326      *
8327      * @param itemID the ID of the item to read.
8328      * @param itemValue the value to write, as a String.
8329      * @return true on success; false on any failure.
8330      *
8331      * @deprecated Legacy CDMA is unsupported.
8332      * @hide
8333      */
8334     @Deprecated
nvWriteItem(int itemID, String itemValue)8335     public boolean nvWriteItem(int itemID, String itemValue) {
8336         if (Flags.cleanupCdma()) return false;
8337         try {
8338             ITelephony telephony = getITelephony();
8339             if (telephony != null)
8340                 return telephony.nvWriteItem(itemID, itemValue);
8341         } catch (RemoteException ex) {
8342             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
8343         } catch (NullPointerException ex) {
8344             Rlog.e(TAG, "nvWriteItem NPE", ex);
8345         }
8346         return false;
8347     }
8348 
8349     /**
8350      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
8351      * Used for device configuration by some CDMA operators.
8352      *
8353      * <p>Requires Permission:
8354      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8355      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8356      *
8357      * @param preferredRoamingList byte array containing the new PRL.
8358      * @return true on success; false on any failure.
8359      *
8360      * @deprecated Legacy CDMA is unsupported.
8361      * @hide
8362      */
8363     @Deprecated
nvWriteCdmaPrl(byte[] preferredRoamingList)8364     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
8365         if (Flags.cleanupCdma()) return false;
8366         try {
8367             ITelephony telephony = getITelephony();
8368             if (telephony != null)
8369                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
8370         } catch (RemoteException ex) {
8371             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
8372         } catch (NullPointerException ex) {
8373             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
8374         }
8375         return false;
8376     }
8377 
8378     /**
8379      * Perform the specified type of NV config reset. The radio will be taken offline
8380      * and the device must be rebooted after the operation. Used for device
8381      * configuration by some CDMA operators.
8382      *
8383      * <p>Requires Permission:
8384      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8385      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8386      *
8387      * TODO: remove this one. use {@link #rebootModem()} for reset type 1 and
8388      * {@link #resetRadioConfig()} for reset type 3 (b/116476729)
8389      *
8390      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
8391      * @deprecated NV APIs are deprecated starting from Android U.
8392      * @return true on success; false on any failure.
8393      *
8394      * @hide
8395      */
8396     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8397     @Deprecated
nvResetConfig(int resetType)8398     public boolean nvResetConfig(int resetType) {
8399         if (Flags.cleanupCdma()) {
8400             if (resetType != 1) {  // 1: reload NV reset (reboot modem)
8401                 return false;
8402             }
8403         }
8404         try {
8405             ITelephony telephony = getITelephony();
8406             if (telephony != null) {
8407                 if (resetType == 1 /*1: reload NV reset */) {
8408                     return telephony.rebootModem(getSlotIndex());
8409                 } else if (resetType == 3 /*3: factory NV reset */) {
8410                     return telephony.resetModemConfig(getSlotIndex());
8411                 } else {
8412                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
8413                 }
8414             }
8415         } catch (RemoteException ex) {
8416             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
8417         } catch (NullPointerException ex) {
8418             Rlog.e(TAG, "nvResetConfig NPE", ex);
8419         }
8420         return false;
8421     }
8422 
8423     /**
8424      * Rollback modem configurations to factory default except some config which are in allowlist.
8425      * Used for device configuration by some carriers.
8426      *
8427      * <p>Requires Permission:
8428      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8429      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8430      *
8431      * @return {@code true} on success; {@code false} on any failure.
8432      *
8433      * @deprecated NV APIs are deprecated starting from Android U.
8434      * @throws UnsupportedOperationException If the device does not have
8435      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
8436      * @hide
8437      */
8438     @Deprecated
8439     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
8440     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8441     @SystemApi
8442     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
resetRadioConfig()8443     public boolean resetRadioConfig() {
8444         if (Flags.cleanupCdma()) {
8445             return false;
8446         }
8447         try {
8448             ITelephony telephony = getITelephony();
8449             if (telephony != null) {
8450                 return telephony.resetModemConfig(getSlotIndex());
8451             }
8452         } catch (RemoteException ex) {
8453             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
8454         } catch (NullPointerException ex) {
8455             Rlog.e(TAG, "resetRadioConfig NPE", ex);
8456         }
8457         return false;
8458     }
8459 
8460     /**
8461      * Generate a radio modem reset. Used for device configuration by some carriers.
8462      *
8463      * <p>Requires Permission:
8464      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8465      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8466      *
8467      * @return {@code true} on success; {@code false} on any failure.
8468      *
8469      * @deprecated  Using {@link #rebootModem()} instead.
8470      *
8471      * @throws UnsupportedOperationException If the device does not have
8472      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
8473      * @hide
8474      */
8475     @Deprecated
8476     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8477     @SystemApi
8478     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
rebootRadio()8479     public boolean rebootRadio() {
8480         try {
8481             ITelephony telephony = getITelephony();
8482             if (telephony != null) {
8483                 return telephony.rebootModem(getSlotIndex());
8484             }
8485         } catch (RemoteException ex) {
8486             Rlog.e(TAG, "rebootRadio RemoteException", ex);
8487         } catch (NullPointerException ex) {
8488             Rlog.e(TAG, "rebootRadio NPE", ex);
8489         }
8490         return false;
8491     }
8492 
8493     /**
8494      * Generate a radio modem reset. Used for device configuration by some carriers.
8495      *
8496      * <p>Requires Permission:
8497      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8498      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8499      * @throws IllegalStateException if the Telephony process is not currently available.
8500      * @throws RuntimeException
8501      * @throws UnsupportedOperationException If the device does not have
8502      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
8503      */
8504     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8505     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
rebootModem()8506     public void rebootModem() {
8507         try {
8508             ITelephony telephony = getITelephony();
8509             if (telephony == null) {
8510                 throw new IllegalStateException("telephony service is null.");
8511             }
8512             if (!telephony.rebootModem(getSlotIndex())) {
8513                 throw new RuntimeException("Couldn't reboot modem (it may be not supported)");
8514             }
8515         } catch (RemoteException ex) {
8516             Rlog.e(TAG, "rebootRadio RemoteException", ex);
8517             throw ex.rethrowAsRuntimeException();
8518         }
8519     }
8520 
8521     /**
8522      * Return an appropriate subscription ID for any situation.
8523      *
8524      * If this object has been created with {@link #createForSubscriptionId}, then the provided
8525      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
8526      *
8527      */
8528     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriptionId()8529     public int getSubscriptionId() {
8530         return getSubId();
8531     }
8532 
8533     /**
8534      * Return an appropriate subscription ID for any situation.
8535      *
8536      * If this object has been created with {@link #createForSubscriptionId}, then the provided
8537      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
8538      *
8539      */
getSubId()8540     private int getSubId() {
8541       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
8542         return mSubId;
8543       }
8544       return SubscriptionManager.getDefaultSubscriptionId();
8545     }
8546 
8547     /**
8548      * Return an appropriate subscription ID for any situation.
8549      *
8550      * If this object has been created with {@link #createForSubscriptionId}, then the provided
8551      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
8552      * returned.
8553      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
8554      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
8555      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
8556      */
8557     @UnsupportedAppUsage
getSubId(int preferredSubId)8558     private int getSubId(int preferredSubId) {
8559         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
8560             return mSubId;
8561         }
8562         return preferredSubId;
8563     }
8564 
8565     /**
8566      * Return an appropriate phone ID for any situation.
8567      *
8568      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
8569      * associated with the provided subId is returned. Otherwise, the default phoneId associated
8570      * with the default subId will be returned.
8571      */
getPhoneId()8572     private int getPhoneId() {
8573         return SubscriptionManager.getPhoneId(getSubId());
8574     }
8575 
8576     /**
8577      * Return an appropriate phone ID for any situation.
8578      *
8579      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
8580      * associated with the provided subId is returned. Otherwise, return the phoneId associated
8581      * with the preferred subId based on caller's context.
8582      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
8583      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
8584      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
8585      */
8586     @UnsupportedAppUsage
getPhoneId(int preferredSubId)8587     private int getPhoneId(int preferredSubId) {
8588         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
8589     }
8590 
8591     /**
8592      * Return an appropriate slot index for any situation.
8593      *
8594      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
8595      * associated with the provided subId is returned. Otherwise, return the slot index associated
8596      * with the default subId.
8597      * If SIM is not inserted, return default SIM slot index.
8598      *
8599      * {@hide}
8600      */
8601     @VisibleForTesting
8602     @UnsupportedAppUsage
getSlotIndex()8603     public int getSlotIndex() {
8604         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
8605         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
8606             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
8607         }
8608         return slotIndex;
8609     }
8610 
8611     /**
8612      * Request that the next incoming call from a number matching {@code range} be intercepted.
8613      *
8614      * This API is intended for OEMs to provide a service for apps to verify the device's phone
8615      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
8616      * intercept the next incoming call from a number that lies within the range, within a timeout
8617      * specified by {@code timeoutMillis}.
8618      *
8619      * If such a phone call is received, the caller will be notified via
8620      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
8621      * If verification fails for any reason, the caller will be notified via
8622      * {@link NumberVerificationCallback#onVerificationFailed(int)}
8623      * on the provided {@link Executor}.
8624      *
8625      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
8626      * API must also be listed in the device configuration as an authorized app in
8627      * {@code packages/services/Telephony/res/values/config.xml} under the
8628      * {@code platform_number_verification_package} key.
8629      *
8630      * @hide
8631      * @param range The range of phone numbers the caller expects a phone call from.
8632      * @param timeoutMillis The amount of time to wait for such a call, or the value of
8633      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
8634      * @param executor The {@link Executor} that callbacks should be executed on.
8635      * @param callback The callback to use for delivering results.
8636      *
8637      * @throws UnsupportedOperationException If the device does not have
8638      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
8639      */
8640     @SystemApi
8641     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
8642     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)8643     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
8644             @NonNull @CallbackExecutor Executor executor,
8645             @NonNull NumberVerificationCallback callback) {
8646         if (executor == null) {
8647             throw new NullPointerException("Executor must be non-null");
8648         }
8649         if (callback == null) {
8650             throw new NullPointerException("Callback must be non-null");
8651         }
8652 
8653         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
8654             @Override
8655             public void onCallReceived(String phoneNumber) {
8656                 final long identity = Binder.clearCallingIdentity();
8657                 try {
8658                     executor.execute(() ->
8659                             callback.onCallReceived(phoneNumber));
8660                 } finally {
8661                     Binder.restoreCallingIdentity(identity);
8662                 }
8663             }
8664 
8665             @Override
8666             public void onVerificationFailed(int reason) {
8667                 final long identity = Binder.clearCallingIdentity();
8668                 try {
8669                     executor.execute(() ->
8670                             callback.onVerificationFailed(reason));
8671                 } finally {
8672                     Binder.restoreCallingIdentity(identity);
8673                 }
8674             }
8675         };
8676 
8677         try {
8678             ITelephony telephony = getITelephony();
8679             if (telephony == null) {
8680                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
8681                     throw new IllegalStateException("Telephony is null");
8682                 } else {
8683                     return;
8684                 }
8685             }
8686 
8687             telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
8688                     getOpPackageName());
8689         } catch (RemoteException ex) {
8690             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
8691             runOnBackgroundThread(() -> executor.execute(
8692                     () -> callback.onVerificationFailed(
8693                             NumberVerificationCallback.REASON_UNSPECIFIED)));
8694         }
8695     }
8696 
8697     /**
8698      * Inserts or updates a list property. Expands the list if its length is not enough.
8699      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)8700     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
8701         List<T> ret = new ArrayList<>(prop);
8702         while (ret.size() <= phoneId) ret.add(null);
8703         ret.set(phoneId, value);
8704         return ret;
8705     }
8706     /**
8707      * Convenience function for retrieving a value from the secure settings
8708      * value list as an integer.  Note that internally setting values are
8709      * always stored as strings; this function converts the string to an
8710      * integer for you.
8711      * <p>
8712      * This version does not take a default value.  If the setting has not
8713      * been set, or the string value is not a number,
8714      * it throws {@link SettingNotFoundException}.
8715      *
8716      * @param cr The ContentResolver to access.
8717      * @param name The name of the setting to retrieve.
8718      * @param index The index of the list
8719      *
8720      * @throws SettingNotFoundException Thrown if a setting by the given
8721      * name can't be found or the setting value is not an integer.
8722      *
8723      * @return The value at the given index of settings.
8724      * @hide
8725      */
8726     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getIntAtIndex(android.content.ContentResolver cr, String name, int index)8727     public static int getIntAtIndex(android.content.ContentResolver cr,
8728             String name, int index)
8729             throws android.provider.Settings.SettingNotFoundException {
8730         String v = android.provider.Settings.Global.getString(cr, name);
8731         if (v != null) {
8732             String valArray[] = v.split(",");
8733             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
8734                 try {
8735                     return Integer.parseInt(valArray[index]);
8736                 } catch (NumberFormatException e) {
8737                     //Log.e(TAG, "Exception while parsing Integer: ", e);
8738                 }
8739             }
8740         }
8741         throw new android.provider.Settings.SettingNotFoundException(name);
8742     }
8743 
8744     /**
8745      * Convenience function for updating settings value as coma separated
8746      * integer values. This will either create a new entry in the table if the
8747      * given name does not exist, or modify the value of the existing row
8748      * with that name.  Note that internally setting values are always
8749      * stored as strings, so this function converts the given value to a
8750      * string before storing it.
8751      *
8752      * @param cr The ContentResolver to access.
8753      * @param name The name of the setting to modify.
8754      * @param index The index of the list
8755      * @param value The new value for the setting to be added to the list.
8756      * @return true if the value was set, false on database errors
8757      * @hide
8758      */
8759     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)8760     public static boolean putIntAtIndex(android.content.ContentResolver cr,
8761             String name, int index, int value) {
8762         String data = "";
8763         String valArray[] = null;
8764         String v = android.provider.Settings.Global.getString(cr, name);
8765 
8766         if (index == Integer.MAX_VALUE) {
8767             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
8768         }
8769         if (index < 0) {
8770             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
8771         }
8772         if (v != null) {
8773             valArray = v.split(",");
8774         }
8775 
8776         // Copy the elements from valArray till index
8777         for (int i = 0; i < index; i++) {
8778             String str = "";
8779             if ((valArray != null) && (i < valArray.length)) {
8780                 str = valArray[i];
8781             }
8782             data = data + str + ",";
8783         }
8784 
8785         data = data + value;
8786 
8787         // Copy the remaining elements from valArray if any.
8788         if (valArray != null) {
8789             for (int i = index+1; i < valArray.length; i++) {
8790                 data = data + "," + valArray[i];
8791             }
8792         }
8793         return android.provider.Settings.Global.putString(cr, name, data);
8794     }
8795 
8796     /**
8797      * Gets a per-phone telephony property from a property name.
8798      *
8799      * @hide
8800      */
8801     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)8802     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
8803         String propVal = null;
8804         String prop = SystemProperties.get(property);
8805         if ((prop != null) && (prop.length() > 0)) {
8806             String values[] = prop.split(",");
8807             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
8808                 propVal = values[phoneId];
8809             }
8810         }
8811         return propVal == null ? defaultVal : propVal;
8812     }
8813 
8814     /**
8815      * Gets a typed per-phone telephony property from a schematized list property.
8816      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)8817     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
8818         T ret = null;
8819         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
8820         return ret != null ? ret : defaultValue;
8821     }
8822 
8823     /**
8824      * Gets a global telephony property.
8825      *
8826      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
8827      * per-phone.
8828      *
8829      * @hide
8830      */
8831     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getTelephonyProperty(String property, String defaultVal)8832     public static String getTelephonyProperty(String property, String defaultVal) {
8833         String propVal = SystemProperties.get(property);
8834         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
8835     }
8836 
8837     /** @hide */
8838     @UnsupportedAppUsage
getSimCount()8839     public int getSimCount() {
8840         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
8841         // and then this method shouldn't be used at all!
8842         return getPhoneCount();
8843     }
8844 
8845     /**
8846      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
8847      *
8848      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
8849      *
8850      * @return IMS Service Table or null if not present or not loaded
8851      *
8852      * @throws UnsupportedOperationException If the device does not have
8853      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8854      * @hide
8855      */
8856     @Nullable
8857     @SystemApi
8858     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8859     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIsimIst()8860     public String getIsimIst() {
8861         try {
8862             IPhoneSubInfo info = getSubscriberInfoService();
8863             if (info == null)
8864                 return null;
8865             //get the Isim Ist based on subId
8866             return info.getIsimIst(getSubId());
8867         } catch (RemoteException ex) {
8868             return null;
8869         } catch (NullPointerException ex) {
8870             // This could happen before phone restarts due to crashing
8871             return null;
8872         }
8873     }
8874 
8875     /**
8876      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
8877      * @return an array of PCSCF strings with one PCSCF per string, or null if
8878      *         not present or not loaded
8879      * @hide
8880      * @deprecated use {@link #getImsPcscfAddresses()} instead.
8881      */
8882     @Deprecated
8883     @FlaggedApi(Flags.FLAG_SUPPORT_ISIM_RECORD)
8884     @UnsupportedAppUsage
getIsimPcscf()8885     public String[] getIsimPcscf() {
8886         try {
8887             IPhoneSubInfo info = getSubscriberInfoService();
8888             if (info == null)
8889                 return null;
8890             //get the Isim Pcscf based on subId
8891             return info.getIsimPcscf(getSubId());
8892         } catch (RemoteException ex) {
8893             return null;
8894         } catch (NullPointerException ex) {
8895             // This could happen before phone restarts due to crashing
8896             return null;
8897         }
8898     }
8899 
8900     /**
8901      * Returns the IMS Proxy Call Session Control Function(P-CSCF) that were loaded from the ISIM.
8902      *
8903      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission or carrier
8904      * privileges.
8905      *
8906      * @return List of P-CSCF address strings or empty list if not available.
8907      * @throws IllegalStateException in case the ISIM hasn’t been loaded
8908      * @throws SecurityException if the caller does not have the required permission/privilege
8909      * @throws UnsupportedOperationException If the device does not have
8910      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
8911      * @hide
8912      */
8913     @FlaggedApi(Flags.FLAG_SUPPORT_ISIM_RECORD)
8914     @SystemApi
8915     @RequiresPermission(value = Manifest.permission.READ_PRIVILEGED_PHONE_STATE, conditional = true)
8916     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
8917     @NonNull
getImsPcscfAddresses()8918     public List<String> getImsPcscfAddresses() {
8919         try {
8920             IPhoneSubInfo info = getSubscriberInfoService();
8921             if (info == null) {
8922                 throw new RuntimeException("P-CSCF error: Subscriber Info is null");
8923             }
8924             return info.getImsPcscfAddresses(getSubId(), getOpPackageName());
8925         } catch (IllegalArgumentException | NullPointerException ex) {
8926             Rlog.e(TAG, "getImsPcscfAddresses Exception = " + ex);
8927         } catch (RemoteException ex) {
8928             Rlog.e(TAG, "getImsPcscfAddresses Exception = " + ex);
8929             ex.rethrowAsRuntimeException();
8930         }
8931         return Collections.EMPTY_LIST;
8932     }
8933 
8934     /** UICC application type is unknown or not specified */
8935     public static final int APPTYPE_UNKNOWN = PhoneConstants.APPTYPE_UNKNOWN;
8936     /** UICC application type is SIM */
8937     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
8938     /** UICC application type is USIM */
8939     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
8940     /** UICC application type is RUIM */
8941     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
8942     /** UICC application type is CSIM */
8943     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
8944     /** UICC application type is ISIM */
8945     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
8946 
8947     // authContext (parameter P2) when doing UICC challenge,
8948     // per 3GPP TS 31.102 (Section 7.1.2)
8949     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
8950     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
8951     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
8952     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
8953     /**
8954      * Authentication type for GBA Bootstrap Challenge.
8955      * Pass this authentication type into the {@link #getIccAuthentication} API to perform a GBA
8956      * Bootstrap challenge (BSF), with {@code data} (generated according to the procedure defined in
8957      * 3GPP 33.220 Section 5.3.2 step.4) in base64 encoding.
8958      * This method will return the Bootstrapping response in base64 encoding when ICC authentication
8959      * is completed.
8960      * Ref 3GPP 33.220 Section 5.3.2.
8961      */
8962     public static final int AUTHTYPE_GBA_BOOTSTRAP = PhoneConstants.AUTH_CONTEXT_GBA_BOOTSTRAP;
8963     /**
8964      * Authentication type for GBA Network Application Functions (NAF) key External Challenge.
8965      * Pass this authentication type into the {@link #getIccAuthentication} API to perform a GBA
8966      * Network Applications Functions (NAF) key External challenge using the NAF_ID parameter
8967      * as the {@code data} in base64 encoding.
8968      * This method will return the Ks_Ext_Naf key in base64 encoding when ICC authentication
8969      * is completed.
8970      * Ref 3GPP 33.220 Section 5.3.2.
8971      */
8972     public static final int AUTHTYPE_GBA_NAF_KEY_EXTERNAL =
8973             PhoneConstants.AUTHTYPE_GBA_NAF_KEY_EXTERNAL;
8974 
8975     /** @hide */
8976     @Retention(RetentionPolicy.SOURCE)
8977     @IntDef({
8978             AUTHTYPE_EAP_SIM,
8979             AUTHTYPE_EAP_AKA,
8980             AUTHTYPE_GBA_BOOTSTRAP,
8981             AUTHTYPE_GBA_NAF_KEY_EXTERNAL
8982     })
8983     public @interface AuthType {}
8984 
8985     /**
8986      * Returns the response of authentication for the default subscription.
8987      * Returns null if the authentication hasn't been successful
8988      *
8989      * <p>Requires one of the following permissions:
8990      * <ul>
8991      *     <li>READ_PRIVILEGED_PHONE_STATE
8992      *     <li>the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8993      *     <li>the calling app has been granted the
8994      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
8995      * </ul>
8996      *
8997      * @param appType the icc application type, like {@link #APPTYPE_USIM}
8998      * @param authType the authentication type, any one of {@link #AUTHTYPE_EAP_AKA} or
8999      * {@link #AUTHTYPE_EAP_SIM} or {@link #AUTHTYPE_GBA_BOOTSTRAP} or
9000      * {@link #AUTHTYPE_GBA_NAF_KEY_EXTERNAL}
9001      * @param data authentication challenge data, base64 encoded.
9002      * See 3GPP TS 31.102 7.1.2 for more details.
9003      * @return the response of authentication. This value will be null in the following cases:
9004      *   Authentication error, incorrect MAC
9005      *   Authentication error, security context not supported
9006      *   Key freshness failure
9007      *   Authentication error, no memory space available
9008      *   Authentication error, no memory space available in EFMUK
9009      *
9010      * @throws UnsupportedOperationException If the device does not have
9011      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION} or doesn't support given
9012      *          authType.
9013      */
9014     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getIccAuthentication(int appType, @AuthType int authType, String data)9015     public String getIccAuthentication(int appType, @AuthType int authType, String data) {
9016         return getIccAuthentication(getSubId(), appType, authType, data);
9017     }
9018 
9019     /**
9020      * Returns the response of USIM Authentication for specified subId.
9021      * Returns null if the authentication hasn't been successful
9022      *
9023      * <p>See {@link #getIccAuthentication(int, int, String)} for details on the required
9024      * permissions.
9025      *
9026      * @param subId subscription ID used for authentication
9027      * @param appType the icc application type, like {@link #APPTYPE_USIM}
9028      * @param authType the authentication type, any one of {@link #AUTHTYPE_EAP_AKA} or
9029      * {@link #AUTHTYPE_EAP_SIM} or {@link #AUTHTYPE_GBA_BOOTSTRAP} or
9030      * {@link #AUTHTYPE_GBA_NAF_KEY_EXTERNAL}
9031      * @param data authentication challenge data, base64 encoded.
9032      * See 3GPP TS 31.102 7.1.2 for more details.
9033      * @return the response of authentication. This value will be null in the following cases only
9034      * (see 3GPP TS 31.102 7.3.1):
9035      *   Authentication error, incorrect MAC
9036      *   Authentication error, security context not supported
9037      *   Key freshness failure
9038      *   Authentication error, no memory space available
9039      *   Authentication error, no memory space available in EFMUK
9040      * @throws UnsupportedOperationException If the device does not have
9041      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION} or doesn't support given
9042      *          authType.
9043      * @hide
9044      */
9045     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType, @AuthType int authType, String data)9046     public String getIccAuthentication(int subId, int appType, @AuthType int authType,
9047             String data) {
9048         try {
9049             IPhoneSubInfo info = getSubscriberInfoService();
9050             if (info == null)
9051                 return null;
9052             return info.getIccSimChallengeResponse(subId, appType, authType, data,
9053                     getOpPackageName(), getAttributionTag());
9054         } catch (RemoteException ex) {
9055             return null;
9056         } catch (NullPointerException ex) {
9057             // This could happen before phone starts
9058             return null;
9059         }
9060     }
9061 
9062     /**
9063      * Returns an array of Forbidden PLMNs from the USIM App
9064      * Returns null if the query fails.
9065      *
9066      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
9067      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9068      *
9069      * @return an array of forbidden PLMNs or null if not available
9070      *
9071      * @throws UnsupportedOperationException If the device does not have
9072      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
9073      */
9074     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9075     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
9076     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getForbiddenPlmns()9077     public String[] getForbiddenPlmns() {
9078       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
9079     }
9080 
9081     /**
9082      * Returns an array of Forbidden PLMNs from the specified SIM App
9083      * Returns null if the query fails.
9084      *
9085      * @param subId subscription ID used for authentication
9086      * @param appType the icc application type, like {@link #APPTYPE_USIM}
9087      * @return fplmns an array of forbidden PLMNs
9088      * @hide
9089      */
9090     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)9091     public String[] getForbiddenPlmns(int subId, int appType) {
9092         try {
9093             ITelephony telephony = getITelephony();
9094             if (telephony == null)
9095                 return null;
9096             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
9097                     getAttributionTag());
9098         } catch (RemoteException ex) {
9099             return null;
9100         } catch (NullPointerException ex) {
9101             // This could happen before phone starts
9102             return null;
9103         }
9104     }
9105 
9106     /**
9107      * Replace the contents of the forbidden PLMN SIM file with the provided values.
9108      * Passing an empty list will clear the contents of the EFfplmn file.
9109      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
9110      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
9111      * If the list is longer than the size of EFfplmn, then the file will be written from the
9112      * beginning of the list up to the file size.
9113      *
9114      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
9115      * MODIFY_PHONE_STATE}
9116      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9117      *
9118      * @param fplmns a list of PLMNs to be forbidden.
9119      *
9120      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
9121      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
9122      * room for all of the values passed in. Return -1 in the event of an unexpected failure
9123      *
9124      * @throws UnsupportedOperationException If the device does not have
9125      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
9126      */
9127     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9128     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9129     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setForbiddenPlmns(@onNull List<String> fplmns)9130     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
9131         try {
9132             ITelephony telephony = getITelephony();
9133             if (telephony == null) return -1;
9134             return telephony.setForbiddenPlmns(
9135                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
9136         } catch (RemoteException ex) {
9137             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
9138         } catch (NullPointerException ex) {
9139             // This could happen before phone starts
9140             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
9141         }
9142         return -1;
9143     }
9144 
9145     /**
9146      * Fetches the sim service table from the EFUST/EFIST based on the application type
9147      * {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}. The return value is hexaString format
9148      * representing X bytes (x >= 1). Each bit of every byte indicates which optional services
9149      * are available for the given application type.
9150      * The USIM service table EF is described in as per Section 4.2.8 of 3GPP TS 31.102.
9151      * The ISIM service table EF is described in as per Section 4.2.7 of 3GPP TS 31.103.
9152      * The list of services mapped to the exact nth byte of response as mentioned in Section 4.2
9153      * .7 of 3GPP TS 31.103. Eg. Service n°1: Local Phone Book, Service n°2: Fixed Dialling
9154      * Numbers (FDN) - Bit 1 and 2 of the 1st Byte represent service Local Phone Book and Fixed
9155      * Dialling Numbers (FDN)respectively. The coding format for each service type  should be
9156      * interpreted as bit = 1: service available;bit = 0:service not available.
9157      *
9158      * @param appType of type int of either {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}.
9159      * @return HexString represents sim service table else null.
9160      * @throws SecurityException if the caller does not have the required permission/privileges
9161      * @throws UnsupportedOperationException If the device does not have
9162      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
9163      * @hide
9164      * @deprecated Use {@link #getSimServiceTable(int, Executor, OutcomeReceiver)} instead.
9165      */
9166     @Deprecated
9167     @FlaggedApi(Flags.FLAG_SUPPORT_ISIM_RECORD)
9168     @Nullable
9169     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9170     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimServiceTable(int appType)9171     public String getSimServiceTable(int appType) {
9172         try {
9173             IPhoneSubInfo info = getSubscriberInfoService();
9174             if (info == null) {
9175                 Rlog.e(TAG, "getSimServiceTable(): IPhoneSubInfo is null");
9176                 return null;
9177             }
9178             //Fetches the sim service table based on subId and appType
9179             if (appType == APPTYPE_ISIM) {
9180                 return info.getIsimIst(getSubId());
9181             } else if ((appType == APPTYPE_USIM)) {
9182                 return info.getSimServiceTable(getSubId(), APPTYPE_USIM);
9183             } else {
9184                 return null;
9185             }
9186         } catch (RemoteException ex) {
9187             Rlog.e(TAG, "getSimServiceTable(): RemoteException=" + ex.getMessage());
9188         } catch (NullPointerException ex) {
9189             Rlog.e(TAG, "getSimServiceTable(): NullPointerException=" + ex.getMessage());
9190         }
9191         return null;
9192     }
9193 
9194     /**
9195      * Fetches the sim service table from the EFUST/EFIST based on the application type
9196      * {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}.
9197      * The USIM service table EF is described in as per Section 4.2.8 of 3GPP TS 31.102.
9198      * The ISIM service table EF is described in as per Section 4.2.7 of 3GPP TS 31.103.
9199      *
9200      * @param appType of type int of either {@link #APPTYPE_USIM} or {@link #APPTYPE_ISIM}.
9201      * @param executor executor to run the callback on.
9202      * @param callback callback object to which the result will be delivered.
9203      * @hide
9204      */
9205     @FlaggedApi(Flags.FLAG_SUPPORT_ISIM_RECORD)
9206     @SystemApi
9207     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9208     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimServiceTable(@iccAppType int appType, @NonNull @CallbackExecutor Executor executor, @NonNull OutcomeReceiver<byte[], Exception> callback)9209     public void getSimServiceTable(@UiccAppType int appType,
9210             @NonNull @CallbackExecutor Executor executor,
9211             @NonNull OutcomeReceiver<byte[], Exception> callback) {
9212         Objects.requireNonNull(executor);
9213         Objects.requireNonNull(callback);
9214 
9215         IPhoneSubInfo info = getSubscriberInfoService();
9216         if (info == null) {
9217             executor.execute(() -> callback.onError(
9218                     new RuntimeException("getSimServiceTable: Subscriber Info is null")));
9219             return;
9220         }
9221 
9222         try {
9223             String serviceTable;
9224             if (appType == APPTYPE_ISIM) {
9225                 serviceTable  = info.getIsimIst(getSubId());
9226             } else if ((appType == APPTYPE_USIM)) {
9227                 serviceTable = info.getSimServiceTable(getSubId(), APPTYPE_USIM);
9228             } else {
9229                 serviceTable = null;
9230             }
9231 
9232             if (serviceTable == null) {
9233                 executor.execute(() -> callback.onResult(new byte[0]));
9234             } else {
9235                 byte[] simServiceTable = IccUtils.hexStringToBytes(serviceTable);
9236                 executor.execute(() -> callback.onResult(simServiceTable));
9237             }
9238         } catch (Exception ex) {
9239             executor.execute(() -> callback.onError(ex));
9240         }
9241     }
9242 
9243     /**
9244      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
9245      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
9246      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
9247      * state.
9248      *
9249      * @param slotIndex the sim slot to reset the IMS stack on.
9250      *
9251      * @throws UnsupportedOperationException If the device does not have
9252      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
9253      * @hide */
9254     @SystemApi
9255     @WorkerThread
9256     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9257     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
resetIms(int slotIndex)9258     public void resetIms(int slotIndex) {
9259         try {
9260             ITelephony telephony = getITelephony();
9261             if (telephony != null) {
9262                 telephony.resetIms(slotIndex);
9263             }
9264         } catch (RemoteException e) {
9265             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
9266                     + e.getMessage());
9267         }
9268     }
9269 
9270     /**
9271      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
9272      * status updates, if not already enabled.
9273      * @hide
9274      */
enableIms(int slotId)9275     public void enableIms(int slotId) {
9276         try {
9277             ITelephony telephony = getITelephony();
9278             if (telephony != null) {
9279                 telephony.enableIms(slotId);
9280             }
9281         } catch (RemoteException e) {
9282             Rlog.e(TAG, "enableIms, RemoteException: "
9283                     + e.getMessage());
9284         }
9285     }
9286 
9287     /**
9288      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
9289      * status updates to disabled.
9290      * @hide
9291      */
disableIms(int slotId)9292     public void disableIms(int slotId) {
9293         try {
9294             ITelephony telephony = getITelephony();
9295             if (telephony != null) {
9296                 telephony.disableIms(slotId);
9297             }
9298         } catch (RemoteException e) {
9299             Rlog.e(TAG, "disableIms, RemoteException: "
9300                     + e.getMessage());
9301         }
9302     }
9303 
9304     /**
9305      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
9306      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
9307      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
9308      * Corresponds to features defined in ImsFeature.
9309      * @hide
9310      */
9311     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsRegistration(int slotIndex, int feature)9312     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
9313         try {
9314             ITelephony telephony = getITelephony();
9315             if (telephony != null) {
9316                 return telephony.getImsRegistration(slotIndex, feature);
9317             }
9318         } catch (RemoteException e) {
9319             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
9320         }
9321         return null;
9322     }
9323 
9324     /**
9325      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
9326      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
9327      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
9328      * Corresponds to features defined in ImsFeature.
9329      * @hide
9330      */
9331     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsConfig(int slotIndex, int feature)9332     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
9333         try {
9334             ITelephony telephony = getITelephony();
9335             if (telephony != null) {
9336                 return telephony.getImsConfig(slotIndex, feature);
9337             }
9338         } catch (RemoteException e) {
9339             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
9340         }
9341         return null;
9342     }
9343 
9344     /**
9345      * Set IMS registration state on all active subscriptions.
9346      * <p/>
9347      * Use {@link android.telephony.ims.stub.ImsRegistrationImplBase#onRegistered} and
9348      * {@link android.telephony.ims.stub.ImsRegistrationImplBase#onDeregistered} to set Ims
9349      * registration state instead.
9350      *
9351      * @param registered whether ims is registered
9352      *
9353      * @hide
9354      */
9355     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setImsRegistrationState(final boolean registered)9356     public void setImsRegistrationState(final boolean registered) {
9357         try {
9358             final ITelephony telephony = getITelephony();
9359             if (telephony != null)
9360                 telephony.setImsRegistrationState(registered);
9361         } catch (final RemoteException e) {
9362         }
9363     }
9364 
9365     /** @hide */
9366     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
9367             NETWORK_MODE_WCDMA_PREF,
9368             NETWORK_MODE_GSM_ONLY,
9369             NETWORK_MODE_WCDMA_ONLY,
9370             NETWORK_MODE_GSM_UMTS,
9371             NETWORK_MODE_CDMA_EVDO,
9372             NETWORK_MODE_CDMA_NO_EVDO,
9373             NETWORK_MODE_EVDO_NO_CDMA,
9374             NETWORK_MODE_GLOBAL,
9375             NETWORK_MODE_LTE_CDMA_EVDO,
9376             NETWORK_MODE_LTE_GSM_WCDMA,
9377             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
9378             NETWORK_MODE_LTE_ONLY,
9379             NETWORK_MODE_LTE_WCDMA,
9380             NETWORK_MODE_TDSCDMA_ONLY,
9381             NETWORK_MODE_TDSCDMA_WCDMA,
9382             NETWORK_MODE_LTE_TDSCDMA,
9383             NETWORK_MODE_TDSCDMA_GSM,
9384             NETWORK_MODE_LTE_TDSCDMA_GSM,
9385             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
9386             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
9387             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
9388             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
9389             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
9390             NETWORK_MODE_NR_ONLY,
9391             NETWORK_MODE_NR_LTE,
9392             NETWORK_MODE_NR_LTE_CDMA_EVDO,
9393             NETWORK_MODE_NR_LTE_GSM_WCDMA,
9394             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
9395             NETWORK_MODE_NR_LTE_WCDMA,
9396             NETWORK_MODE_NR_LTE_TDSCDMA,
9397             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
9398             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
9399             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
9400             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
9401     })
9402     @Retention(RetentionPolicy.SOURCE)
9403     public @interface PrefNetworkMode{}
9404 
9405     /**
9406      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
9407      * @hide
9408      */
9409     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
9410 
9411     /**
9412      * Preferred network mode is GSM only.
9413      * @hide
9414      */
9415     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
9416 
9417     /**
9418      * Preferred network mode is WCDMA only.
9419      * @hide
9420      */
9421     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
9422 
9423     /**
9424      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
9425      * @hide
9426      */
9427     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
9428 
9429     /**
9430      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
9431      * @deprecated Legacy CDMA is unsupported.
9432      * @hide
9433      */
9434     @Deprecated
9435     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
9436 
9437     /**
9438      * Preferred network mode is CDMA only.
9439      * @deprecated Legacy CDMA is unsupported.
9440      * @hide
9441      */
9442     @Deprecated
9443     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
9444 
9445     /**
9446      * Preferred network mode is EvDo only.
9447      * @deprecated Legacy CDMA is unsupported.
9448      * @hide
9449      */
9450     @Deprecated
9451     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
9452 
9453     /**
9454      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
9455      * @hide
9456      */
9457     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
9458 
9459     /**
9460      * Preferred network mode is LTE, CDMA and EvDo.
9461      * @deprecated Legacy CDMA is unsupported.
9462      * @hide
9463      */
9464     @Deprecated
9465     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
9466 
9467     /**
9468      * Preferred network mode is LTE, GSM/WCDMA.
9469      * @hide
9470      */
9471     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
9472 
9473     /**
9474      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
9475      * @deprecated Legacy CDMA is unsupported.
9476      * @hide
9477      */
9478     @Deprecated
9479     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
9480             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
9481 
9482     /**
9483      * Preferred network mode is LTE Only.
9484      * @hide
9485      */
9486     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
9487 
9488     /**
9489      * Preferred network mode is LTE/WCDMA.
9490      * @hide
9491      */
9492     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
9493 
9494     /**
9495      * Preferred network mode is TD-SCDMA only.
9496      * @hide
9497      */
9498     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
9499 
9500     /**
9501      * Preferred network mode is TD-SCDMA and WCDMA.
9502      * @hide
9503      */
9504     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
9505 
9506     /**
9507      * Preferred network mode is TD-SCDMA and LTE.
9508      * @hide
9509      */
9510     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
9511 
9512     /**
9513      * Preferred network mode is TD-SCDMA and GSM.
9514      * @hide
9515      */
9516     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
9517 
9518     /**
9519      * Preferred network mode is TD-SCDMA,GSM and LTE.
9520      * @hide
9521      */
9522     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
9523             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
9524 
9525     /**
9526      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
9527      * @hide
9528      */
9529     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
9530             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
9531 
9532     /**
9533      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
9534      * @hide
9535      */
9536     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
9537             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
9538 
9539     /**
9540      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
9541      * @hide
9542      */
9543     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
9544             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
9545 
9546     /**
9547      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
9548      * @deprecated Legacy CDMA is unsupported.
9549      * @hide
9550      */
9551     @Deprecated
9552     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
9553             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
9554     /**
9555      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
9556      * @deprecated Legacy CDMA is unsupported.
9557      * @hide
9558      */
9559     @Deprecated
9560     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
9561             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
9562 
9563     /**
9564      * Preferred network mode is NR 5G only.
9565      * @hide
9566      */
9567     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
9568 
9569     /**
9570      * Preferred network mode is NR 5G, LTE.
9571      * @hide
9572      */
9573     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
9574 
9575     /**
9576      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
9577      * @deprecated Legacy CDMA is unsupported.
9578      * @hide
9579      */
9580     @Deprecated
9581     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
9582             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
9583 
9584     /**
9585      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
9586      * @hide
9587      */
9588     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
9589             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
9590 
9591     /**
9592      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
9593      * @deprecated Legacy CDMA is unsupported.
9594      * @hide
9595      */
9596     @Deprecated
9597     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
9598             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
9599 
9600     /**
9601      * Preferred network mode is NR 5G, LTE and WCDMA.
9602      * @hide
9603      */
9604     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
9605 
9606     /**
9607      * Preferred network mode is NR 5G, LTE and TDSCDMA.
9608      * @hide
9609      */
9610     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
9611 
9612     /**
9613      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
9614      * @hide
9615      */
9616     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
9617             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
9618 
9619     /**
9620      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
9621      * @hide
9622      */
9623     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
9624             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
9625 
9626     /**
9627      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
9628      * @hide
9629      */
9630     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
9631             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
9632 
9633     /**
9634      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
9635      * @deprecated Legacy CDMA is unsupported.
9636      * @hide
9637      */
9638     @Deprecated
9639     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
9640             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
9641 
9642     /**
9643      * The default preferred network mode constant.
9644      *
9645      * <p> This constant is used in case of nothing is set in
9646      * TelephonyProperties#default_network().
9647      *
9648      * @hide
9649      */
9650     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
9651             RILConstants.PREFERRED_NETWORK_MODE;
9652 
9653     /**
9654      * Get the preferred network type.
9655      * Used for device configuration by some CDMA operators.
9656      *
9657      * <p>Requires Permission:
9658      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9659      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9660      *
9661      * @return the preferred network type.
9662      * @hide
9663      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
9664      */
9665     @Deprecated
9666     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
9667     @UnsupportedAppUsage
getPreferredNetworkType(int subId)9668     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
9669         return RadioAccessFamily.getNetworkTypeFromRaf((int) getAllowedNetworkTypesBitmask());
9670     }
9671 
9672     /**
9673      * Get the preferred network type bitmask.
9674      *
9675      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9676      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9677      *
9678      * <p>Requires Permission:
9679      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9680      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9681      *
9682      * @return The bitmask of preferred network types.
9683      *
9684      * @throws UnsupportedOperationException If the device does not have
9685      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9686      * @hide
9687      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
9688      */
9689     @Deprecated
9690     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9691     @SystemApi
9692     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getPreferredNetworkTypeBitmask()9693     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
9694         return getAllowedNetworkTypesBitmask();
9695     }
9696 
9697     /**
9698      * Get the allowed network type bitmask.
9699      * Note that the device can only register on the network of {@link NetworkTypeBitmask}
9700      * (except for emergency call cases).
9701      *
9702      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9703      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9704      *
9705      * <p>Requires Permission:
9706      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9707      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9708      *
9709      * @return The bitmask of allowed network types.
9710      *
9711      * @throws UnsupportedOperationException If the device does not have
9712      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9713      * @hide
9714      */
9715     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9716     @SystemApi
9717     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getAllowedNetworkTypesBitmask()9718     public @NetworkTypeBitMask long getAllowedNetworkTypesBitmask() {
9719         try {
9720             ITelephony telephony = getITelephony();
9721             if (telephony != null) {
9722                 return (long) telephony.getAllowedNetworkTypesBitmask(getSubId());
9723             }
9724         } catch (RemoteException ex) {
9725             Rlog.e(TAG, "getAllowedNetworkTypesBitmask RemoteException", ex);
9726         }
9727         return 0;
9728     }
9729 
9730     /**
9731      * Get the allowed network types by carriers.
9732      *
9733      * <p>Requires Permission:
9734      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
9735      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
9736      *
9737      * @return the allowed network type bitmask
9738      *
9739      * @throws UnsupportedOperationException If the device does not have
9740      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9741      * @hide
9742      * @deprecated Use {@link #getAllowedNetworkTypesForReason} instead.
9743      */
9744     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9745     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
9746     @SystemApi
9747     @Deprecated
getAllowedNetworkTypes()9748     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
9749         try {
9750             ITelephony telephony = getITelephony();
9751             if (telephony != null) {
9752                 return telephony.getAllowedNetworkTypesForReason(getSubId(),
9753                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER);
9754             }
9755         } catch (RemoteException ex) {
9756             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
9757         }
9758         return -1;
9759     }
9760 
9761     /**
9762      * Sets the network selection mode to automatic.
9763      *
9764      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9765      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9766      *
9767      * <p>Requires Permission:
9768      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9769      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9770      *
9771      * @throws UnsupportedOperationException If the device does not have
9772      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9773      */
9774     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9775     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9776     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeAutomatic()9777     public void setNetworkSelectionModeAutomatic() {
9778         try {
9779             ITelephony telephony = getITelephony();
9780             if (telephony != null) {
9781                 telephony.setNetworkSelectionModeAutomatic(getSubId());
9782             }
9783         } catch (RemoteException ex) {
9784             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
9785         } catch (NullPointerException ex) {
9786             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
9787         }
9788     }
9789 
9790     /**
9791      * Perform a radio scan and return the list of available networks.
9792      *
9793      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9794      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9795      *
9796      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
9797      *
9798      * <p>Requires Permissions:
9799      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
9800      * privileges (see {@link #hasCarrierPrivileges})
9801      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
9802      *
9803      * @return {@link CellNetworkScanResult} with the status
9804      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
9805      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
9806      * caused will be included in the result.
9807      *
9808      * @hide
9809      */
9810     @RequiresPermission(allOf = {
9811             android.Manifest.permission.MODIFY_PHONE_STATE,
9812             Manifest.permission.ACCESS_COARSE_LOCATION
9813     })
getAvailableNetworks()9814     public CellNetworkScanResult getAvailableNetworks() {
9815         try {
9816             ITelephony telephony = getITelephony();
9817             if (telephony != null) {
9818                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
9819                         getAttributionTag());
9820             }
9821         } catch (RemoteException ex) {
9822             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
9823         } catch (NullPointerException ex) {
9824             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
9825         }
9826         return new CellNetworkScanResult(
9827                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
9828     }
9829 
9830     /**
9831      * Request a network scan.
9832      *
9833      * This method is asynchronous, so the network scan results will be returned by callback.
9834      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
9835      *
9836      * <p>Requires Permission:
9837      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9838      * app has carrier privileges (see {@link #hasCarrierPrivileges})
9839      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
9840      *
9841      * If the system-wide location switch is off, apps may still call this API, with the
9842      * following constraints:
9843      * <ol>
9844      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
9845      *     <li>The app must not supply any specific bands or channels to scan.</li>
9846      *     <li>The app must only specify MCC/MNC pairs that are
9847      *     associated to a SIM in the device.</li>
9848      *     <li>Returned results will have no meaningful info other than signal strength
9849      *     and MCC/MNC info.</li>
9850      * </ol>
9851      *
9852      * @param request Contains all the RAT with bands/channels that need to be scanned.
9853      * @param executor The executor through which the callback should be invoked. Since the scan
9854      *        request may trigger multiple callbacks and they must be invoked in the same order as
9855      *        they are received by the platform, the user should provide an executor which executes
9856      *        tasks one at a time in serial order.
9857      * @param callback Returns network scan results or errors.
9858      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
9859      *
9860      * @throws UnsupportedOperationException If the device does not have
9861      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9862      */
9863     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9864     @RequiresPermission(allOf = {
9865             android.Manifest.permission.MODIFY_PHONE_STATE,
9866             Manifest.permission.ACCESS_FINE_LOCATION
9867     })
9868     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)9869     public NetworkScan requestNetworkScan(
9870             NetworkScanRequest request, Executor executor,
9871             TelephonyScanManager.NetworkScanCallback callback) {
9872         return requestNetworkScan(INCLUDE_LOCATION_DATA_FINE, request, executor, callback);
9873     }
9874 
9875     /**
9876      * Request a network scan.
9877      *
9878      * This method is asynchronous, so the network scan results will be returned by callback.
9879      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
9880      *
9881      * <p>Requires Permission:
9882      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9883      * app has carrier privileges (see {@link #hasCarrierPrivileges})
9884      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION} if includeLocationData is
9885      * set to {@link #INCLUDE_LOCATION_DATA_FINE}.
9886      *
9887      * If the system-wide location switch is off, apps may still call this API, with the
9888      * following constraints:
9889      * <ol>
9890      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
9891      *     <li>The app must not supply any specific bands or channels to scan.</li>
9892      *     <li>The app must only specify MCC/MNC pairs that are
9893      *     associated to a SIM in the device.</li>
9894      *     <li>Returned results will have no meaningful info other than signal strength
9895      *     and MCC/MNC info.</li>
9896      * </ol>
9897      *
9898      * @param includeLocationData Specifies if the caller would like to receive
9899      * location related information. If this parameter is set to
9900      * {@link #INCLUDE_LOCATION_DATA_FINE} then the application will be checked for
9901      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission and available
9902      * location related information received during network scan will be sent to the caller.
9903      * @param request Contains all the RAT with bands/channels that need to be scanned.
9904      * @param executor The executor through which the callback should be invoked. Since the scan
9905      *        request may trigger multiple callbacks and they must be invoked in the same order as
9906      *        they are received by the platform, the user should provide an executor which executes
9907      *        tasks one at a time in serial order.
9908      * @param callback Returns network scan results or errors.
9909      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
9910      *
9911      * @throws UnsupportedOperationException If the device does not have
9912      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9913      */
9914     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9915     @RequiresPermission(allOf = {
9916             android.Manifest.permission.MODIFY_PHONE_STATE
9917     })
9918     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( @ncludeLocationData int includeLocationData, @NonNull NetworkScanRequest request, @NonNull Executor executor, @NonNull TelephonyScanManager.NetworkScanCallback callback)9919     public @Nullable NetworkScan requestNetworkScan(
9920             @IncludeLocationData int includeLocationData,
9921             @NonNull NetworkScanRequest request,
9922             @NonNull Executor executor,
9923             @NonNull TelephonyScanManager.NetworkScanCallback callback) {
9924         synchronized (sCacheLock) {
9925             if (mTelephonyScanManager == null) {
9926                 mTelephonyScanManager = new TelephonyScanManager();
9927             }
9928         }
9929         return mTelephonyScanManager.requestNetworkScan(getSubId(),
9930                 includeLocationData != INCLUDE_LOCATION_DATA_FINE,
9931                 request, executor, callback,
9932                 getOpPackageName(), getAttributionTag());
9933     }
9934 
9935     /**
9936      * @throws UnsupportedOperationException If the device does not have
9937      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9938      *
9939      * @deprecated
9940      * Use {@link
9941      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
9942      * @removed
9943      */
9944     @Deprecated
9945     @RequiresPermission(allOf = {
9946             android.Manifest.permission.MODIFY_PHONE_STATE,
9947             Manifest.permission.ACCESS_FINE_LOCATION
9948     })
9949     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)9950     public NetworkScan requestNetworkScan(
9951         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
9952         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
9953     }
9954 
9955     /**
9956      * Ask the radio to connect to the input network and change selection mode to manual.
9957      *
9958      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9959      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9960      *
9961      * <p>Requires Permission:
9962      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9963      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9964      *
9965      * @param operatorNumeric the PLMN ID of the network to select.
9966      * @param persistSelection whether the selection will persist until reboot. If true, only allows
9967      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
9968      * normal network selection next time.
9969      * @return {@code true} on success; {@code false} on any failure.
9970      *
9971      * @throws UnsupportedOperationException If the device does not have
9972      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
9973      */
9974     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9975     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9976     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)9977     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
9978         return setNetworkSelectionModeManual(
9979                 new OperatorInfo(
9980                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
9981                 persistSelection);
9982     }
9983 
9984     /**
9985      * Ask the radio to connect to the input network and change selection mode to manual.
9986      *
9987      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9988      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9989      *
9990      * <p>Requires Permission:
9991      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9992      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9993      *
9994      * @param operatorNumeric the PLMN ID of the network to select.
9995      * @param persistSelection whether the selection will persist until reboot.
9996      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
9997      *         attach to the chosen PLMN and resume normal network selection next time.
9998      * @param ran the initial suggested radio access network type.
9999      *         If registration fails, the RAN is not available after, the RAN is not within the
10000      *         network types specified by the preferred network types, or the value is
10001      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
10002      *         the next best RAN for network registration.
10003      * @return {@code true} on success; {@code false} on any failure.
10004      *
10005      * @throws UnsupportedOperationException If the device does not have
10006      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10007      */
10008     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10009     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)10010     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
10011             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
10012         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
10013                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
10014     }
10015 
10016     /**
10017      * Ask the radio to connect to the input network and change selection mode to manual.
10018      *
10019      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10020      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10021      *
10022      * <p>Requires Permission:
10023      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10024      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10025      *
10026      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
10027      * @param persistSelection whether the selection will persist until reboot. If true, only allows
10028      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
10029      * normal network selection next time.
10030      * @return {@code true} on success; {@code true} on any failure.
10031      *
10032      * @hide
10033      */
10034     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)10035     public boolean setNetworkSelectionModeManual(
10036             OperatorInfo operatorInfo, boolean persistSelection) {
10037         try {
10038             ITelephony telephony = getITelephony();
10039             if (telephony != null) {
10040                 return telephony.setNetworkSelectionModeManual(
10041                         getSubId(), operatorInfo, persistSelection);
10042             }
10043         } catch (RemoteException ex) {
10044             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
10045         }
10046         return false;
10047     }
10048 
10049     /**
10050      * Get the network selection mode.
10051      *
10052      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10053      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10054      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
10055      * READ_PRECISE_PHONE_STATE}
10056      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10057      *
10058      * @return the network selection mode.
10059      *
10060      * @throws UnsupportedOperationException If the device does not have
10061      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10062      */
10063     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
10064     @RequiresPermission(anyOf = {
10065             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10066             android.Manifest.permission.READ_PRECISE_PHONE_STATE
10067     })
10068     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getNetworkSelectionMode()10069     public @NetworkSelectionMode int getNetworkSelectionMode() {
10070         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
10071         try {
10072             ITelephony telephony = getITelephony();
10073             if (telephony != null) {
10074                 mode = telephony.getNetworkSelectionMode(getSubId());
10075             }
10076         } catch (RemoteException ex) {
10077             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
10078         }
10079         return mode;
10080     }
10081 
10082     /**
10083      * Get the PLMN chosen for Manual Network Selection if active.
10084      * Return empty string if in automatic selection.
10085      *
10086      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
10087      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
10088      * (see {@link #hasCarrierPrivileges})
10089      *
10090      * @return manually selected network info on success or empty string on failure
10091      *
10092      * @throws UnsupportedOperationException If the device does not have
10093      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10094      */
10095     @SuppressAutoDoc // No support carrier privileges (b/72967236).
10096     @RequiresPermission(android.Manifest.permission.READ_PRECISE_PHONE_STATE)
10097     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getManualNetworkSelectionPlmn()10098     public @NonNull String getManualNetworkSelectionPlmn() {
10099         try {
10100             ITelephony telephony = getITelephony();
10101             if (telephony != null && isManualNetworkSelectionAllowed()) {
10102                 return telephony.getManualNetworkSelectionPlmn(getSubId());
10103             }
10104         } catch (RemoteException ex) {
10105             Rlog.e(TAG, "getManualNetworkSelectionPlmn RemoteException", ex);
10106         }
10107         return "";
10108     }
10109 
10110     /**
10111      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
10112      * user and we are still within the time interval after the emergency SMS was sent that we are
10113      * considered in Emergency SMS mode.
10114      *
10115      * <p>This mode is used by other applications to allow them to perform special functionality,
10116      * such as allow the GNSS service to provide user location to the carrier network for emergency
10117      * when an emergency SMS is sent. This interval is set by
10118      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
10119      * the carrier does not support this mode, this function will always return false.
10120      *
10121      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
10122      *
10123      * @throws UnsupportedOperationException If the device does not have
10124      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
10125      * @hide
10126      */
10127     @SystemApi
10128     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10129     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
isInEmergencySmsMode()10130     public boolean isInEmergencySmsMode() {
10131         try {
10132             ITelephony telephony = getITelephony();
10133             if (telephony != null) {
10134                 return telephony.isInEmergencySmsMode();
10135             }
10136         } catch (RemoteException ex) {
10137             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
10138         }
10139         return false;
10140     }
10141 
10142     /**
10143      * Set the preferred network type.
10144      *
10145      * <p>Requires Permission:
10146      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10147      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10148      * <p>
10149      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
10150      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
10151      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
10152      * setPreferredNetworkTypesBitmap is used instead.
10153      *
10154      * @param subId the id of the subscription to set the preferred network type for.
10155      * @param networkType the preferred network type
10156      * @return true on success; false on any failure.
10157      * @hide
10158      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
10159      */
10160     @Deprecated
10161     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)10162     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
10163         try {
10164             ITelephony telephony = getITelephony();
10165             if (telephony != null) {
10166                 return telephony.setAllowedNetworkTypesForReason(subId,
10167                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
10168                         RadioAccessFamily.getRafFromNetworkType(networkType));
10169             }
10170         } catch (RemoteException ex) {
10171             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
10172         }
10173         return false;
10174     }
10175 
10176     /**
10177      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
10178      * only the allowed network type will set to the modem.
10179      *
10180      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10181      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10182      *
10183      * <p>Requires Permission:
10184      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10185      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10186      * <p>
10187      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
10188      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
10189      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
10190      * setPreferredNetworkTypesBitmap is used instead.
10191      *
10192      * @param networkTypeBitmask The bitmask of preferred network types.
10193      * @return true on success; false on any failure.
10194      *
10195      * @throws UnsupportedOperationException If the device does not have
10196      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10197      * @hide
10198      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
10199      */
10200     @Deprecated
10201     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10202     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
10203     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)10204     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
10205         try {
10206             ITelephony telephony = getITelephony();
10207             if (telephony != null) {
10208                 networkTypeBitmask = checkNetworkTypeBitmask(networkTypeBitmask);
10209                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
10210                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER, networkTypeBitmask);
10211             }
10212         } catch (RemoteException ex) {
10213             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
10214         }
10215         return false;
10216     }
10217 
10218     /**
10219      * If {@link #NETWORK_TYPE_BITMASK_LTE_CA} bit is set, convert it to NETWORK_TYPE_BITMASK_LTE.
10220      *
10221      * @param networkTypeBitmask The networkTypeBitmask being checked
10222      * @return The checked/converted networkTypeBitmask
10223      */
checkNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)10224     private long checkNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
10225         if ((networkTypeBitmask & NETWORK_TYPE_BITMASK_LTE_CA) != 0) {
10226             networkTypeBitmask ^= NETWORK_TYPE_BITMASK_LTE_CA;
10227             networkTypeBitmask |= NETWORK_TYPE_BITMASK_LTE;
10228         }
10229         return networkTypeBitmask;
10230     }
10231 
10232     /**
10233      * Set the allowed network types of the device. This is for carrier or privileged apps to
10234      * enable/disable certain network types on the device. The user preferred network types should
10235      * be set through {@link #setPreferredNetworkTypeBitmask}.
10236      * <p>
10237      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
10238      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
10239      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
10240      * setPreferredNetworkTypesBitmap is used instead.
10241      *
10242      * @param allowedNetworkTypes The bitmask of allowed network types.
10243      * @return true on success; false on any failure.
10244      *
10245      * @throws UnsupportedOperationException If the device does not have
10246      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10247      *
10248      * @hide
10249      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead with reason
10250      * {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}.
10251      */
10252     @Deprecated
10253     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10254     @RequiresFeature(
10255             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
10256             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
10257     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)10258     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
10259         try {
10260             ITelephony telephony = getITelephony();
10261             if (telephony != null) {
10262                 allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
10263                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
10264                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER, allowedNetworkTypes);
10265             }
10266         } catch (RemoteException ex) {
10267             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
10268         }
10269         return false;
10270     }
10271 
10272     /** @hide */
10273     @IntDef({
10274             ALLOWED_NETWORK_TYPES_REASON_USER,
10275             ALLOWED_NETWORK_TYPES_REASON_POWER,
10276             ALLOWED_NETWORK_TYPES_REASON_CARRIER,
10277             ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G,
10278             ALLOWED_NETWORK_TYPES_REASON_TEST,
10279     })
10280     @Retention(RetentionPolicy.SOURCE)
10281     public @interface AllowedNetworkTypesReason {
10282     }
10283 
10284     /**
10285      * To indicate allowed network type change is requested by user.
10286      */
10287     public static final int ALLOWED_NETWORK_TYPES_REASON_USER = 0;
10288 
10289     /**
10290      * To indicate allowed network type change is requested by power manager.
10291      * Power Manger configuration won't affect the settings configured through
10292      * other reasons and will result in allowing network types that are in both
10293      * configurations (i.e intersection of both sets).
10294      *
10295      * @hide
10296      */
10297     @SystemApi
10298     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 1;
10299 
10300     /**
10301      * To indicate allowed network type change is requested by carrier.
10302      * Carrier configuration won't affect the settings configured through
10303      * other reasons and will result in allowing network types that are in both
10304      * configurations (i.e intersection of both sets).
10305      */
10306     public static final int ALLOWED_NETWORK_TYPES_REASON_CARRIER = 2;
10307 
10308     /**
10309      * To indicate allowed network type change is requested by the user via the 2G toggle.
10310      *
10311      * @hide
10312      */
10313     @SystemApi
10314     public static final int ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G = 3;
10315 
10316     /**
10317      * To indicate allowed network type change is requested by Testing purpose, should be default to
10318      * {@link #getAllNetworkTypesBitmask} when done testing.
10319      *
10320      * @hide
10321      */
10322     public static final int ALLOWED_NETWORK_TYPES_REASON_TEST = 4;
10323 
10324     /**
10325      * Set the allowed network types of the device and provide the reason triggering the allowed
10326      * network change.
10327      * <p>Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
10328      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10329      *
10330      * This can be called for following reasons:
10331      * <ol>
10332      * <li>Allowed network types control by USER
10333      * {@link TelephonyManager#ALLOWED_NETWORK_TYPES_REASON_USER}
10334      * <li>Allowed network types control by carrier {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}
10335      * </ol>
10336      * This API will result in allowing an intersection of allowed network types for all reasons,
10337      * including the configuration done through other reasons.
10338      *
10339      * @param reason the reason the allowed network type change is taking place
10340      * @param allowedNetworkTypes The bitmask of allowed network type
10341      * @throws IllegalStateException if the Telephony process is not currently available.
10342      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
10343      * @throws SecurityException if the caller does not have the required privileges or if the
10344      * @throws UnsupportedOperationException If the device does not have
10345      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10346      * caller tries to use one of the following security-based reasons without
10347      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} permissions.
10348      * <ol>
10349      *     <li>{@code TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G}</li>
10350      * </ol>
10351      *
10352      * @throws UnsupportedOperationException If the device does not have
10353      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10354      */
10355     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10356     @RequiresFeature(
10357             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
10358             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)10359     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
10360             @NetworkTypeBitMask long allowedNetworkTypes) {
10361         if (!isValidAllowedNetworkTypesReason(reason)) {
10362             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
10363         }
10364 
10365         try {
10366             ITelephony telephony = getITelephony();
10367             if (telephony != null) {
10368                 allowedNetworkTypes = checkNetworkTypeBitmask(allowedNetworkTypes);
10369                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
10370                         allowedNetworkTypes);
10371             } else {
10372                 throw new IllegalStateException("telephony service is null.");
10373             }
10374         } catch (RemoteException ex) {
10375             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
10376             ex.rethrowFromSystemServer();
10377         }
10378     }
10379 
10380     /**
10381      * Get the allowed network types for certain reason.
10382      *
10383      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
10384      * specific reason.
10385      * <p>Requires permission: android.Manifest.READ_PRIVILEGED_PHONE_STATE or
10386      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10387      *
10388      * @param reason the reason the allowed network type change is taking place
10389      * @return the allowed network type bitmask
10390      * @throws IllegalStateException    if the Telephony process is not currently available.
10391      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
10392      * @throws SecurityException if the caller does not have the required permission/privileges
10393      * @throws UnsupportedOperationException If the device does not have
10394      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10395      */
10396     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10397     @RequiresFeature(
10398             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
10399             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)10400     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
10401             @AllowedNetworkTypesReason int reason) {
10402         if (!isValidAllowedNetworkTypesReason(reason)) {
10403             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
10404         }
10405 
10406         try {
10407             ITelephony telephony = getITelephony();
10408             if (telephony != null) {
10409                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
10410             } else {
10411                 throw new IllegalStateException("telephony service is null.");
10412             }
10413         } catch (RemoteException ex) {
10414             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
10415             ex.rethrowFromSystemServer();
10416         }
10417         return -1;
10418     }
10419     /**
10420      * Verifies that the reason provided is valid.
10421      * @hide
10422      */
isValidAllowedNetworkTypesReason(@llowedNetworkTypesReason int reason)10423     public static boolean isValidAllowedNetworkTypesReason(@AllowedNetworkTypesReason int reason) {
10424         switch (reason) {
10425             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER:
10426             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER:
10427             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER:
10428             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G:
10429                 return true;
10430             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_TEST:
10431                 return TelephonyUtils.IS_DEBUGGABLE;
10432         }
10433         return false;
10434     }
10435     /**
10436      * Get bit mask of all network types.
10437      *
10438      * @return bit mask of all network types
10439      * @hide
10440      */
getAllNetworkTypesBitmask()10441     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
10442         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
10443     }
10444 
10445     /**
10446      * Returns a string representation of the allowed network types{@link NetworkTypeBitMask}.
10447      *
10448      * @param networkTypeBitmask The bitmask of allowed network types.
10449      * @return the name of the allowed network types
10450      * @hide
10451      */
convertNetworkTypeBitmaskToString( @etworkTypeBitMask long networkTypeBitmask)10452     public static String convertNetworkTypeBitmaskToString(
10453             @NetworkTypeBitMask long networkTypeBitmask) {
10454         String networkTypeName = IntStream.rangeClosed(NETWORK_TYPE_GPRS, NETWORK_TYPE_NR)
10455                 .filter(x -> {
10456                     return (networkTypeBitmask & getBitMaskForNetworkType(x))
10457                             == getBitMaskForNetworkType(x);
10458                 })
10459                 .mapToObj(x -> getNetworkTypeName(x))
10460                 .collect(Collectors.joining("|"));
10461         return TextUtils.isEmpty(networkTypeName) ? "UNKNOWN" : networkTypeName;
10462     }
10463 
10464     /**
10465      * Set the preferred network type to global mode which includes NR, LTE, CDMA, EvDo
10466      * and GSM/WCDMA.
10467      *
10468      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10469      *
10470      * @return true on success; false on any failure.
10471      *
10472      * @throws UnsupportedOperationException If the device does not have
10473      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
10474      */
10475     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setPreferredNetworkTypeToGlobal()10476     public boolean setPreferredNetworkTypeToGlobal() {
10477         return setPreferredNetworkTypeToGlobal(getSubId());
10478     }
10479 
10480     /**
10481      * Set the preferred network type to global mode which includes NR, LTE, CDMA, EvDo
10482      * and GSM/WCDMA.
10483      *
10484      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10485      *
10486      * @return true on success; false on any failure.
10487      * @hide
10488      */
setPreferredNetworkTypeToGlobal(int subId)10489     public boolean setPreferredNetworkTypeToGlobal(int subId) {
10490         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA);
10491     }
10492 
10493     /**
10494      * Check whether DUN APN is required for tethering.
10495      * <p>
10496      * Requires Permission: MODIFY_PHONE_STATE.
10497      *
10498      * @return {@code true} if DUN APN is required for tethering.
10499      *
10500      * @throws UnsupportedOperationException If the device does not have
10501      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
10502      * @hide
10503      */
10504     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10505     @SystemApi
10506     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isTetheringApnRequired()10507     public boolean isTetheringApnRequired() {
10508         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
10509     }
10510 
10511     /**
10512      * Check whether DUN APN is required for tethering with subId.
10513      *
10514      * @param subId the id of the subscription to require tethering.
10515      * @return {@code true} if DUN APN is required for tethering.
10516      * @hide
10517      */
isTetheringApnRequired(int subId)10518     public boolean isTetheringApnRequired(int subId) {
10519         try {
10520             ITelephony telephony = getITelephony();
10521             if (telephony != null)
10522                 return telephony.isTetheringApnRequiredForSubscriber(subId);
10523         } catch (RemoteException ex) {
10524             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
10525         } catch (NullPointerException ex) {
10526             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
10527         }
10528         return false;
10529     }
10530 
10531 
10532     /**
10533      * Values used to return status for hasCarrierPrivileges call.
10534      */
10535     /** @hide */ @SystemApi
10536     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
10537     /** @hide */ @SystemApi
10538     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
10539     /** @hide */ @SystemApi
10540     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
10541     /** @hide */ @SystemApi
10542     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
10543 
10544     /**
10545      * Has the calling application been granted carrier privileges by the carrier.
10546      *
10547      * If any of the packages in the calling UID has carrier privileges, the
10548      * call will return true. This access is granted by the owner of the UICC
10549      * card and does not depend on the registered carrier.
10550      *
10551      * Note that this API applies to both physical and embedded subscriptions and
10552      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
10553      *
10554      * @return true if the app has carrier privileges.
10555      *
10556      * @throws UnsupportedOperationException If the device does not have
10557      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10558      */
10559     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
hasCarrierPrivileges()10560     public boolean hasCarrierPrivileges() {
10561         return hasCarrierPrivileges(getSubId());
10562     }
10563 
10564     /**
10565      * Has the calling application been granted carrier privileges by the carrier.
10566      *
10567      * If any of the packages in the calling UID has carrier privileges, the
10568      * call will return true. This access is granted by the owner of the UICC
10569      * card and does not depend on the registered carrier.
10570      *
10571      * Note that this API applies to both physical and embedded subscriptions and
10572      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
10573      *
10574      * @param subId The subscription to use.
10575      * @return true if the app has carrier privileges.
10576      * @hide
10577      */
hasCarrierPrivileges(int subId)10578     public boolean hasCarrierPrivileges(int subId) {
10579         try {
10580             ITelephony telephony = getITelephony();
10581             if (telephony == null) {
10582                 Rlog.e(TAG, "hasCarrierPrivileges: no Telephony service");
10583                 return false;
10584             }
10585             int status = telephony.getCarrierPrivilegeStatus(subId);
10586             switch (status) {
10587                 case CARRIER_PRIVILEGE_STATUS_HAS_ACCESS:
10588                     return true;
10589                 case CARRIER_PRIVILEGE_STATUS_NO_ACCESS:
10590                     return false;
10591                 default:
10592                     Rlog.e(TAG, "hasCarrierPrivileges: " + status);
10593                     return false;
10594             }
10595         } catch (RemoteException ex) {
10596             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
10597         } catch (NullPointerException ex) {
10598             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
10599         }
10600         return false;
10601     }
10602 
10603     /**
10604      * Override the branding for the current ICCID.
10605      *
10606      * Once set, whenever the SIM is present in the device, the service
10607      * provider name (SPN) and the operator name will both be replaced by the
10608      * brand value input. To unset the value, the same function should be
10609      * called with a null brand value.
10610      *
10611      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10612      *
10613      * @param brand The brand name to display/set.
10614      * @return true if the operation was executed correctly.
10615      *
10616      * @throws UnsupportedOperationException If the device does not have
10617      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10618      */
10619     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setOperatorBrandOverride(String brand)10620     public boolean setOperatorBrandOverride(String brand) {
10621         return setOperatorBrandOverride(getSubId(), brand);
10622     }
10623 
10624     /**
10625      * Override the branding for the current ICCID.
10626      *
10627      * Once set, whenever the SIM is present in the device, the service
10628      * provider name (SPN) and the operator name will both be replaced by the
10629      * brand value input. To unset the value, the same function should be
10630      * called with a null brand value.
10631      *
10632      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10633      *
10634      * @param subId The subscription to use.
10635      * @param brand The brand name to display/set.
10636      * @return true if the operation was executed correctly.
10637      * @hide
10638      */
setOperatorBrandOverride(int subId, String brand)10639     public boolean setOperatorBrandOverride(int subId, String brand) {
10640         try {
10641             ITelephony telephony = getITelephony();
10642             if (telephony != null)
10643                 return telephony.setOperatorBrandOverride(subId, brand);
10644         } catch (RemoteException ex) {
10645             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
10646         } catch (NullPointerException ex) {
10647             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
10648         }
10649         return false;
10650     }
10651 
10652     /**
10653      * Override the roaming preference for the current ICCID.
10654      *
10655      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
10656      * the platform's notion of a network operator being considered roaming or not.
10657      * The change only affects the ICCID that was active when this call was made.
10658      *
10659      * If null is passed as any of the input, the corresponding value is deleted.
10660      *
10661      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
10662      *
10663      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
10664      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
10665      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
10666      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
10667      * @return true if the operation was executed correctly.
10668      *
10669      * @hide
10670      */
10671     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)10672     public boolean setRoamingOverride(List<String> gsmRoamingList,
10673             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
10674             List<String> cdmaNonRoamingList) {
10675         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
10676                 cdmaRoamingList, cdmaNonRoamingList);
10677     }
10678 
10679     /**
10680      * Override the roaming preference for the current ICCID.
10681      *
10682      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
10683      * the platform's notion of a network operator being considered roaming or not.
10684      * The change only affects the ICCID that was active when this call was made.
10685      *
10686      * If null is passed as any of the input, the corresponding value is deleted.
10687      *
10688      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
10689      *
10690      * @param subId for which the roaming overrides apply.
10691      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
10692      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
10693      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
10694      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
10695      * @return true if the operation was executed correctly.
10696      *
10697      * @hide
10698      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)10699     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
10700             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
10701             List<String> cdmaNonRoamingList) {
10702         try {
10703             ITelephony telephony = getITelephony();
10704             if (telephony != null)
10705                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
10706                         cdmaRoamingList, cdmaNonRoamingList);
10707         } catch (RemoteException ex) {
10708             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
10709         } catch (NullPointerException ex) {
10710             Rlog.e(TAG, "setRoamingOverride NPE", ex);
10711         }
10712         return false;
10713     }
10714 
10715     /**
10716      * Expose the rest of ITelephony to @SystemApi
10717      */
10718 
10719     /**
10720      * @throws UnsupportedOperationException If the device does not have
10721      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10722      * @deprecated Legacy CDMA is unsupported.
10723      * @hide
10724      */
10725     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
10726     @Deprecated
10727     @SystemApi
10728     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10729     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMdn()10730     public String getCdmaMdn() {
10731         if (Flags.cleanupCdma()) return null;
10732         return getCdmaMdn(getSubId());
10733     }
10734 
10735     /**
10736      * @throws UnsupportedOperationException If the device does not have
10737      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10738      * @deprecated Legacy CDMA is unsupported.
10739      * @hide
10740      */
10741     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
10742     @Deprecated
10743     @SystemApi
10744     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10745     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMdn(int subId)10746     public String getCdmaMdn(int subId) {
10747         if (Flags.cleanupCdma()) return null;
10748         try {
10749             ITelephony telephony = getITelephony();
10750             if (telephony == null)
10751                 return null;
10752             return telephony.getCdmaMdn(subId);
10753         } catch (RemoteException ex) {
10754             return null;
10755         } catch (NullPointerException ex) {
10756             return null;
10757         }
10758     }
10759 
10760     /**
10761      * @throws UnsupportedOperationException If the device does not have
10762      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10763      * @deprecated Legacy CDMA is unsupported.
10764      * @hide
10765      */
10766     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
10767     @Deprecated
10768     @SystemApi
10769     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10770     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMin()10771     public String getCdmaMin() {
10772         if (Flags.cleanupCdma()) return null;
10773         return getCdmaMin(getSubId());
10774     }
10775 
10776     /**
10777      * @throws UnsupportedOperationException If the device does not have
10778      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
10779      * @deprecated Legacy CDMA is unsupported.
10780      * @hide
10781      */
10782     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
10783     @Deprecated
10784     @SystemApi
10785     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
10786     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaMin(int subId)10787     public String getCdmaMin(int subId) {
10788         if (Flags.cleanupCdma()) return null;
10789         try {
10790             ITelephony telephony = getITelephony();
10791             if (telephony == null)
10792                 return null;
10793             return telephony.getCdmaMin(subId);
10794         } catch (RemoteException ex) {
10795             return null;
10796         } catch (NullPointerException ex) {
10797             return null;
10798         }
10799     }
10800 
10801     /**
10802      * @throws UnsupportedOperationException If the device does not have
10803      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10804      * @hide
10805      */
10806     @SystemApi
10807     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10808     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
checkCarrierPrivilegesForPackage(String pkgName)10809     public int checkCarrierPrivilegesForPackage(String pkgName) {
10810         try {
10811             ITelephony telephony = getITelephony();
10812             if (telephony != null)
10813                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
10814         } catch (RemoteException ex) {
10815             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
10816         } catch (NullPointerException ex) {
10817             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
10818         }
10819         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
10820     }
10821 
10822     /**
10823      * @throws UnsupportedOperationException If the device does not have
10824      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10825      * @hide
10826      */
10827     @SystemApi
10828     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10829     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)10830     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
10831         try {
10832             ITelephony telephony = getITelephony();
10833             if (telephony != null)
10834                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
10835         } catch (RemoteException ex) {
10836             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
10837         } catch (NullPointerException ex) {
10838             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
10839         }
10840         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
10841     }
10842 
10843     /**
10844      * @throws UnsupportedOperationException If the device does not have
10845      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10846      * @hide
10847      */
10848     @SystemApi
10849     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPackageNamesForIntent(Intent intent)10850     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
10851         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
10852     }
10853 
10854     /**
10855      * @throws UnsupportedOperationException If the device does not have
10856      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10857      * @hide
10858      */
10859     @SystemApi
10860     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10861     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)10862     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
10863         try {
10864             ITelephony telephony = getITelephony();
10865             if (telephony != null)
10866                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
10867         } catch (RemoteException ex) {
10868             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
10869         } catch (NullPointerException ex) {
10870             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
10871         }
10872         return null;
10873     }
10874 
10875     /**
10876      * Returns the package name that provides the {@link CarrierService} implementation for the
10877      * current subscription, or {@code null} if no package with carrier privileges declares one.
10878      *
10879      * <p>If this object has been created with {@link #createForSubscriptionId}, then the provided
10880      * subscription ID is used. Otherwise, the default subscription ID will be used.
10881      *
10882      * @return The system-selected package that provides the {@link CarrierService} implementation
10883      * for the current subscription, or {@code null} if none is resolved
10884      *
10885      * @throws UnsupportedOperationException If the device does not have
10886      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10887      * @hide
10888      */
10889     @SystemApi
10890     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10891     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierServicePackageName()10892     public @Nullable String getCarrierServicePackageName() {
10893         return getCarrierServicePackageNameForLogicalSlot(getPhoneId());
10894     }
10895 
10896     /**
10897      * Returns the package name that provides the {@link CarrierService} implementation for the
10898      * specified {@code logicalSlotIndex}, or {@code null} if no package with carrier privileges
10899      * declares one.
10900      *
10901      * @param logicalSlotIndex The slot index to fetch the {@link CarrierService} package for
10902      * @return The system-selected package that provides the {@link CarrierService} implementation
10903      * for the slot, or {@code null} if none is resolved
10904      *
10905      * @throws UnsupportedOperationException If the device does not have
10906      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10907      * @hide
10908      */
10909     @SystemApi
10910     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10911     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex)10912     public @Nullable String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex) {
10913         try {
10914             ITelephony telephony = getITelephony();
10915             if (telephony != null) {
10916                 return telephony.getCarrierServicePackageNameForLogicalSlot(logicalSlotIndex);
10917             }
10918         } catch (RemoteException ex) {
10919             Rlog.e(TAG, "getCarrierServicePackageNameForLogicalSlot RemoteException", ex);
10920         } catch (NullPointerException ex) {
10921             Rlog.e(TAG, "getCarrierServicePackageNameForLogicalSlot NPE", ex);
10922         }
10923         return null;
10924     }
10925 
10926     /**
10927      * Get the names of packages with carrier privileges for the current subscription.
10928      *
10929      * @throws UnsupportedOperationException If the device does not have {@link
10930      *     PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}
10931      * @hide
10932      */
10933     @FlaggedApi(android.os.Flags.FLAG_MAINLINE_VCN_PLATFORM_API)
10934     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
10935     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10936     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
10937     @NonNull
getPackagesWithCarrierPrivileges()10938     public Set<String> getPackagesWithCarrierPrivileges() {
10939         final Set<String> result = new HashSet<>();
10940         try {
10941             ITelephony telephony = getITelephony();
10942             if (telephony != null) {
10943                 result.addAll(telephony.getPackagesWithCarrierPrivileges(getPhoneId()));
10944             }
10945         } catch (RemoteException ex) {
10946             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
10947         } catch (NullPointerException ex) {
10948             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
10949         }
10950         return result;
10951     }
10952 
10953     /**
10954      * Get the names of packages with carrier privileges for all the active subscriptions.
10955      *
10956      * @throws UnsupportedOperationException If the device does not have
10957      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
10958      * @hide
10959      */
10960     @SystemApi
10961     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
10962     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
10963     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()10964     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
10965         try {
10966             ITelephony telephony = getITelephony();
10967             if (telephony != null) {
10968                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
10969             }
10970         } catch (RemoteException ex) {
10971             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
10972                     ex);
10973         } catch (NullPointerException ex) {
10974             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
10975         }
10976         return Collections.EMPTY_LIST;
10977     }
10978 
10979     /**
10980      * Call composer status <b>OFF</b> from user setting.
10981      */
10982     public static final int CALL_COMPOSER_STATUS_OFF = 0;
10983 
10984     /**
10985      * Call composer status <b>ON</b> from user setting.
10986      */
10987     public static final int CALL_COMPOSER_STATUS_ON = 1;
10988 
10989     /**
10990      * Call composer status <b>Business Only</b> from user setting.
10991      */
10992     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_BUSINESS_CALL_COMPOSER)
10993     public static final int CALL_COMPOSER_STATUS_BUSINESS_ONLY = 2;
10994 
10995     /** @hide */
10996     @IntDef(prefix = {"CALL_COMPOSER_STATUS_"},
10997             value = {
10998                 CALL_COMPOSER_STATUS_ON,
10999                 CALL_COMPOSER_STATUS_OFF,
11000                 CALL_COMPOSER_STATUS_BUSINESS_ONLY
11001             })
11002     @Retention(RetentionPolicy.SOURCE)
11003     public @interface CallComposerStatus {}
11004 
11005     /**
11006      * Set the user-set status for enriched calling with call composer.
11007      *
11008      * @param status user-set status for enriched calling with call composer.
11009      *
11010      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11011      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11012      *
11013      * @throws IllegalArgumentException if requested state is invalid.
11014      * @throws SecurityException if the caller does not have the permission.
11015      * @throws UnsupportedOperationException If the device does not have
11016      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11017      */
11018     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11019     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallComposerStatus(@allComposerStatus int status)11020     public void setCallComposerStatus(@CallComposerStatus int status) {
11021         if (com.android.server.telecom.flags.Flags.businessCallComposer()) {
11022             if (status > CALL_COMPOSER_STATUS_BUSINESS_ONLY
11023                     || status < CALL_COMPOSER_STATUS_OFF) {
11024                 throw new IllegalArgumentException("requested status is invalid");
11025             }
11026         } else {
11027             if (status > CALL_COMPOSER_STATUS_ON
11028                     || status < CALL_COMPOSER_STATUS_OFF) {
11029                 throw new IllegalArgumentException("requested status is invalid");
11030             }
11031         }
11032         try {
11033             ITelephony telephony = getITelephony();
11034             if (telephony != null) {
11035                 telephony.setCallComposerStatus(getSubId(), status);
11036             }
11037         } catch (RemoteException ex) {
11038             Log.e(TAG, "Error calling ITelephony#setCallComposerStatus", ex);
11039             ex.rethrowFromSystemServer();
11040         }
11041     }
11042 
11043     /**
11044      * Get the user-set status for enriched calling with call composer.
11045      *
11046      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11047      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11048      *
11049      * @throws SecurityException if the caller does not have the permission.
11050      *
11051      * @return the user-set status for enriched calling with call composer, either of
11052      * {@link #CALL_COMPOSER_STATUS_ON} or {@link #CALL_COMPOSER_STATUS_OFF}.
11053      *
11054      * @throws UnsupportedOperationException If the device does not have
11055      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11056      */
11057     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11058     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallComposerStatus()11059     public @CallComposerStatus int getCallComposerStatus() {
11060         try {
11061             ITelephony telephony = getITelephony();
11062             if (telephony != null) {
11063                 return telephony.getCallComposerStatus(getSubId());
11064             }
11065         } catch (RemoteException ex) {
11066             Log.e(TAG, "Error calling ITelephony#getCallComposerStatus", ex);
11067             ex.rethrowFromSystemServer();
11068         }
11069         return CALL_COMPOSER_STATUS_OFF;
11070     }
11071 
11072     /**
11073      * @throws UnsupportedOperationException If the device does not have
11074      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11075      * @hide
11076      */
11077     @SystemApi
11078     @SuppressLint("RequiresPermission")
11079     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
dial(String number)11080     public void dial(String number) {
11081         try {
11082             ITelephony telephony = getITelephony();
11083             if (telephony != null)
11084                 telephony.dial(number);
11085         } catch (RemoteException e) {
11086             Log.e(TAG, "Error calling ITelephony#dial", e);
11087         }
11088     }
11089 
11090     /**
11091      * @throws UnsupportedOperationException If the device does not have
11092      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11093      *
11094      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
11095      * Bundle extras)} instead.
11096      * @hide
11097      */
11098     @Deprecated
11099     @SystemApi
11100     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
11101     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
call(String callingPackage, String number)11102     public void call(String callingPackage, String number) {
11103         try {
11104             ITelephony telephony = getITelephony();
11105             if (telephony != null)
11106                 telephony.call(callingPackage, number);
11107         } catch (RemoteException e) {
11108             Log.e(TAG, "Error calling ITelephony#call", e);
11109         }
11110     }
11111 
11112     /**
11113      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
11114      * @hide
11115      * @removed
11116      */
11117     @Deprecated
11118     @SystemApi
11119     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()11120     public boolean endCall() {
11121         return false;
11122     }
11123 
11124     /**
11125      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
11126      * @hide
11127      * @removed
11128      */
11129     @Deprecated
11130     @SystemApi
11131     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()11132     public void answerRingingCall() {
11133         // No-op
11134     }
11135 
11136     /**
11137      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
11138      * @hide
11139      */
11140     @Deprecated
11141     @SystemApi
11142     @SuppressLint("RequiresPermission")
silenceRinger()11143     public void silenceRinger() {
11144         // No-op
11145     }
11146 
11147     /**
11148    * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
11149      * @hide
11150      */
11151     @Deprecated
11152     @SystemApi
11153     @RequiresPermission(anyOf = {
11154             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11155             android.Manifest.permission.READ_PHONE_STATE
11156     })
isOffhook()11157     public boolean isOffhook() {
11158         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
11159         return tm.isInCall();
11160     }
11161 
11162     /**
11163      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
11164      * @hide
11165      */
11166     @Deprecated
11167     @SystemApi
11168     @RequiresPermission(anyOf = {
11169             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11170             android.Manifest.permission.READ_PHONE_STATE
11171     })
isRinging()11172     public boolean isRinging() {
11173         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
11174         return tm.isRinging();
11175     }
11176 
11177     /**
11178      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
11179      * @hide
11180      */
11181     @Deprecated
11182     @SystemApi
11183     @RequiresPermission(anyOf = {
11184             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11185             android.Manifest.permission.READ_PHONE_STATE
11186     })
isIdle()11187     public boolean isIdle() {
11188         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
11189         return !tm.isInCall();
11190     }
11191 
11192     /**
11193      * @throws UnsupportedOperationException If the device does not have
11194      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11195      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
11196      * @hide
11197      */
11198     @Deprecated
11199     @SystemApi
11200     @RequiresPermission(anyOf = {
11201             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11202             android.Manifest.permission.READ_PHONE_STATE
11203     })
11204     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isRadioOn()11205     public boolean isRadioOn() {
11206         try {
11207             ITelephony telephony = getITelephony();
11208             if (telephony != null)
11209                 return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
11210         } catch (RemoteException e) {
11211             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
11212         }
11213         return false;
11214     }
11215 
11216     /**
11217      * @throws UnsupportedOperationException If the device does not have
11218      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11219      * @hide
11220      */
11221     @SystemApi
11222     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11223     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyPin(String pin)11224     public boolean supplyPin(String pin) {
11225         try {
11226             ITelephony telephony = getITelephony();
11227             if (telephony != null)
11228                 return telephony.supplyPinForSubscriber(getSubId(), pin);
11229         } catch (RemoteException e) {
11230             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
11231         }
11232         return false;
11233     }
11234 
11235     /**
11236      * @throws UnsupportedOperationException If the device does not have
11237      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11238      * @hide
11239      */
11240     @SystemApi
11241     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11242     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyPuk(String puk, String pin)11243     public boolean supplyPuk(String puk, String pin) {
11244         try {
11245             ITelephony telephony = getITelephony();
11246             if (telephony != null)
11247                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
11248         } catch (RemoteException e) {
11249             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
11250         }
11251         return false;
11252     }
11253 
11254     /**
11255      * @throws UnsupportedOperationException If the device does not have
11256      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11257      *
11258      * @deprecated use {@link #supplyIccLockPin(String)} instead.
11259      * @hide
11260      */
11261     @SystemApi
11262     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11263     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
11264     @Deprecated
supplyPinReportResult(String pin)11265     public int[] supplyPinReportResult(String pin) {
11266         try {
11267             ITelephony telephony = getITelephony();
11268             if (telephony != null)
11269                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
11270         } catch (RemoteException e) {
11271             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
11272         }
11273         return new int[0];
11274     }
11275 
11276     /**
11277      * @throws UnsupportedOperationException If the device does not have
11278      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11279      *
11280      * @deprecated use {@link #supplyIccLockPuk(String, String)} instead.
11281      * @hide
11282      */
11283     @SystemApi
11284     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11285     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
11286     @Deprecated
supplyPukReportResult(String puk, String pin)11287     public int[] supplyPukReportResult(String puk, String pin) {
11288         try {
11289             ITelephony telephony = getITelephony();
11290             if (telephony != null)
11291                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
11292         } catch (RemoteException e) {
11293             Log.e(TAG, "Error calling ITelephony#supplyPukReportResultForSubscriber", e);
11294         }
11295         return new int[0];
11296     }
11297 
11298     /**
11299      * Supplies a PIN to unlock the ICC and returns the corresponding {@link PinResult}.
11300      * Used when the user enters their ICC unlock PIN to attempt an unlock.
11301      *
11302      * @param pin The user entered PIN.
11303      * @return The result of the PIN.
11304      * @throws SecurityException if the caller doesn't have the permission.
11305      * @throws IllegalStateException if the Telephony process is not currently available.
11306      *
11307      * <p>Requires Permission:
11308      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11309      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11310      *
11311      * @throws UnsupportedOperationException If the device does not have
11312      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11313      * @hide
11314      */
11315     @SystemApi
11316     @NonNull
11317     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11318     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyIccLockPin(@onNull String pin)11319     public PinResult supplyIccLockPin(@NonNull String pin) {
11320         try {
11321             ITelephony telephony = getITelephony();
11322             if (telephony != null) {
11323                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
11324                 return new PinResult(result[0], result[1]);
11325             } else {
11326                 throw new IllegalStateException("telephony service is null.");
11327             }
11328         } catch (RemoteException e) {
11329             Log.e(TAG, "Error calling ITelephony#supplyIccLockPin", e);
11330             e.rethrowFromSystemServer();
11331         }
11332         return PinResult.getDefaultFailedResult();
11333     }
11334 
11335     /**
11336      * Supplies a PUK and PIN to unlock the ICC and returns the corresponding {@link PinResult}.
11337      * Used when the user enters their ICC unlock PUK and PIN to attempt an unlock.
11338      *
11339      * @param puk The product unlocking key.
11340      * @param pin The user entered PIN.
11341      * @return The result of the PUK and PIN.
11342      * @throws SecurityException if the caller doesn't have the permission.
11343      * @throws IllegalStateException if the Telephony process is not currently available.
11344      *
11345      * <p>Requires Permission:
11346      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11347      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11348      *
11349      * @throws UnsupportedOperationException If the device does not have
11350      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
11351      * @hide
11352      */
11353     @SystemApi
11354     @NonNull
11355     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11356     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
supplyIccLockPuk(@onNull String puk, @NonNull String pin)11357     public PinResult supplyIccLockPuk(@NonNull String puk, @NonNull String pin) {
11358         try {
11359             ITelephony telephony = getITelephony();
11360             if (telephony != null) {
11361                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
11362                 return new PinResult(result[0], result[1]);
11363             } else {
11364                 throw new IllegalStateException("telephony service is null.");
11365             }
11366         } catch (RemoteException e) {
11367             Log.e(TAG, "Error calling ITelephony#supplyIccLockPuk", e);
11368             e.rethrowFromSystemServer();
11369         }
11370         return PinResult.getDefaultFailedResult();
11371     }
11372 
11373     /**
11374      * Used to notify callers of
11375      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
11376      * network either successfully executes a USSD request, or if there was a failure while
11377      * executing the request.
11378      * <p>
11379      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
11380      * USSD request has succeeded.
11381      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
11382      * USSD request has failed.
11383      */
11384     public static abstract class UssdResponseCallback {
11385        /**
11386         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
11387         * response received from the network.  The calling app can choose to either display the
11388         * response to the user or perform some operation based on the response.
11389         * <p>
11390         * USSD responses are unstructured text and their content is determined by the mobile network
11391         * operator.
11392         *
11393         * @param telephonyManager the TelephonyManager the callback is registered to.
11394         * @param request the USSD request sent to the mobile network.
11395         * @param response the response to the USSD request provided by the mobile network.
11396         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)11397        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
11398                                          String request, CharSequence response) {};
11399 
11400        /**
11401         * Called when a USSD request has failed to complete.
11402         *
11403         * @param telephonyManager the TelephonyManager the callback is registered to.
11404         * @param request the USSD request sent to the mobile network.
11405         * @param failureCode failure code indicating why the request failed.  Will be either
11406         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
11407         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
11408         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)11409        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
11410                                                String request, int failureCode) {};
11411     }
11412 
11413     /**
11414      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
11415      * informs the caller of the response via the supplied {@code callback}.
11416      * <p>Carriers define USSD codes which can be sent by the user to request information such as
11417      * the user's current data balance or minutes balance.
11418      * <p>Requires permission:
11419      * {@link android.Manifest.permission#CALL_PHONE}
11420      * @param ussdRequest the USSD command to be executed.
11421      * @param callback called by the framework to inform the caller of the result of executing the
11422      *                 USSD request (see {@link UssdResponseCallback}).
11423      * @param handler the {@link Handler} to run the request on.
11424      *
11425      * @throws UnsupportedOperationException If the device does not have
11426      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11427      */
11428     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
11429     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)11430     public void sendUssdRequest(String ussdRequest,
11431                                 final UssdResponseCallback callback, Handler handler) {
11432         checkNotNull(callback, "UssdResponseCallback cannot be null.");
11433         final TelephonyManager telephonyManager = this;
11434 
11435         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
11436             @Override
11437             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
11438                 Rlog.d(TAG, "USSD:" + resultCode);
11439                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
11440                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE, android.telephony.UssdResponse.class);
11441 
11442                 if (resultCode == USSD_RETURN_SUCCESS) {
11443                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
11444                             response.getReturnMessage());
11445                 } else {
11446                     callback.onReceiveUssdResponseFailed(telephonyManager,
11447                             response.getUssdRequest(), resultCode);
11448                 }
11449             }
11450         };
11451 
11452         try {
11453             ITelephony telephony = getITelephony();
11454             if (telephony != null) {
11455                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
11456             }
11457         } catch (RemoteException e) {
11458             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
11459             UssdResponse response = new UssdResponse(ussdRequest, "");
11460             Bundle returnData = new Bundle();
11461             returnData.putParcelable(USSD_RESPONSE, response);
11462             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
11463         }
11464     }
11465 
11466     /**
11467      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
11468      * voice and data simultaneously. This can change based on location or network condition.
11469      *
11470      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
11471      *
11472      * @throws UnsupportedOperationException If the device does not have
11473      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11474      */
11475     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isConcurrentVoiceAndDataSupported()11476     public boolean isConcurrentVoiceAndDataSupported() {
11477         try {
11478             ITelephony telephony = getITelephony();
11479             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
11480                     getSubId()));
11481         } catch (RemoteException e) {
11482             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
11483         }
11484         return false;
11485     }
11486 
11487     /**
11488      * @throws UnsupportedOperationException If the device does not have
11489      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11490      * @hide */
11491     @SystemApi
11492     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11493     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
handlePinMmi(String dialString)11494     public boolean handlePinMmi(String dialString) {
11495         try {
11496             ITelephony telephony = getITelephony();
11497             if (telephony != null)
11498                 return telephony.handlePinMmi(dialString);
11499         } catch (RemoteException e) {
11500             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
11501         }
11502         return false;
11503     }
11504 
11505     /**
11506      * @throws UnsupportedOperationException If the device does not have
11507      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
11508      * @hide
11509      */
11510     @SystemApi
11511     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11512     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
handlePinMmiForSubscriber(int subId, String dialString)11513     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
11514         try {
11515             ITelephony telephony = getITelephony();
11516             if (telephony != null)
11517                 return telephony.handlePinMmiForSubscriber(subId, dialString);
11518         } catch (RemoteException e) {
11519             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
11520         }
11521         return false;
11522     }
11523 
11524     /**
11525      * @throws UnsupportedOperationException If the device does not have
11526      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11527      * @hide
11528      */
11529     @SystemApi
11530     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11531     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
toggleRadioOnOff()11532     public void toggleRadioOnOff() {
11533         try {
11534             ITelephony telephony = getITelephony();
11535             if (telephony != null)
11536                 telephony.toggleRadioOnOff();
11537         } catch (RemoteException e) {
11538             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
11539         }
11540     }
11541 
11542     /**
11543      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
11544      * {@link clearRadioPowerOffForReason}.
11545      *
11546      * @throws UnsupportedOperationException If the device does not have
11547      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11548      * @hide
11549      */
11550     @Deprecated
11551     @SystemApi
11552     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11553     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadio(boolean turnOn)11554     public boolean setRadio(boolean turnOn) {
11555         boolean result = true;
11556         try {
11557             if (turnOn) {
11558                 clearRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11559             } else {
11560                 requestRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11561             }
11562         } catch (Exception e) {
11563             String calledFunction =
11564                     turnOn ? "clearRadioPowerOffForReason" : "requestRadioPowerOffForReason";
11565             Log.e(TAG, "Error calling " + calledFunction, e);
11566             result = false;
11567         }
11568         return result;
11569     }
11570 
11571     /**
11572      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
11573      * {@link clearRadioPowerOffForReason}.
11574      *
11575      * @throws UnsupportedOperationException If the device does not have
11576      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11577      * @hide
11578      */
11579     @Deprecated
11580     @SystemApi
11581     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11582     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadioPower(boolean turnOn)11583     public boolean setRadioPower(boolean turnOn) {
11584         boolean result = true;
11585         try {
11586             if (turnOn) {
11587                 clearRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11588             } else {
11589                 requestRadioPowerOffForReason(RADIO_POWER_REASON_USER);
11590             }
11591         } catch (Exception e) {
11592             String calledFunction =
11593                     turnOn ? "clearRadioPowerOffForReason" : "requestRadioPowerOffForReason";
11594             Log.e(TAG, "Error calling " + calledFunction, e);
11595             result = false;
11596         }
11597         return result;
11598     }
11599 
11600     /**
11601      * Vote on powering off the radio for a reason. The radio will be turned on only when there is
11602      * no reason to power it off. When any of the voters want to power it off, it will be turned
11603      * off. In case of emergency, the radio will be turned on even if there are some reasons for
11604      * powering it off, and these radio off votes will be cleared.
11605      * <p>
11606      * Each API call is for one reason. However, an app can call the API multiple times for multiple
11607      * reasons. Multiple apps can vote for the same reason but the vote of one app does not affect
11608      * the vote of another app.
11609      * <p>
11610      * Each app is responsible for its vote. A powering-off vote for a reason of an app will be
11611      * maintained until it is cleared by calling {@link #clearRadioPowerOffForReason(int)} for that
11612      * reason by the app, or an emergency call is made, or the device is rebooted. When an app
11613      * comes backup from a crash, it needs to make sure if its vote is as expected. An app can use
11614      * the API {@link #getRadioPowerOffReasons()} to check its votes. Votes won't be removed when
11615      * an app crashes.
11616      * <p>
11617      * User setting for power state is persistent across device reboots. This applies to all users,
11618      * callers must be careful to update the off reasons when the current user changes.
11619      *
11620      * @param reason The reason for powering off radio.
11621      * @throws SecurityException if the caller does not have MODIFY_PHONE_STATE permission.
11622      * @throws IllegalStateException if the Telephony service is not currently available.
11623      *
11624      * @throws UnsupportedOperationException If the device does not have
11625      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11626      * @hide
11627      */
11628     @SystemApi
11629     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11630     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
requestRadioPowerOffForReason(@adioPowerReason int reason)11631     public void requestRadioPowerOffForReason(@RadioPowerReason int reason) {
11632         try {
11633             ITelephony telephony = getITelephony();
11634             if (telephony != null) {
11635                 if (!telephony.requestRadioPowerOffForReason(getSubId(), reason)) {
11636                     throw new IllegalStateException("Telephony service is not available.");
11637                 }
11638             } else {
11639                 throw new IllegalStateException("Telephony service is null.");
11640             }
11641         } catch (RemoteException e) {
11642             Log.e(TAG, "Error calling ITelephony#requestRadioPowerOffForReason", e);
11643             e.rethrowAsRuntimeException();
11644         }
11645     }
11646 
11647     /**
11648      * Remove the vote on powering off the radio for a reason, as requested by
11649      * {@link requestRadioPowerOffForReason}.
11650      *
11651      * @param reason The reason for powering off radio.
11652      * @throws SecurityException if the caller does not have MODIFY_PHONE_STATE permission.
11653      * @throws IllegalStateException if the Telephony service is not currently available.
11654      *
11655      * @throws UnsupportedOperationException If the device does not have
11656      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11657      * @hide
11658      */
11659     @SystemApi
11660     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11661     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
clearRadioPowerOffForReason(@adioPowerReason int reason)11662     public void clearRadioPowerOffForReason(@RadioPowerReason int reason) {
11663         try {
11664             ITelephony telephony = getITelephony();
11665             if (telephony != null) {
11666                 if (!telephony.clearRadioPowerOffForReason(getSubId(), reason)) {
11667                     throw new IllegalStateException("Telephony service is not available.");
11668                 }
11669             } else {
11670                 throw new IllegalStateException("Telephony service is null.");
11671             }
11672         } catch (RemoteException e) {
11673             Log.e(TAG, "Error calling ITelephony#clearRadioPowerOffForReason", e);
11674             e.rethrowAsRuntimeException();
11675         }
11676     }
11677 
11678     /**
11679      * Get reasons for powering off radio of the calling app, as requested by
11680      * {@link #requestRadioPowerOffForReason(int)}.
11681      *
11682      * @return Set of reasons for powering off radio of the calling app.
11683      * @throws SecurityException if the caller does not have READ_PRIVILEGED_PHONE_STATE permission.
11684      * @throws IllegalStateException if the Telephony service is not currently available.
11685      *
11686      * @throws UnsupportedOperationException If the device does not have
11687      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11688      * @hide
11689      */
11690     @SystemApi
11691     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11692     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
11693     @NonNull
getRadioPowerOffReasons()11694     public Set<Integer> getRadioPowerOffReasons() {
11695         Set<Integer> result = new HashSet<>();
11696         try {
11697             ITelephony telephony = getITelephony();
11698             if (telephony != null) {
11699                 result.addAll(telephony.getRadioPowerOffReasons(getSubId(),
11700                         mContext.getOpPackageName(), mContext.getAttributionTag()));
11701             } else {
11702                 throw new IllegalStateException("Telephony service is null.");
11703             }
11704         } catch (RemoteException e) {
11705             Log.e(TAG, "Error calling ITelephony#getRadioPowerOffReasons", e);
11706             e.rethrowAsRuntimeException();
11707         }
11708         return result;
11709     }
11710 
11711     /**
11712      * Shut down all the live radios over all the slot indexes.
11713      *
11714      * <p>To know when the radio has completed powering off, use
11715      * {@link TelephonyCallback.ServiceStateListener}.
11716      *
11717      * @throws UnsupportedOperationException If the device does not have
11718      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11719      * @hide
11720      */
11721     @SystemApi
11722     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11723     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
shutdownAllRadios()11724     public void shutdownAllRadios() {
11725         try {
11726             ITelephony telephony = getITelephony();
11727             if (telephony != null) {
11728                 telephony.shutdownMobileRadios();
11729             }
11730         } catch (RemoteException e) {
11731             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
11732             e.rethrowAsRuntimeException();
11733         }
11734     }
11735 
11736     /**
11737      * Check if any radio is on over all the slot indexes.
11738      *
11739      * @return {@code true} if any radio is on over any slot index.
11740      *
11741      * @throws UnsupportedOperationException If the device does not have
11742      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11743      * @hide
11744      */
11745     @SystemApi
11746     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11747     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isAnyRadioPoweredOn()11748     public boolean isAnyRadioPoweredOn() {
11749         try {
11750             ITelephony telephony = getITelephony();
11751             if (telephony != null) {
11752                 return telephony.needMobileRadioShutdown();
11753             }
11754         } catch (RemoteException e) {
11755             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
11756             e.rethrowAsRuntimeException();
11757         }
11758         return false;
11759     }
11760 
11761     /**
11762      * Radio explicitly powered off (e.g, airplane mode).
11763      * @hide
11764      */
11765     @SystemApi
11766     public static final int RADIO_POWER_OFF = 0;
11767 
11768     /**
11769      * Radio power is on.
11770      * @hide
11771      */
11772     @SystemApi
11773     public static final int RADIO_POWER_ON = 1;
11774 
11775     /**
11776      * Radio power unavailable (eg, modem resetting or not booted).
11777      * @hide
11778      */
11779     @SystemApi
11780     public static final int RADIO_POWER_UNAVAILABLE = 2;
11781 
11782     /**
11783      * @return current modem radio state.
11784      *
11785      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
11786      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
11787      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11788      *
11789      * @throws UnsupportedOperationException If the device does not have
11790      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11791      * @hide
11792      */
11793     @SystemApi
11794     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
11795             android.Manifest.permission.READ_PHONE_STATE})
11796     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getRadioPowerState()11797     public @RadioPowerState int getRadioPowerState() {
11798         try {
11799             ITelephony telephony = getITelephony();
11800             if (telephony != null) {
11801                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
11802                         mContext.getAttributionTag());
11803             }
11804         } catch (RemoteException ex) {
11805             // This could happen if binder process crashes.
11806         }
11807         return RADIO_POWER_UNAVAILABLE;
11808     }
11809 
11810     /**
11811      * This method should not be used due to privacy and stability concerns.
11812      *
11813      * @hide
11814      */
11815     @SystemApi
updateServiceLocation()11816     public void updateServiceLocation() {
11817         Log.e(TAG, "Do not call TelephonyManager#updateServiceLocation()");
11818     }
11819 
11820     /**
11821      * @throws UnsupportedOperationException If the device does not have
11822      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11823      * @hide
11824      */
11825     @SystemApi
11826     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11827     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
enableDataConnectivity()11828     public boolean enableDataConnectivity() {
11829         try {
11830             ITelephony telephony = getITelephony();
11831             if (telephony != null)
11832                 return telephony.enableDataConnectivity(getOpPackageName());
11833         } catch (RemoteException e) {
11834             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
11835         }
11836         return false;
11837     }
11838 
11839     /**
11840      * @throws UnsupportedOperationException If the device does not have
11841      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11842      * @hide
11843      */
11844     @SystemApi
11845     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11846     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
disableDataConnectivity()11847     public boolean disableDataConnectivity() {
11848         try {
11849             ITelephony telephony = getITelephony();
11850             if (telephony != null)
11851                 return telephony.disableDataConnectivity(getOpPackageName());
11852         } catch (RemoteException e) {
11853             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
11854         }
11855         return false;
11856     }
11857 
11858     /**
11859      * @throws UnsupportedOperationException If the device does not have
11860      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11861      * @hide
11862      */
11863     @SystemApi
11864     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataConnectivityPossible()11865     public boolean isDataConnectivityPossible() {
11866         try {
11867             ITelephony telephony = getITelephony();
11868             if (telephony != null)
11869                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
11870                         .getActiveDataSubscriptionId()));
11871         } catch (RemoteException e) {
11872             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
11873         }
11874         return false;
11875     }
11876 
11877     /**
11878      * @throws UnsupportedOperationException If the device does not have
11879      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
11880      * @hide
11881      */
11882     @SystemApi
11883     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
needsOtaServiceProvisioning()11884     public boolean needsOtaServiceProvisioning() {
11885         try {
11886             ITelephony telephony = getITelephony();
11887             if (telephony != null)
11888                 return telephony.needsOtaServiceProvisioning();
11889         } catch (RemoteException e) {
11890             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
11891         }
11892         return false;
11893     }
11894 
11895     /**
11896      * Get the mobile provisioning url that is used to launch a browser to allow users to manage
11897      * their mobile plan.
11898      *
11899      * <p>Requires Permission:
11900      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}.
11901      *
11902      * TODO: The legacy design only supports single sim design. Ideally, this should support
11903      * multi-sim design in current world.
11904      *
11905      * {@hide}
11906      */
11907     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMobileProvisioningUrl()11908     public @Nullable String getMobileProvisioningUrl() {
11909         try {
11910             final ITelephony service = getITelephony();
11911             if (service != null) {
11912                 return service.getMobileProvisioningUrl();
11913             } else {
11914                 throw new IllegalStateException("telephony service is null.");
11915             }
11916         } catch (RemoteException ex) {
11917             Rlog.e(TAG, "Telephony#getMobileProvisioningUrl RemoteException" + ex);
11918         }
11919         return null;
11920     }
11921 
11922     /**
11923      * Turns mobile data on or off.
11924      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
11925      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11926      *
11927      * <p>Requires Permission:
11928      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
11929      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
11930      *
11931      * @param enable Whether to enable mobile data.
11932      * @throws UnsupportedOperationException If the device does not have
11933      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11934      * @deprecated use setDataEnabledForReason with reason DATA_ENABLED_REASON_USER instead.
11935      *
11936      */
11937     @Deprecated
11938     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
11939     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11940     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabled(boolean enable)11941     public void setDataEnabled(boolean enable) {
11942         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
11943     }
11944 
11945     /**
11946      * @throws UnsupportedOperationException If the device does not have
11947      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11948      * @hide
11949      * @deprecated use {@link #setDataEnabledForReason(int, boolean)} instead.
11950     */
11951     @SystemApi
11952     @Deprecated
11953     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
11954     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabled(int subId, boolean enable)11955     public void setDataEnabled(int subId, boolean enable) {
11956         try {
11957             setDataEnabledForReason(subId, DATA_ENABLED_REASON_USER, enable);
11958         } catch (RuntimeException e) {
11959             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
11960         }
11961     }
11962 
11963     /**
11964      * @deprecated use {@link #isDataEnabled()} instead.
11965      *
11966      * @throws UnsupportedOperationException If the device does not have
11967      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11968      * @hide
11969      */
11970     @SystemApi
11971     @Deprecated
11972     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataEnabled()11973     public boolean getDataEnabled() {
11974         return isDataEnabled();
11975     }
11976 
11977     /**
11978      * Returns whether mobile data is enabled or not per user setting. There are other factors
11979      * that could disable mobile data, but they are not considered here.
11980      *
11981      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
11982      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11983      *
11984      * <p>Requires one of the following permissions:
11985      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
11986      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or
11987      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
11988      * READ_BASIC_PHONE_STATE} or that the calling app has carrier
11989      * privileges (see {@link #hasCarrierPrivileges}).
11990      *
11991      * <p>Note that this does not take into account any data restrictions that may be present on the
11992      * calling app. Such restrictions may be inspected with
11993      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
11994      *
11995      * @return true if mobile data is enabled.
11996      *
11997      * @throws UnsupportedOperationException If the device does not have
11998      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
11999      */
12000     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
12001             android.Manifest.permission.MODIFY_PHONE_STATE,
12002             android.Manifest.permission.READ_PHONE_STATE,
12003             android.Manifest.permission.READ_BASIC_PHONE_STATE})
12004     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabled()12005     public boolean isDataEnabled() {
12006         try {
12007             return isDataEnabledForReason(DATA_ENABLED_REASON_USER);
12008         } catch (IllegalStateException ise) {
12009             // TODO(b/176163590): Remove this catch once TelephonyManager is booting safely.
12010             Log.e(TAG, "Error calling #isDataEnabled, returning default (false).", ise);
12011             return false;
12012         }
12013     }
12014 
12015     /**
12016      * Returns whether mobile data roaming is enabled on the subscription.
12017      *
12018      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12019      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12020      *
12021      * <p>Requires one of the following permissions:
12022      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
12023      * {@link android.Manifest.permission#READ_PHONE_STATE} or
12024      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE
12025      * READ_BASIC_PHONE_STATE} or that the calling app
12026      * has carrier privileges (see {@link #hasCarrierPrivileges}).
12027      *
12028      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
12029      *
12030      * @throws UnsupportedOperationException If the device does not have
12031      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
12032      * {@code false}.
12033      */
12034     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
12035             android.Manifest.permission.READ_PHONE_STATE,
12036             android.Manifest.permission.READ_BASIC_PHONE_STATE})
12037     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataRoamingEnabled()12038     public boolean isDataRoamingEnabled() {
12039         boolean isDataRoamingEnabled = false;
12040         try {
12041             ITelephony telephony = getITelephony();
12042             if (telephony != null) {
12043                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
12044                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
12045             }
12046         } catch (RemoteException e) {
12047             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
12048         }
12049         return isDataRoamingEnabled;
12050     }
12051 
12052     /**
12053      * Gets the roaming mode for CDMA phone.
12054      *
12055      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12056      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12057      *
12058      * @return the CDMA roaming mode.
12059      * @throws SecurityException if the caller does not have the permission.
12060      * @throws IllegalStateException if the Telephony process is not currently available.
12061      *
12062      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
12063      * @see #CDMA_ROAMING_MODE_HOME
12064      * @see #CDMA_ROAMING_MODE_AFFILIATED
12065      * @see #CDMA_ROAMING_MODE_ANY
12066      *
12067      * <p>Requires permission:
12068      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12069      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12070      *
12071      * @throws UnsupportedOperationException If the device does not have
12072      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
12073      * @deprecated Legacy CDMA is unsupported.
12074      * @hide
12075      */
12076     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12077     @Deprecated
12078     @SystemApi
12079     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12080     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaRoamingMode()12081     public @CdmaRoamingMode int getCdmaRoamingMode() {
12082         if (Flags.cleanupCdma()) return CDMA_ROAMING_MODE_RADIO_DEFAULT;
12083         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
12084         try {
12085             ITelephony telephony = getITelephony();
12086             if (telephony != null) {
12087                 mode = telephony.getCdmaRoamingMode(getSubId());
12088             } else {
12089                 throw new IllegalStateException("telephony service is null.");
12090             }
12091         } catch (RemoteException ex) {
12092             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
12093             ex.rethrowFromSystemServer();
12094         }
12095         return mode;
12096     }
12097 
12098     /**
12099      * Sets the roaming mode for CDMA phone to the given mode {@code mode}. If the phone is not
12100      * CDMA capable, this method throws an IllegalStateException.
12101      *
12102      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12103      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12104      *
12105      * @param mode CDMA roaming mode.
12106      * @throws SecurityException if the caller does not have the permission.
12107      * @throws IllegalStateException if the Telephony process or radio is not currently available,
12108      *         the device is not CDMA capable, or the request fails.
12109      *
12110      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
12111      * @see #CDMA_ROAMING_MODE_HOME
12112      * @see #CDMA_ROAMING_MODE_AFFILIATED
12113      * @see #CDMA_ROAMING_MODE_ANY
12114      *
12115      * <p>Requires Permission:
12116      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
12117      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
12118      *
12119      * @throws UnsupportedOperationException If the device does not have
12120      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
12121      * @deprecated Legacy CDMA is unsupported.
12122      * @hide
12123      */
12124     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12125     @Deprecated
12126     @SystemApi
12127     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12128     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
setCdmaRoamingMode(@dmaRoamingMode int mode)12129     public void setCdmaRoamingMode(@CdmaRoamingMode int mode) {
12130         if (Flags.cleanupCdma()) return;
12131         if (getPhoneType() != PHONE_TYPE_CDMA) {
12132             throw new IllegalStateException("Phone does not support CDMA.");
12133         }
12134         try {
12135             ITelephony telephony = getITelephony();
12136             if (telephony != null) {
12137                 boolean result = telephony.setCdmaRoamingMode(getSubId(), mode);
12138                 if (!result) throw new IllegalStateException("radio is unavailable.");
12139             } else {
12140                 throw new IllegalStateException("telephony service is null.");
12141             }
12142         } catch (RemoteException ex) {
12143             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
12144             ex.rethrowFromSystemServer();
12145         }
12146     }
12147 
12148     /** @hide
12149      * @deprecated Legacy CDMA is unsupported.
12150      */
12151     @Deprecated
12152     @IntDef(prefix = { "CDMA_SUBSCRIPTION_" }, value = {
12153             CDMA_SUBSCRIPTION_UNKNOWN,
12154             CDMA_SUBSCRIPTION_RUIM_SIM,
12155             CDMA_SUBSCRIPTION_NV
12156     })
12157     @Retention(RetentionPolicy.SOURCE)
12158     public @interface CdmaSubscription{}
12159 
12160     /**
12161      * Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
12162      * @deprecated Legacy CDMA is unsupported.
12163      * @hide
12164      */
12165     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12166     @Deprecated
12167     @SystemApi
12168     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
12169 
12170     /**
12171      * Used for CDMA subscription mode: RUIM/SIM (default)
12172      * @deprecated Legacy CDMA is unsupported.
12173      * @hide
12174      */
12175     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12176     @Deprecated
12177     @SystemApi
12178     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
12179 
12180     /**
12181      * Used for CDMA subscription mode: NV -> non-volatile memory
12182      * @deprecated Legacy CDMA is unsupported.
12183      * @hide
12184      */
12185     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12186     @Deprecated
12187     @SystemApi
12188     public static final int CDMA_SUBSCRIPTION_NV       = 1;
12189 
12190     /**
12191      * Gets the subscription mode for CDMA phone.
12192      *
12193      * @return the CDMA subscription mode.
12194      * @throws SecurityException if the caller does not have the permission.
12195      * @throws IllegalStateException if the Telephony process or radio is not currently available.
12196      *
12197      * @see #CDMA_SUBSCRIPTION_UNKNOWN
12198      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
12199      * @see #CDMA_SUBSCRIPTION_NV
12200      *
12201      * <p>Requires Permission:
12202      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12203      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12204      *
12205      * @throws UnsupportedOperationException If the device does not have
12206      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
12207      * @deprecated Legacy CDMA is unsupported.
12208      * @hide
12209      */
12210     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12211     @Deprecated
12212     @SystemApi
12213     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12214     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaSubscriptionMode()12215     public @CdmaSubscription int getCdmaSubscriptionMode() {
12216         if (Flags.cleanupCdma()) return CDMA_SUBSCRIPTION_UNKNOWN;
12217         int mode = CDMA_SUBSCRIPTION_RUIM_SIM;
12218         try {
12219             ITelephony telephony = getITelephony();
12220             if (telephony != null) {
12221                 mode = telephony.getCdmaSubscriptionMode(getSubId());
12222             } else {
12223                 throw new IllegalStateException("telephony service is null.");
12224             }
12225         } catch (RemoteException ex) {
12226             Log.e(TAG, "Error calling ITelephony#getCdmaSubscriptionMode", ex);
12227             ex.rethrowFromSystemServer();
12228         }
12229         return mode;
12230     }
12231 
12232     /**
12233      * Sets the subscription mode for CDMA phone to the given mode {@code mode}. If the phone is not
12234      * CDMA capable, this method throws an IllegalStateException.
12235      *
12236      * @param mode CDMA subscription mode.
12237      * @throws SecurityException if the caller does not have the permission.
12238      * @throws IllegalStateException if the Telephony process or radio is not currently available,
12239      *         the device is not CDMA capable, or the request fails.
12240      *
12241      * @see #CDMA_SUBSCRIPTION_UNKNOWN
12242      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
12243      * @see #CDMA_SUBSCRIPTION_NV
12244      *
12245      * <p>Requires Permission:
12246      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
12247      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
12248      *
12249      * @throws UnsupportedOperationException If the device does not have
12250      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
12251      * @deprecated Legacy CDMA is unsupported.
12252      * @hide
12253      */
12254     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
12255     @Deprecated
12256     @SystemApi
12257     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12258     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
setCdmaSubscriptionMode(@dmaSubscription int mode)12259     public void setCdmaSubscriptionMode(@CdmaSubscription int mode) {
12260         if (Flags.cleanupCdma()) return;
12261         if (getPhoneType() != PHONE_TYPE_CDMA) {
12262             throw new IllegalStateException("Phone does not support CDMA.");
12263         }
12264         try {
12265             ITelephony telephony = getITelephony();
12266             if (telephony != null) {
12267                 boolean result = telephony.setCdmaSubscriptionMode(getSubId(), mode);
12268                 if (!result) throw new IllegalStateException("radio is unavailable.");
12269             } else {
12270                 throw new IllegalStateException("telephony service is null.");
12271             }
12272         } catch (RemoteException ex) {
12273             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
12274             ex.rethrowFromSystemServer();
12275         }
12276     }
12277 
12278     /**
12279      * Enables/Disables the data roaming on the subscription.
12280      *
12281      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12282      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12283      *
12284      * <p> Requires permission:
12285      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
12286      * privileges (see {@link #hasCarrierPrivileges}).
12287      *
12288      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
12289      *
12290      * @throws UnsupportedOperationException If the device does not have
12291      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
12292      * @hide
12293      */
12294     @SystemApi
12295     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12296     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataRoamingEnabled(boolean isEnabled)12297     public void setDataRoamingEnabled(boolean isEnabled) {
12298         try {
12299             ITelephony telephony = getITelephony();
12300             if (telephony != null) {
12301                 telephony.setDataRoamingEnabled(
12302                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
12303             }
12304         } catch (RemoteException e) {
12305             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
12306         }
12307     }
12308 
12309     /**
12310      * @throws UnsupportedOperationException If the device does not have
12311      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
12312      *
12313      * @deprecated use {@link #isDataEnabled()} instead.
12314      * @hide
12315      */
12316     @Deprecated
12317     @SystemApi
12318     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getDataEnabled(int subId)12319     public boolean getDataEnabled(int subId) {
12320         try {
12321             return isDataEnabledForReason(subId, DATA_ENABLED_REASON_USER);
12322         } catch (RuntimeException e) {
12323             Log.e(TAG, "Error calling isDataEnabledForReason e:" + e);
12324         }
12325         return false;
12326     }
12327 
12328     /**
12329      * @throws UnsupportedOperationException If the device does not have
12330      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
12331      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
12332      * instead.
12333      * @hide
12334      */
12335     @Deprecated
12336     @SystemApi
12337     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12338     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
enableVideoCalling(boolean enable)12339     public void enableVideoCalling(boolean enable) {
12340         try {
12341             ITelephony telephony = getITelephony();
12342             if (telephony != null)
12343                 telephony.enableVideoCalling(enable);
12344         } catch (RemoteException e) {
12345             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
12346         }
12347     }
12348 
12349     /**
12350      * @throws UnsupportedOperationException If the device does not have
12351      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
12352      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
12353      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
12354      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
12355      * determine if video calling is capable.
12356      * @hide
12357      */
12358     @Deprecated
12359     @SystemApi
12360     @RequiresPermission(anyOf = {
12361             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
12362             android.Manifest.permission.READ_PHONE_STATE
12363     })
12364     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
isVideoCallingEnabled()12365     public boolean isVideoCallingEnabled() {
12366         try {
12367             ITelephony telephony = getITelephony();
12368             if (telephony != null)
12369                 return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
12370         } catch (RemoteException e) {
12371             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
12372         }
12373         return false;
12374     }
12375 
12376     /**
12377      * Whether the device supports configuring the DTMF tone length.
12378      *
12379      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
12380      *
12381      * @throws UnsupportedOperationException If the device does not have
12382      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
12383      */
12384     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
canChangeDtmfToneLength()12385     public boolean canChangeDtmfToneLength() {
12386         try {
12387             ITelephony telephony = getITelephony();
12388             if (telephony != null) {
12389                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
12390                         getAttributionTag());
12391             }
12392         } catch (RemoteException e) {
12393             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
12394         } catch (SecurityException e) {
12395             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
12396         }
12397         return false;
12398     }
12399 
12400     /**
12401      * Whether the device is a world phone.
12402      *
12403      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
12404      *
12405      * @throws UnsupportedOperationException If the device does not have
12406      *          {@link PackageManager#FEATURE_TELEPHONY}.
12407      */
12408     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
isWorldPhone()12409     public boolean isWorldPhone() {
12410         try {
12411             ITelephony telephony = getITelephony();
12412             if (telephony != null) {
12413                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
12414             }
12415         } catch (RemoteException e) {
12416             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
12417         } catch (SecurityException e) {
12418             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
12419         }
12420         return false;
12421     }
12422 
12423     /**
12424      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
12425      * Whether the phone supports TTY mode.
12426      *
12427      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
12428      *
12429      */
12430     @Deprecated
isTtyModeSupported()12431     public boolean isTtyModeSupported() {
12432         try {
12433             TelecomManager telecomManager = null;
12434             if (mContext != null) {
12435                 telecomManager = mContext.getSystemService(TelecomManager.class);
12436             }
12437             if (telecomManager != null) {
12438                 return telecomManager.isTtySupported();
12439             }
12440         } catch (SecurityException e) {
12441             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
12442         }
12443         return false;
12444     }
12445 
12446     /**
12447      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
12448      * support for the feature and device firmware support.
12449      *
12450      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
12451      *
12452      * @throws UnsupportedOperationException If the device does not have
12453      *          {@link PackageManager#FEATURE_TELEPHONY_IMS}.
12454      */
12455     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_IMS)
isRttSupported()12456     public boolean isRttSupported() {
12457         try {
12458             ITelephony telephony = getITelephony();
12459             if (telephony != null) {
12460                 return telephony.isRttSupported(mSubId);
12461             }
12462         } catch (RemoteException e) {
12463             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
12464         } catch (SecurityException e) {
12465             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
12466         }
12467         return false;
12468     }
12469     /**
12470      * Whether the phone supports hearing aid compatibility.
12471      *
12472      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
12473      * otherwise.
12474      *
12475      * @throws UnsupportedOperationException If the device does not have
12476      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
12477      */
12478     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isHearingAidCompatibilitySupported()12479     public boolean isHearingAidCompatibilitySupported() {
12480         try {
12481             ITelephony telephony = getITelephony();
12482             if (telephony != null) {
12483                 return telephony.isHearingAidCompatibilitySupported();
12484             }
12485         } catch (RemoteException e) {
12486             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
12487         } catch (SecurityException e) {
12488             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
12489         }
12490         return false;
12491     }
12492 
12493     /**
12494      * Returns the IMS Registration Status for a particular Subscription ID.
12495      *
12496      * @param subId Subscription ID
12497      * @return true if IMS status is registered, false if the IMS status is not registered or a
12498      * RemoteException occurred.
12499      * @hide
12500      * @deprecated Use {@link ImsMmTelManager#getRegistrationState(Executor, Consumer)} instead.
12501      */
12502     @Deprecated
isImsRegistered(int subId)12503     public boolean isImsRegistered(int subId) {
12504         try {
12505             return getITelephony().isImsRegistered(subId);
12506         } catch (RemoteException | NullPointerException ex) {
12507             return false;
12508         }
12509     }
12510 
12511     /**
12512      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
12513      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
12514      * invalid subscription ID is used during creation, will the default subscription ID will be
12515      * used.
12516      *
12517      * @return true if IMS status is registered, false if the IMS status is not registered or a
12518      * RemoteException occurred.
12519      * @see SubscriptionManager#getDefaultSubscriptionId()
12520      * @deprecated Use {@link ImsMmTelManager#getRegistrationState(Executor, Consumer)} instead.
12521      * @hide
12522      */
12523     @Deprecated
12524     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()12525     public boolean isImsRegistered() {
12526        try {
12527            return getITelephony().isImsRegistered(getSubId());
12528        } catch (RemoteException | NullPointerException ex) {
12529            return false;
12530        }
12531     }
12532 
12533     /**
12534      * The current status of Voice over LTE for the subscription associated with this instance when
12535      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
12536      * used during creation, the default subscription ID will be used.
12537      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
12538      * @see SubscriptionManager#getDefaultSubscriptionId()
12539      * <p>
12540      * @Deprecated Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
12541      * @hide
12542      */
12543     @Deprecated
12544     @UnsupportedAppUsage
isVolteAvailable()12545     public boolean isVolteAvailable() {
12546         try {
12547             return getITelephony().isAvailable(getSubId(),
12548                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
12549                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
12550         } catch (RemoteException | NullPointerException ex) {
12551             return false;
12552         }
12553     }
12554 
12555     /**
12556      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
12557      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
12558      * used during creation, the default subscription ID will be used. To query the
12559      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
12560      * @return true if VT is available, or false if it is unavailable or unknown.
12561      * @Deprecated Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
12562      * @hide
12563      */
12564     @Deprecated
12565     @UnsupportedAppUsage
isVideoTelephonyAvailable()12566     public boolean isVideoTelephonyAvailable() {
12567         try {
12568             return getITelephony().isVideoTelephonyAvailable(getSubId());
12569         } catch (RemoteException | NullPointerException ex) {
12570             return false;
12571         }
12572     }
12573 
12574     /**
12575      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
12576      * @param subId the subscription ID.
12577      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
12578      * @Deprecated Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
12579      * @hide
12580      */
12581     @Deprecated
12582     @UnsupportedAppUsage
isWifiCallingAvailable()12583     public boolean isWifiCallingAvailable() {
12584        try {
12585            return getITelephony().isWifiCallingAvailable(getSubId());
12586        } catch (RemoteException | NullPointerException ex) {
12587            return false;
12588        }
12589    }
12590 
12591     /**
12592      * The technology that IMS is registered for for the MMTEL feature.
12593      * @param subId subscription ID to get IMS registration technology for.
12594      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
12595      * Valid return results are:
12596      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
12597      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
12598      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_CROSS_SIM} for registration over
12599      *  other sim's internet, or
12600      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
12601      *  result is unavailable.
12602      *  @Deprecated Use {@link ImsMmTelManager#registerImsRegistrationCallback(Executor, RegistrationCallback)}
12603      *      or {@link ImsMmTelManager#getRegistrationTransportType(Executor, Consumer)} instead.
12604      *  @hide
12605      */
12606     @Deprecated
getImsRegTechnologyForMmTel()12607     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
12608         try {
12609             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
12610         } catch (RemoteException ex) {
12611             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
12612         }
12613     }
12614 
12615    /**
12616     * Set TelephonyProperties.icc_operator_numeric for the given phone.
12617     *
12618     * @hide
12619     */
12620     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setSimOperatorNumericForPhone(int phoneId, String numeric)12621     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
12622         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12623             List<String> newList = updateTelephonyProperty(
12624                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
12625             TelephonyProperties.icc_operator_numeric(newList);
12626         }
12627     }
12628 
12629     /**
12630      * Set TelephonyProperties.icc_operator_alpha for the given phone.
12631      *
12632      * @hide
12633      */
12634     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)12635     public void setSimOperatorNameForPhone(int phoneId, String name) {
12636         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12637             List<String> newList = updateTelephonyProperty(
12638                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
12639             TelephonyProperties.icc_operator_alpha(newList);
12640         }
12641     }
12642 
12643    /**
12644     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
12645     *
12646     * @hide
12647     */
setSimCountryIso(String iso)12648     public void setSimCountryIso(String iso) {
12649         int phoneId = getPhoneId();
12650         setSimCountryIsoForPhone(phoneId, iso);
12651     }
12652 
12653    /**
12654     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
12655     *
12656     * @hide
12657     */
12658     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)12659     public void setSimCountryIsoForPhone(int phoneId, String iso) {
12660         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12661             List<String> newList = updateTelephonyProperty(
12662                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
12663             TelephonyProperties.icc_operator_iso_country(newList);
12664         }
12665     }
12666 
12667     /**
12668      * Set TelephonyProperties.sim_state for the default phone.
12669      *
12670      * @hide
12671      */
setSimState(String state)12672     public void setSimState(String state) {
12673         int phoneId = getPhoneId();
12674         setSimStateForPhone(phoneId, state);
12675     }
12676 
12677     /**
12678      * Set TelephonyProperties.sim_state for the given phone.
12679      *
12680      * @hide
12681      */
12682     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)12683     public void setSimStateForPhone(int phoneId, String state) {
12684         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12685             List<String> newList = updateTelephonyProperty(
12686                     TelephonyProperties.sim_state(), phoneId, state);
12687             TelephonyProperties.sim_state(newList);
12688         }
12689     }
12690 
12691     /**
12692      * Powers down the SIM. SIM must be up prior.
12693      * @hide
12694      */
12695     public static final int CARD_POWER_DOWN = 0;
12696 
12697     /**
12698      * Powers up the SIM normally. SIM must be down prior.
12699      * @hide
12700      */
12701     public static final int CARD_POWER_UP = 1;
12702 
12703     /**
12704      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
12705      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
12706      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
12707      * and the SIM card is controlled completely by Telephony sending APDUs
12708      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
12709      * number of card apps will be 0.
12710      * No new error code is generated. Emergency calls are supported in the
12711      * same way as if the SIM card is absent.
12712      * The PASS_THROUGH mode is valid only for the specific card session where it
12713      * is activated, and normal behavior occurs at the next SIM initialization,
12714      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
12715      * is NOT persistent across boots. On reboot, SIM will power up normally.
12716      * @hide
12717      */
12718     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
12719 
12720     /** @hide */
12721     @Retention(RetentionPolicy.SOURCE)
12722     @IntDef(prefix = {"CARD_POWER"},
12723             value = {
12724                     CARD_POWER_DOWN,
12725                     CARD_POWER_UP,
12726                     CARD_POWER_UP_PASS_THROUGH,
12727             })
12728     public @interface SimPowerState {}
12729 
12730     /**
12731      * Set SIM card power state.
12732      *
12733      * @param state  State of SIM (power down, power up, pass through)
12734      * @see #CARD_POWER_DOWN
12735      * @see #CARD_POWER_UP
12736      * @see #CARD_POWER_UP_PASS_THROUGH
12737      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
12738      * broadcasts to determine success or failure and timeout if needed.
12739      *
12740      * @deprecated prefer {@link setSimPowerState(int, Executor, Consumer<Integer>)}.
12741      * There is no guarantee that SIM power changes will trigger ACTION_SIM_STATE_CHANGED on new
12742      * devices.
12743      *
12744      * <p>Requires Permission:
12745      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12746      *
12747      * @throws UnsupportedOperationException If the device does not have
12748      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12749      * {@hide}
12750      **/
12751     @SystemApi
12752     @Deprecated
12753     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12754     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerState(int state)12755     public void setSimPowerState(int state) {
12756         setSimPowerStateForSlot(getSlotIndex(), state);
12757     }
12758 
12759     /**
12760      * Set SIM card power state.
12761      *
12762      * @param slotIndex SIM slot id
12763      * @param state  State of SIM (power down, power up, pass through)
12764      * @see #CARD_POWER_DOWN
12765      * @see #CARD_POWER_UP
12766      * @see #CARD_POWER_UP_PASS_THROUGH
12767      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
12768      * broadcasts to determine success or failure and timeout if needed.
12769      *
12770      * @deprecated prefer {@link setSimPowerStateForSlot(int, int, Executor, Consumer<Integer>)}.
12771      * changes will trigger ACTION_SIM_STATE_CHANGED on new devices.
12772      *
12773      * <p>Requires Permission:
12774      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12775      *
12776      * @throws UnsupportedOperationException If the device does not have
12777      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12778      * {@hide}
12779      **/
12780     @SystemApi
12781     @Deprecated
12782     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12783     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerStateForSlot(int slotIndex, int state)12784     public void setSimPowerStateForSlot(int slotIndex, int state) {
12785         try {
12786             ITelephony telephony = getITelephony();
12787             if (telephony != null) {
12788                 telephony.setSimPowerStateForSlot(slotIndex, state);
12789             }
12790         } catch (RemoteException e) {
12791             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
12792         } catch (SecurityException e) {
12793             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
12794         }
12795     }
12796 
12797     /**
12798      * Set SIM card power state.
12799      *
12800      * @param state  State of SIM (power down, power up, pass through)
12801      * @see #CARD_POWER_DOWN
12802      * @see #CARD_POWER_UP
12803      * @see #CARD_POWER_UP_PASS_THROUGH
12804      * @param executor The executor of where the callback will execute.
12805      * @param callback Callback will be triggered once it succeeds or failed.
12806      * @see #SET_SIM_POWER_STATE_SUCCESS
12807      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
12808      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
12809      * @see #SET_SIM_POWER_STATE_SIM_ERROR
12810      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
12811      * @throws IllegalArgumentException if requested SIM state is invalid
12812      *
12813      * <p>Requires Permission:
12814      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12815      *
12816      * @throws UnsupportedOperationException If the device does not have
12817      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12818      * {@hide}
12819      **/
12820     @SystemApi
12821     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12822     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerState(@imPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)12823     public void setSimPowerState(@SimPowerState int state, @NonNull Executor executor,
12824             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
12825         setSimPowerStateForSlot(getSlotIndex(), state, executor, callback);
12826     }
12827 
12828     /**
12829      * Set SIM card power state.
12830      *
12831      * @param slotIndex SIM slot id
12832      * @param state  State of SIM (power down, power up, pass through)
12833      * @see #CARD_POWER_DOWN
12834      * @see #CARD_POWER_UP
12835      * @see #CARD_POWER_UP_PASS_THROUGH
12836      * @param executor The executor of where the callback will execute.
12837      * @param callback Callback will be triggered once it succeeds or failed.
12838      * @see #SET_SIM_POWER_STATE_SUCCESS
12839      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
12840      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
12841      * @see #SET_SIM_POWER_STATE_SIM_ERROR
12842      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
12843      * @throws IllegalArgumentException if requested SIM state is invalid
12844      *
12845      * <p>Requires Permission:
12846      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12847      *
12848      * @throws UnsupportedOperationException If the device does not have
12849      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
12850      * {@hide}
12851      **/
12852     @SystemApi
12853     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12854     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setSimPowerStateForSlot(int slotIndex, @SimPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)12855     public void setSimPowerStateForSlot(int slotIndex, @SimPowerState int state,
12856             @NonNull Executor executor,
12857             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
12858         if (state != CARD_POWER_DOWN && state != CARD_POWER_UP
12859                 && state != CARD_POWER_UP_PASS_THROUGH) {
12860             throw new IllegalArgumentException("requested SIM state is invalid");
12861         }
12862         try {
12863             ITelephony telephony = getITelephony();
12864             if (telephony == null) throw new IllegalStateException("Telephony is null.");
12865 
12866             IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
12867                 @Override
12868                 public void accept(int result) {
12869                     executor.execute(() ->
12870                             Binder.withCleanCallingIdentity(() -> callback.accept(result)));
12871                 }
12872             };
12873             if (telephony == null) {
12874                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
12875                     throw new IllegalStateException("Telephony is null");
12876                 } else {
12877                     return;
12878                 }
12879             }
12880             telephony.setSimPowerStateForSlotWithCallback(slotIndex, state, internalCallback);
12881         } catch (RemoteException e) {
12882             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
12883             runOnBackgroundThread(() -> executor.execute(
12884                     () -> callback.accept(SET_SIM_POWER_STATE_MODEM_ERROR)));
12885         } catch (SecurityException e) {
12886             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot",
12887                     e);
12888         }
12889     }
12890 
12891     /**
12892      * Set baseband version by phone id.
12893      *
12894      * @param phoneId for which baseband version is set
12895      * @param version baseband version
12896      * @hide
12897      */
12898     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)12899     public void setBasebandVersionForPhone(int phoneId, String version) {
12900         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12901             List<String> newList = updateTelephonyProperty(
12902                     TelephonyProperties.baseband_version(), phoneId, version);
12903             TelephonyProperties.baseband_version(newList);
12904         }
12905     }
12906 
12907     /**
12908      * Get baseband version for the default phone.
12909      *
12910      * @return baseband version.
12911      * @hide
12912      */
getBasebandVersion()12913     public String getBasebandVersion() {
12914         int phoneId = getPhoneId();
12915         return getBasebandVersionForPhone(phoneId);
12916     }
12917 
12918     /**
12919      * Get baseband version by phone id.
12920      *
12921      * @return baseband version.
12922      * @hide
12923      */
getBasebandVersionForPhone(int phoneId)12924     public String getBasebandVersionForPhone(int phoneId) {
12925         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
12926     }
12927 
12928     /**
12929      * Set phone type by phone id.
12930      *
12931      * @param phoneId for which phone type is set
12932      * @param type phone type
12933      *
12934      * @hide
12935      */
12936     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)12937     public void setPhoneType(int phoneId, int type) {
12938         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12939             List<Integer> newList = updateTelephonyProperty(
12940                     TelephonyProperties.current_active_phone(), phoneId, type);
12941             TelephonyProperties.current_active_phone(newList);
12942         }
12943     }
12944 
12945     /**
12946      * Get OTASP number schema by phone id.
12947      *
12948      * @param phoneId for which OTA SP number schema is get
12949      * @param defaultValue default value
12950      * @return OTA SP number schema
12951      *
12952      * @hide
12953      */
12954     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)12955     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
12956         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12957             return getTelephonyProperty(
12958                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
12959         }
12960 
12961         return defaultValue;
12962     }
12963 
12964     /**
12965      * Get SMS receive capable from system property by phone id.
12966      *
12967      * @param phoneId for which SMS receive capable is get
12968      * @param defaultValue default value
12969      * @return SMS receive capable
12970      *
12971      * @hide
12972      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)12973     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
12974         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12975             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
12976         }
12977 
12978         return defaultValue;
12979     }
12980 
12981     /**
12982      * Get SMS send capable from system property by phone id.
12983      *
12984      * @param phoneId for which SMS send capable is get
12985      * @param defaultValue default value
12986      * @return SMS send capable
12987      *
12988      * @hide
12989      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)12990     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
12991         if (SubscriptionManager.isValidPhoneId(phoneId)) {
12992             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
12993         }
12994 
12995         return defaultValue;
12996     }
12997 
12998     /**
12999      * Get the component name of the default app to direct respond-via-message intent for the
13000      * user associated with this subscription, update the cache if there is no respond-via-message
13001      * application currently configured for this user.
13002      * @return component name of the app and class to direct Respond Via Message intent to, or
13003      * {@code null} if the functionality is not supported.
13004      *
13005      * @throws UnsupportedOperationException If the device does not have
13006      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
13007      * @hide
13008      */
13009     @SystemApi
13010     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
13011     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getAndUpdateDefaultRespondViaMessageApplication()13012     public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
13013         try {
13014             ITelephony telephony = getITelephony();
13015             if (telephony != null) {
13016                 return telephony.getDefaultRespondViaMessageApplication(getSubId(), true);
13017             }
13018         } catch (RemoteException e) {
13019             Log.e(TAG, "Error in getAndUpdateDefaultRespondViaMessageApplication: " + e);
13020         }
13021         return null;
13022     }
13023 
13024     /**
13025      * Get the component name of the default app to direct respond-via-message intent for the
13026      * user associated with this subscription.
13027      * @return component name of the app and class to direct Respond Via Message intent to, or
13028      * {@code null} if the functionality is not supported.
13029      *
13030      * @throws UnsupportedOperationException If the device does not have
13031      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
13032      * @hide
13033      */
13034     @SystemApi
13035     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
13036     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
getDefaultRespondViaMessageApplication()13037     public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
13038         try {
13039             ITelephony telephony = getITelephony();
13040             if (telephony != null) {
13041                 return telephony.getDefaultRespondViaMessageApplication(getSubId(), false);
13042             }
13043         } catch (RemoteException e) {
13044             Log.e(TAG, "Error in getDefaultRespondViaMessageApplication: " + e);
13045         }
13046         return null;
13047     }
13048 
13049     /**
13050      * Set the alphabetic name of current registered operator.
13051      * @param phoneId which phone you want to set
13052      * @param name the alphabetic name of current registered operator.
13053      * @hide
13054      */
13055     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNameForPhone(int phoneId, String name)13056     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
13057         if (SubscriptionManager.isValidPhoneId(phoneId)) {
13058             List<String> newList = updateTelephonyProperty(
13059                     TelephonyProperties.operator_alpha(), phoneId, name);
13060             try {
13061                 TelephonyProperties.operator_alpha(newList);
13062             } catch (IllegalArgumentException e) { //property value is longer than the byte limit
13063                 Log.e(TAG, "setNetworkOperatorNameForPhone: ", e);
13064 
13065                 int numberOfEntries = newList.size();
13066                 int maxOperatorLength = //save 1 byte for joiner " , "
13067                         (SystemProperties.PROP_VALUE_MAX - numberOfEntries) / numberOfEntries;
13068 
13069                 //examine and truncate every operator and retry
13070                 for (int i = 0; i < newList.size(); i++) {
13071                     if (newList.get(i) != null) {
13072                         newList.set(i, TextUtils
13073                                 .truncateStringForUtf8Storage(newList.get(i), maxOperatorLength));
13074                     }
13075                 }
13076                 TelephonyProperties.operator_alpha(newList);
13077                 Log.e(TAG, "successfully truncated operator_alpha: " + newList);
13078             }
13079         }
13080     }
13081 
13082     /**
13083      * Set the numeric name (MCC+MNC) of current registered operator.
13084      * @param phoneId for which phone type is set
13085      * @param operator the numeric name (MCC+MNC) of current registered operator
13086      * @hide
13087      */
13088     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNumericForPhone(int phoneId, String numeric)13089     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
13090         if (SubscriptionManager.isValidPhoneId(phoneId)) {
13091             List<String> newList = updateTelephonyProperty(
13092                     TelephonyProperties.operator_numeric(), phoneId, numeric);
13093             TelephonyProperties.operator_numeric(newList);
13094         }
13095     }
13096 
13097     /**
13098      * Set roaming state of the current network, for GSM purposes.
13099      * @param phoneId which phone you want to set
13100      * @param isRoaming is network in romaing state or not
13101      * @hide
13102      */
13103     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)13104     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
13105         if (SubscriptionManager.isValidPhoneId(phoneId)) {
13106             List<Boolean> newList = updateTelephonyProperty(
13107                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
13108             TelephonyProperties.operator_is_roaming(newList);
13109         }
13110     }
13111 
13112     /**
13113      * Set the network type currently in use on the device for data transmission.
13114      *
13115      * If this object has been created with {@link #createForSubscriptionId}, applies to the
13116      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
13117      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
13118      * @param type the network type currently in use on the device for data transmission
13119      * @hide
13120      */
setDataNetworkType(int type)13121     public void setDataNetworkType(int type) {
13122         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
13123         setDataNetworkTypeForPhone(phoneId, type);
13124     }
13125 
13126     /**
13127      * Set the network type currently in use on the device for data transmission.
13128      * @param phoneId which phone you want to set
13129      * @param type the network type currently in use on the device for data transmission
13130      * @hide
13131      */
13132     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setDataNetworkTypeForPhone(int phoneId, int type)13133     public void setDataNetworkTypeForPhone(int phoneId, int type) {
13134         if (SubscriptionManager.isValidPhoneId(phoneId)) {
13135             List<String> newList = updateTelephonyProperty(
13136                     TelephonyProperties.data_network_type(), phoneId,
13137                     ServiceState.rilRadioTechnologyToString(type));
13138             TelephonyProperties.data_network_type(newList);
13139         }
13140     }
13141 
13142     /**
13143      * Returns the subscription ID for the given phone account.
13144      * @hide
13145      */
13146     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)13147     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
13148         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
13149         if (phoneAccount != null
13150                 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
13151             retval = getSubscriptionId(phoneAccount.getAccountHandle());
13152         }
13153         return retval;
13154     }
13155 
13156     /**
13157      * Determines the {@link PhoneAccountHandle} associated with this TelephonyManager.
13158      *
13159      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13160      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
13161      *
13162      * <p>Requires Permission android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE or that the
13163      * calling app has carrier privileges (see {@link #hasCarrierPrivileges})
13164      *
13165      * @return The {@link PhoneAccountHandle} associated with the TelphonyManager, or {@code null}
13166      * if there is no associated {@link PhoneAccountHandle}; this can happen if the subscription is
13167      * data-only or an opportunistic subscription.
13168      *
13169      * @throws UnsupportedOperationException If the device does not have
13170      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13171      */
13172     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13173     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13174     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getPhoneAccountHandle()13175     public @Nullable PhoneAccountHandle getPhoneAccountHandle() {
13176         return getPhoneAccountHandleForSubscriptionId(getSubId());
13177     }
13178 
13179     /**
13180      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
13181      *
13182      * @param subscriptionId The subscription Id to check.
13183      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
13184      * there is no associated {@link PhoneAccountHandle}.
13185      * @hide
13186      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)13187     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
13188         PhoneAccountHandle returnValue = null;
13189         try {
13190             ITelephony service = getITelephony();
13191             if (service != null) {
13192                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
13193             }
13194         } catch (RemoteException e) {
13195         }
13196 
13197         return returnValue;
13198     }
13199 
13200     /**
13201      * Returns the subscription ID for the given phone account handle.
13202      *
13203      * @param phoneAccountHandle the phone account handle for outgoing calls
13204      * @return subscription ID for the given phone account handle; or
13205      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
13206      *         if not available; or throw a SecurityException if the caller doesn't have the
13207      *         permission.
13208      */
13209     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
13210     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)13211     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
13212         return mPhoneAccountHandleToSubIdCache.query(phoneAccountHandle);
13213     }
13214 
13215     /**
13216      * Resets telephony manager settings back to factory defaults.
13217      *
13218      * @hide
13219      */
factoryReset(int subId)13220     public void factoryReset(int subId) {
13221         try {
13222             Log.d(TAG, "factoryReset: subId=" + subId);
13223             ITelephony telephony = getITelephony();
13224             if (telephony != null) {
13225                 telephony.factoryReset(subId, getOpPackageName());
13226             }
13227         } catch (RemoteException e) {
13228         }
13229     }
13230 
13231 
13232     /**
13233      * Resets Telephony and IMS settings back to factory defaults only for the subscription
13234      * associated with this instance.
13235      * @see #createForSubscriptionId(int)
13236      *
13237      * @throws UnsupportedOperationException If the device does not have
13238      *          {@link PackageManager#FEATURE_TELEPHONY}.
13239      * @hide
13240      */
13241     @SystemApi
13242     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
13243     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
resetSettings()13244     public void resetSettings() {
13245         try {
13246             Log.d(TAG, "resetSettings: subId=" + getSubId());
13247             ITelephony telephony = getITelephony();
13248             if (telephony != null) {
13249                 telephony.factoryReset(getSubId(), getOpPackageName());
13250             }
13251         } catch (RemoteException e) {
13252         }
13253     }
13254 
13255 
13256     /**
13257      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
13258      * no locale could be derived from subscriptions.
13259      *
13260      * <p>Requires Permission:
13261      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
13262      *
13263      * @see Locale#toLanguageTag()
13264      *
13265      * @throws UnsupportedOperationException If the device does not have
13266      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13267      * @hide
13268      */
13269     @SystemApi
13270     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13271     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimLocale()13272     @Nullable public Locale getSimLocale() {
13273         try {
13274             final ITelephony telephony = getITelephony();
13275             if (telephony != null) {
13276                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
13277                 if (!TextUtils.isEmpty(languageTag)) {
13278                     return Locale.forLanguageTag(languageTag);
13279                 }
13280             }
13281         } catch (RemoteException ex) {
13282         }
13283         return null;
13284     }
13285 
13286     /**
13287      * Exception that may be supplied to the callback provided in {@link #requestModemActivityInfo}.
13288      * @hide
13289      */
13290     @SystemApi
13291     public static class ModemActivityInfoException extends Exception {
13292         /** Indicates that an unknown error occurred */
13293         public static final int ERROR_UNKNOWN = 0;
13294 
13295         /**
13296          * Indicates that the modem or phone processes are not available (such as when the device
13297          * is in airplane mode).
13298          */
13299         public static final int ERROR_PHONE_NOT_AVAILABLE = 1;
13300 
13301         /**
13302          * Indicates that the modem supplied an invalid instance of {@link ModemActivityInfo}
13303          */
13304         public static final int ERROR_INVALID_INFO_RECEIVED = 2;
13305 
13306         /**
13307          * Indicates that the modem encountered an internal failure when processing the request
13308          * for activity info.
13309          */
13310         public static final int ERROR_MODEM_RESPONSE_ERROR = 3;
13311 
13312         /** @hide */
13313         @Retention(RetentionPolicy.SOURCE)
13314         @IntDef(prefix = {"ERROR_"},
13315                 value = {
13316                         ERROR_UNKNOWN,
13317                         ERROR_PHONE_NOT_AVAILABLE,
13318                         ERROR_INVALID_INFO_RECEIVED,
13319                         ERROR_MODEM_RESPONSE_ERROR,
13320                 })
13321         public @interface ModemActivityInfoError {}
13322 
13323         private final int mErrorCode;
13324 
13325         /**
13326          * An exception with ModemActivityInfo specific error codes.
13327          *
13328          * @param errorCode a ModemActivityInfoError code.
13329          */
ModemActivityInfoException(@odemActivityInfoError int errorCode)13330         public ModemActivityInfoException(@ModemActivityInfoError int errorCode) {
13331             mErrorCode = errorCode;
13332         }
13333 
getErrorCode()13334         public @ModemActivityInfoError int getErrorCode() {
13335             return mErrorCode;
13336         }
13337 
13338         @Override
toString()13339         public String toString() {
13340             switch (mErrorCode) {
13341                 case ERROR_UNKNOWN: return "ERROR_UNKNOWN";
13342                 case ERROR_PHONE_NOT_AVAILABLE: return "ERROR_PHONE_NOT_AVAILABLE";
13343                 case ERROR_INVALID_INFO_RECEIVED: return "ERROR_INVALID_INFO_RECEIVED";
13344                 case ERROR_MODEM_RESPONSE_ERROR: return "ERROR_MODEM_RESPONSE_ERROR";
13345                 default: return "UNDEFINED";
13346             }
13347         }
13348     }
13349 
13350     /**
13351      * Requests the current modem activity info.
13352      *
13353      * The provided instance of {@link ModemActivityInfo} represents the cumulative activity since
13354      * the last restart of the phone process.
13355      *
13356      * @param callback A callback object to which the result will be delivered. If there was an
13357      *                 error processing the request, {@link OutcomeReceiver#onError} will be called
13358      *                 with more details about the error.
13359      *
13360      * @throws UnsupportedOperationException If the device does not have
13361      *          {@link PackageManager#FEATURE_TELEPHONY}.
13362      * @hide
13363      */
13364     @SystemApi
13365     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
13366     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
requestModemActivityInfo(@onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback)13367     public void requestModemActivityInfo(@NonNull @CallbackExecutor Executor executor,
13368             @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback) {
13369         Objects.requireNonNull(executor);
13370         Objects.requireNonNull(callback);
13371 
13372         // Pass no handler into the receiver, since we're going to be trampolining the call to the
13373         // listener onto the provided executor.
13374         ResultReceiver wrapperResultReceiver = new ResultReceiver(null) {
13375             @Override
13376             protected void onReceiveResult(int resultCode, Bundle data) {
13377                 if (data == null) {
13378                     Log.w(TAG, "requestModemActivityInfo: received null bundle");
13379                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
13380                     return;
13381                 }
13382                 data.setDefusable(true);
13383                 if (data.containsKey(EXCEPTION_RESULT_KEY)) {
13384                     int receivedErrorCode = data.getInt(EXCEPTION_RESULT_KEY);
13385                     sendErrorToListener(receivedErrorCode);
13386                     return;
13387                 }
13388 
13389                 if (!data.containsKey(MODEM_ACTIVITY_RESULT_KEY)) {
13390                     Log.w(TAG, "requestModemActivityInfo: Bundle did not contain expected key");
13391                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
13392                     return;
13393                 }
13394                 Parcelable receivedResult = data.getParcelable(MODEM_ACTIVITY_RESULT_KEY);
13395                 if (!(receivedResult instanceof ModemActivityInfo)) {
13396                     Log.w(TAG, "requestModemActivityInfo: Bundle contained something that wasn't "
13397                             + "a ModemActivityInfo.");
13398                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
13399                     return;
13400                 }
13401                 ModemActivityInfo modemActivityInfo = (ModemActivityInfo) receivedResult;
13402                 if (!modemActivityInfo.isValid()) {
13403                     Log.w(TAG, "requestModemActivityInfo: Received an invalid ModemActivityInfo");
13404                     sendErrorToListener(ModemActivityInfoException.ERROR_INVALID_INFO_RECEIVED);
13405                     return;
13406                 }
13407                 Log.d(TAG, "requestModemActivityInfo: Sending result to app: " + modemActivityInfo);
13408                 sendResultToListener(modemActivityInfo);
13409             }
13410 
13411             private void sendResultToListener(ModemActivityInfo info) {
13412                 Binder.withCleanCallingIdentity(() ->
13413                         executor.execute(() ->
13414                                 callback.onResult(info)));
13415             }
13416 
13417             private void sendErrorToListener(int code) {
13418                 ModemActivityInfoException e = new ModemActivityInfoException(code);
13419                 Binder.withCleanCallingIdentity(() ->
13420                         executor.execute(() ->
13421                                 callback.onError(e)));
13422             }
13423         };
13424 
13425         try {
13426             ITelephony service = getITelephony();
13427             if (service != null) {
13428                 service.requestModemActivityInfo(wrapperResultReceiver);
13429                 return;
13430             }
13431         } catch (RemoteException e) {
13432             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
13433         }
13434         executor.execute(() -> callback.onError(
13435                 new ModemActivityInfoException(
13436                         ModemActivityInfoException.ERROR_PHONE_NOT_AVAILABLE)));
13437     }
13438 
13439     /**
13440      * Returns the current {@link ServiceState} information.
13441      *
13442      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13443      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
13444      *
13445      * If you want continuous updates of service state info, register a {@link TelephonyCallback}
13446      * that implements {@link TelephonyCallback.ServiceStateListener} through {@link
13447      * #registerTelephonyCallback}.
13448      *
13449      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
13450      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
13451      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
13452      * May return {@code null} when the subscription is inactive or when there was an error
13453      * communicating with the phone process.
13454      *
13455      * @throws UnsupportedOperationException If the device does not have
13456      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
13457      */
13458     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13459     @RequiresPermission(allOf = {
13460             Manifest.permission.READ_PHONE_STATE,
13461             Manifest.permission.ACCESS_COARSE_LOCATION
13462     })
13463     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceState()13464     public @Nullable ServiceState getServiceState() {
13465         return getServiceState(getLocationData());
13466     }
13467 
13468     /**
13469      * Returns the current {@link ServiceState} information.
13470      *
13471      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
13472      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
13473      *
13474      * If you want continuous updates of service state info, register a {@link TelephonyCallback}
13475      * that implements {@link TelephonyCallback.ServiceStateListener} through {@link
13476      * #registerTelephonyCallback}.
13477      *
13478      * There's another way to renounce permissions with a custom context
13479      * {@code AttributionSource.Builder#setRenouncedPermissions(Set<String>)} but only for system
13480      * apps. To avoid confusion, calling this method supersede renouncing permissions with a
13481      * custom context.
13482      *
13483      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
13484      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
13485      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
13486      * @param includeLocationData Specifies if the caller would like to receive
13487      * location related information.
13488      * May return {@code null} when the subscription is inactive or when there was an error
13489      * communicating with the phone process.
13490      *
13491      * @throws UnsupportedOperationException If the device does not have
13492      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
13493      */
13494     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13495     @RequiresPermission(allOf = {
13496             Manifest.permission.READ_PHONE_STATE,
13497             Manifest.permission.ACCESS_COARSE_LOCATION
13498     })
13499     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceState(@ncludeLocationData int includeLocationData)13500     public @Nullable ServiceState getServiceState(@IncludeLocationData int includeLocationData) {
13501         return getServiceStateForSlot(SubscriptionManager.getSlotIndex(getSubId()),
13502                 includeLocationData != INCLUDE_LOCATION_DATA_FINE,
13503                 includeLocationData == INCLUDE_LOCATION_DATA_NONE);
13504     }
13505 
13506     /**
13507      * Returns the service state information on specified SIM slot.
13508      *
13509      * May return {@code null} when the {@code slotIndex} is invalid or when there was an error
13510      * communicating with the phone process.
13511      *
13512      * @param slotIndex of phone whose service state is returned
13513      * @param renounceFineLocationAccess Set this to true if the caller would not like to receive
13514      * location related information which will be sent if the caller already possess
13515      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and do not renounce the permission
13516      * @param renounceCoarseLocationAccess Set this to true if the caller would not like to
13517      * receive location related information which will be sent if the caller already possess
13518      * {@link Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the permissions.
13519      * @return Service state on specified SIM slot.
13520      */
getServiceStateForSlot(int slotIndex, boolean renounceFineLocationAccess, boolean renounceCoarseLocationAccess)13521     private ServiceState getServiceStateForSlot(int slotIndex, boolean renounceFineLocationAccess,
13522             boolean renounceCoarseLocationAccess) {
13523         try {
13524             ITelephony service = getITelephony();
13525             if (service != null) {
13526                 return service.getServiceStateForSlot(slotIndex,
13527                         renounceFineLocationAccess, renounceCoarseLocationAccess,
13528                         getOpPackageName(), getAttributionTag());
13529             }
13530         } catch (RemoteException e) {
13531             Log.e(TAG, "Error calling ITelephony#getServiceStateForSlot", e);
13532         } catch (NullPointerException e) {
13533             AnomalyReporter.reportAnomaly(
13534                     UUID.fromString("e2bed88e-def9-476e-bd71-3e572a8de6d1"),
13535                     "getServiceStateForSlot " + slotIndex + " NPE");
13536         }
13537         return null;
13538     }
13539 
13540     /**
13541      * Returns the service state information on specified subscription. Callers require
13542      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
13543      *
13544      * May return {@code null} when the subscription is inactive or when there was an error
13545      * communicating with the phone process.
13546      * @hide
13547      */
13548     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)13549     public ServiceState getServiceStateForSubscriber(int subId) {
13550         return getServiceStateForSlot(
13551                 SubscriptionManager.getSlotIndex(subId), false, false);
13552     }
13553 
13554     /**
13555      * Returns the service state information on specified SIM slot.
13556      *
13557      * If you want continuous updates of service state info, register a {@link TelephonyCallback}
13558      * that implements {@link TelephonyCallback.ServiceStateListener} through
13559      * {@link #registerTelephonyCallback}.
13560      *
13561      * May return {@code null} when the {@code slotIndex} is invalid or when there was an error
13562      * communicating with the phone process
13563      *
13564      * See {@link #getActiveModemCount()} to get the total number of slots
13565      * that are active on the device.
13566      *
13567      * @param slotIndex of phone whose service state is returned
13568      * @return ServiceState on specified SIM slot.
13569      *
13570      * @hide
13571      */
13572     @RequiresPermission(allOf = {
13573             Manifest.permission.READ_PHONE_STATE,
13574             Manifest.permission.ACCESS_COARSE_LOCATION
13575     })
13576     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getServiceStateForSlot(int slotIndex)13577     public @Nullable ServiceState getServiceStateForSlot(int slotIndex) {
13578         return getServiceStateForSlot(slotIndex, false, false);
13579     }
13580 
13581     /**
13582      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
13583      *
13584      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
13585      * voicemail ringtone.
13586      * @return The URI for the ringtone to play when receiving a voicemail from a specific
13587      * PhoneAccount. May be {@code null} if no ringtone is set.
13588      *
13589      * @throws UnsupportedOperationException If the device does not have
13590      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13591      */
13592     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)13593     public @Nullable Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
13594         try {
13595             ITelephony service = getITelephony();
13596             if (service != null) {
13597                 return service.getVoicemailRingtoneUri(accountHandle);
13598             }
13599         } catch (RemoteException e) {
13600             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
13601         }
13602         return null;
13603     }
13604 
13605     /**
13606      * Sets the per-account voicemail ringtone.
13607      *
13608      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
13609      * {@link #hasCarrierPrivileges}, or has permission
13610      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13611      *
13612      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
13613      * voicemail ringtone.
13614      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
13615      * PhoneAccount.
13616      *
13617      * @throws UnsupportedOperationException If the device does not have
13618      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13619      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
13620      * instead.
13621      */
13622     @Deprecated
13623     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)13624     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
13625         try {
13626             ITelephony service = getITelephony();
13627             if (service != null) {
13628                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
13629             }
13630         } catch (RemoteException e) {
13631             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
13632         }
13633     }
13634 
13635     /**
13636      * Returns whether vibration is set for voicemail notification in Phone settings.
13637      *
13638      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
13639      * voicemail vibration setting.
13640      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
13641      *
13642      * @throws UnsupportedOperationException If the device does not have
13643      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13644      */
13645     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)13646     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
13647         try {
13648             ITelephony service = getITelephony();
13649             if (service != null) {
13650                 return service.isVoicemailVibrationEnabled(accountHandle);
13651             }
13652         } catch (RemoteException e) {
13653             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
13654         }
13655         return false;
13656     }
13657 
13658     /**
13659      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
13660      *
13661      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
13662      * {@link #hasCarrierPrivileges}, or has permission
13663      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13664      *
13665      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
13666      * voicemail vibration setting.
13667      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
13668      * specific PhoneAccount.
13669      *
13670      * @throws UnsupportedOperationException If the device does not have
13671      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
13672      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
13673      * instead.
13674      */
13675     @Deprecated
13676     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)13677     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
13678             boolean enabled) {
13679         try {
13680             ITelephony service = getITelephony();
13681             if (service != null) {
13682                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
13683                         enabled);
13684             }
13685         } catch (RemoteException e) {
13686             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
13687         }
13688     }
13689 
13690     /**
13691      * Returns carrier id of the current subscription.
13692      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
13693      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
13694      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
13695      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13696      *
13697      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
13698      * as an Android platform-wide identifier for carriers.
13699      *
13700      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
13701      * subscription is unavailable or the carrier cannot be identified.
13702      *
13703      * @throws UnsupportedOperationException If the device does not have
13704      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13705      */
13706     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCarrierId()13707     public int getSimCarrierId() {
13708         try {
13709             ITelephony service = getITelephony();
13710             if (service != null) {
13711                 return service.getSubscriptionCarrierId(getSubId());
13712             }
13713         } catch (RemoteException ex) {
13714             // This could happen if binder process crashes.
13715         }
13716         return UNKNOWN_CARRIER_ID;
13717     }
13718 
13719     /**
13720      * Returns carrier id name of the current subscription.
13721      * <p>Carrier id name is a user-facing name of carrier id returned by
13722      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
13723      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
13724      * should have a single carrier name. Carrier name is not a canonical identity,
13725      * use {@link #getSimCarrierId()} instead.
13726      * <p>The returned carrier name is unlocalized.
13727      *
13728      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
13729      * unavailable or the carrier cannot be identified.
13730      *
13731      * @throws UnsupportedOperationException If the device does not have
13732      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13733      */
13734     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimCarrierIdName()13735     public @Nullable CharSequence getSimCarrierIdName() {
13736         try {
13737             ITelephony service = getITelephony();
13738             if (service != null) {
13739                 return service.getSubscriptionCarrierName(getSubId());
13740             }
13741         } catch (RemoteException ex) {
13742             // This could happen if binder process crashes.
13743         }
13744         return null;
13745     }
13746 
13747     /**
13748      * Returns fine-grained carrier ID of the current subscription.
13749      *
13750      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
13751      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
13752      * are used to make up the actual carrier service may have different carrier configurations.
13753      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
13754      * different carrier configuration for different service offering such as a prepaid plan.
13755      *
13756      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
13757      * about the carrier itself should use the regular carrier ID returned by
13758      * {@link #getSimCarrierId()}.
13759      *
13760      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
13761      * subscription while carrier ID remains the same.
13762      *
13763      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
13764      * <p>Specific carrier ids are defined in the same way as carrier id
13765      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13766      * except each with a "parent" id linking to its top-level carrier id.
13767      *
13768      * @return Returns fine-grained carrier id of the current subscription.
13769      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
13770      * be identified.
13771      *
13772      * @throws UnsupportedOperationException If the device does not have
13773      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13774      */
13775     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSpecificCarrierId()13776     public int getSimSpecificCarrierId() {
13777         try {
13778             ITelephony service = getITelephony();
13779             if (service != null) {
13780                 return service.getSubscriptionSpecificCarrierId(getSubId());
13781             }
13782         } catch (RemoteException ex) {
13783             // This could happen if binder process crashes.
13784         }
13785         return UNKNOWN_CARRIER_ID;
13786     }
13787 
13788     /**
13789      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
13790      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
13791      *
13792      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
13793      * about the carrier itself should use the regular carrier ID returned by
13794      * {@link #getSimCarrierIdName()}.
13795      *
13796      * <p>The returned name is unlocalized.
13797      *
13798      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
13799      * subscription is unavailable or the carrier cannot be identified.
13800      *
13801      * @throws UnsupportedOperationException If the device does not have
13802      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13803      */
13804     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getSimSpecificCarrierIdName()13805     public @Nullable CharSequence getSimSpecificCarrierIdName() {
13806         try {
13807             ITelephony service = getITelephony();
13808             if (service != null) {
13809                 return service.getSubscriptionSpecificCarrierName(getSubId());
13810             }
13811         } catch (RemoteException ex) {
13812             // This could happen if binder process crashes.
13813         }
13814         return null;
13815     }
13816 
13817     /**
13818      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
13819      * This is used for fallback when configurations/logic for exact carrier id
13820      * {@link #getSimCarrierId()} are not found.
13821      *
13822      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13823      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
13824      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
13825      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
13826      * take the update with the new id, it might be helpful to always fallback by using carrier
13827      * id based on MCCMNC if there is no match.
13828      *
13829      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
13830      * subscription is unavailable or the carrier cannot be identified.
13831      *
13832      * @throws UnsupportedOperationException If the device does not have
13833      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13834      */
13835     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierIdFromSimMccMnc()13836     public int getCarrierIdFromSimMccMnc() {
13837         try {
13838             ITelephony service = getITelephony();
13839             if (service != null) {
13840                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
13841             }
13842         } catch (RemoteException ex) {
13843             // This could happen if binder process crashes.
13844         }
13845         return UNKNOWN_CARRIER_ID;
13846     }
13847 
13848      /**
13849       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
13850       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
13851       * are not found.
13852       *
13853       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
13854       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
13855       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
13856       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
13857       * take the update with the new id, it might be helpful to always fallback by using carrier
13858       * id based on MCCMNC if there is no match.
13859       *
13860       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
13861       * subscription is unavailable or the carrier cannot be identified.
13862       * @hide
13863       */
13864      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)13865      public int getCarrierIdFromMccMnc(String mccmnc) {
13866         try {
13867             ITelephony service = getITelephony();
13868             if (service != null) {
13869                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
13870             }
13871         } catch (RemoteException ex) {
13872             // This could happen if binder process crashes.
13873         }
13874         return UNKNOWN_CARRIER_ID;
13875     }
13876 
13877     /**
13878      * Return a list of certs as hex strings from loaded carrier privileges access rules.
13879      *
13880      * @return a list of certificates as hex strings, or an empty list if there are no certs or
13881      *     privilege rules are not loaded yet.
13882      * @hide
13883      */
13884     @TestApi
13885     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13886     @NonNull
getCertsFromCarrierPrivilegeAccessRules()13887     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
13888         List<String> certs = null;
13889         try {
13890             ITelephony service = getITelephony();
13891             if (service != null) {
13892                 certs = service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
13893             }
13894         } catch (RemoteException ex) {
13895             // This could happen if binder process crashes.
13896         }
13897         return certs == null ? Collections.emptyList() : certs;
13898     }
13899 
13900     /**
13901      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
13902      * All uicc applications are uniquely identified by application ID, represented by the hex
13903      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
13904      * <p>Requires Permission:
13905      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
13906      *
13907      * @param appType the uicc app type.
13908      * @return Application ID for specified app type or {@code null} if no uicc or error.
13909      *
13910      * @throws UnsupportedOperationException If the device does not have
13911      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
13912      * @hide
13913      */
13914     @Nullable
13915     @SystemApi
13916     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13917     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getAidForAppType(@iccAppType int appType)13918     public String getAidForAppType(@UiccAppType int appType) {
13919         return getAidForAppType(getSubId(), appType);
13920     }
13921 
13922     /**
13923      * same as {@link #getAidForAppType(int)}
13924      * @hide
13925      */
getAidForAppType(int subId, int appType)13926     public String getAidForAppType(int subId, int appType) {
13927         try {
13928             ITelephony service = getITelephony();
13929             if (service != null) {
13930                 return service.getAidForAppType(subId, appType);
13931             }
13932         } catch (RemoteException e) {
13933             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
13934         }
13935         return null;
13936     }
13937 
13938     /**
13939      * Return the Electronic Serial Number.
13940      *
13941      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13942      *
13943      * @return ESN or null if error.
13944      * @hide
13945      */
getEsn()13946     public String getEsn() {
13947         return getEsn(getSubId());
13948     }
13949 
13950     /**
13951      * Return the Electronic Serial Number.
13952      *
13953      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13954      *
13955      * @param subId the subscription ID that this request applies to.
13956      * @return ESN or null if error.
13957      * @hide
13958      */
getEsn(int subId)13959     public String getEsn(int subId) {
13960         try {
13961             ITelephony service = getITelephony();
13962             if (service != null) {
13963                 return service.getEsn(subId);
13964             }
13965         } catch (RemoteException e) {
13966             Log.e(TAG, "Error calling ITelephony#getEsn", e);
13967         }
13968         return null;
13969     }
13970 
13971     /**
13972      * Return the Preferred Roaming List Version
13973      *
13974      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13975      *
13976      * @return PRLVersion or null if error.
13977      *
13978      * @throws UnsupportedOperationException If the device does not have
13979      *          {@link PackageManager#FEATURE_TELEPHONY_CDMA}.
13980      * @deprecated Legacy CDMA is unsupported.
13981      * @hide
13982      */
13983     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
13984     @Deprecated
13985     @SystemApi
13986     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CDMA)
getCdmaPrlVersion()13987     public String getCdmaPrlVersion() {
13988         if (Flags.cleanupCdma()) return null;
13989         return getCdmaPrlVersion(getSubId());
13990     }
13991 
13992     /**
13993      * Return the Preferred Roaming List Version
13994      *
13995      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
13996      *
13997      * @param subId the subscription ID that this request applies to.
13998      * @return PRLVersion or null if error.
13999      * @deprecated Legacy CDMA is unsupported.
14000      * @hide
14001      */
14002     @Deprecated
getCdmaPrlVersion(int subId)14003     public String getCdmaPrlVersion(int subId) {
14004         if (Flags.cleanupCdma()) return null;
14005         try {
14006             ITelephony service = getITelephony();
14007             if (service != null) {
14008                 return service.getCdmaPrlVersion(subId);
14009             }
14010         } catch (RemoteException e) {
14011             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
14012         }
14013         return null;
14014     }
14015 
14016     /**
14017      * Get snapshot of Telephony histograms
14018      * @return List of Telephony histograms
14019      * Requires Permission:
14020      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14021      * Or the calling app has carrier privileges.
14022      * @hide
14023      */
14024     @SystemApi
14025     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()14026     public List<TelephonyHistogram> getTelephonyHistograms() {
14027         try {
14028             ITelephony service = getITelephony();
14029             if (service != null) {
14030                 return service.getTelephonyHistograms();
14031             }
14032         } catch (RemoteException e) {
14033             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
14034         }
14035         return null;
14036     }
14037 
14038     /**
14039      * Set the allowed carrier list for slotIndex
14040      * Require system privileges. In the future we may add this to carrier APIs.
14041      *
14042      * <p>Requires Permission:
14043      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
14044      *
14045      * <p>This method works only on devices with {@link
14046      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
14047      *
14048      * @deprecated use setCarrierRestrictionRules instead
14049      *
14050      * @return The number of carriers set successfully. Should be length of
14051      * carrierList on success; -1 if carrierList null or on error.
14052      *
14053      * @throws UnsupportedOperationException If the device does not have
14054      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
14055      * @hide
14056      */
14057     @SystemApi
14058     @Deprecated
14059     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14060     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)14061     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
14062         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
14063             return -1;
14064         }
14065         // Execute the method setCarrierRestrictionRules with an empty excluded list.
14066         // If the allowed list is empty, it means that all carriers are allowed (default allowed),
14067         // otherwise it means that only specified carriers are allowed (default not allowed).
14068         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
14069                 .setAllowedCarriers(carriers)
14070                 .setDefaultCarrierRestriction(
14071                     carriers.isEmpty()
14072                         ? CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_ALLOWED
14073                         : CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
14074                 .build();
14075 
14076         int result = setCarrierRestrictionRules(carrierRestrictionRules);
14077 
14078         // Convert result into int, as required by this method.
14079         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
14080             return carriers.size();
14081         } else {
14082             return -1;
14083         }
14084     }
14085 
14086     /**
14087      * The carrier restrictions were successfully set.
14088      * @hide
14089      */
14090     @SystemApi
14091     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
14092 
14093     /**
14094      * The carrier restrictions were not set due to lack of support in the modem. This can happen
14095      * if the modem does not support setting the carrier restrictions or if the configuration
14096      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
14097      * @hide
14098      */
14099     @SystemApi
14100     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
14101 
14102     /**
14103      * The setting of carrier restrictions failed.
14104      * @hide
14105      */
14106     @SystemApi
14107     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
14108 
14109     /** @hide */
14110     @Retention(RetentionPolicy.SOURCE)
14111     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
14112             value = {
14113                     SET_CARRIER_RESTRICTION_SUCCESS,
14114                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
14115                     SET_CARRIER_RESTRICTION_ERROR
14116             })
14117     public @interface SetCarrierRestrictionResult {}
14118 
14119     /**
14120      * The SIM power state was successfully set.
14121      * @hide
14122      */
14123     @SystemApi
14124     public static final int SET_SIM_POWER_STATE_SUCCESS = 0;
14125 
14126     /**
14127      * The SIM is already in the requested power state.
14128      * @hide
14129      */
14130     @SystemApi
14131     public static final int SET_SIM_POWER_STATE_ALREADY_IN_STATE = 1;
14132 
14133     /**
14134      * Failed to connect to the modem to make the power state request. This may happen if the
14135      * modem has an error. The user may want to make the request again later.
14136      * @hide
14137      */
14138     @SystemApi
14139     public static final int SET_SIM_POWER_STATE_MODEM_ERROR = 2;
14140 
14141     /**
14142      * Failed to connect to the SIM to make the power state request. This may happen if the
14143      * SIM has been removed. The user may want to make the request again later.
14144      * @hide
14145      */
14146     @SystemApi
14147     public static final int SET_SIM_POWER_STATE_SIM_ERROR = 3;
14148 
14149     /**
14150      * The modem version does not support synchronous power.
14151      * @hide
14152      */
14153     @SystemApi
14154     public static final int SET_SIM_POWER_STATE_NOT_SUPPORTED = 4;
14155 
14156     /** @hide */
14157     @Retention(RetentionPolicy.SOURCE)
14158     @IntDef(prefix = {"SET_SIM_POWER_STATE_"},
14159             value = {
14160                     SET_SIM_POWER_STATE_SUCCESS,
14161                     SET_SIM_POWER_STATE_ALREADY_IN_STATE,
14162                     SET_SIM_POWER_STATE_MODEM_ERROR,
14163                     SET_SIM_POWER_STATE_SIM_ERROR,
14164                     SET_SIM_POWER_STATE_NOT_SUPPORTED
14165             })
14166     public @interface SetSimPowerStateResult {}
14167 
14168     /**
14169      * Set the allowed carrier list and the excluded carrier list indicating the priority between
14170      * the two lists.
14171      * Requires system privileges.
14172      *
14173      * <p>Requires Permission:
14174      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
14175      *
14176      * <p>This method works only on devices with {@link
14177      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
14178      *
14179      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
14180      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
14181      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
14182      *
14183      * @throws UnsupportedOperationException If the device does not have
14184      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
14185      * @hide
14186      */
14187     @SystemApi
14188     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14189     @SetCarrierRestrictionResult
14190     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)14191     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
14192         try {
14193             ITelephony service = getITelephony();
14194             if (service != null) {
14195                 return service.setAllowedCarriers(rules);
14196             }
14197         } catch (RemoteException e) {
14198             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
14199         } catch (NullPointerException e) {
14200             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
14201         }
14202         return SET_CARRIER_RESTRICTION_ERROR;
14203     }
14204 
14205     /**
14206      * Get the allowed carrier list for slotIndex.
14207      * Requires system privileges.
14208      *
14209      * <p>This method returns valid data on devices with {@link
14210      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
14211      *
14212      * @deprecated Apps should use {@link #getCarrierRestrictionRules} to retrieve the list of
14213      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
14214      * list is empty. This API could return an empty list, even if some restrictions are present.
14215      *
14216      * @return List of {@link android.service.carrier.CarrierIdentifier}; empty list
14217      * means all carriers are allowed.
14218      *
14219      * @throws UnsupportedOperationException If the device does not have
14220      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
14221      * @hide
14222      */
14223     @Deprecated
14224     @SystemApi
14225     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14226     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
getAllowedCarriers(int slotIndex)14227     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
14228         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
14229             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
14230             if (carrierRestrictionRule != null) {
14231                 return carrierRestrictionRule.getAllowedCarriers();
14232             }
14233         }
14234         return new ArrayList<CarrierIdentifier>(0);
14235     }
14236 
14237     /**
14238      * Get the allowed carrier list and the excluded carrier list indicating the priority between
14239      * the two lists.
14240      * Require system privileges. In the future we may add this to carrier APIs.
14241      *
14242      * <p>This method returns valid data on devices with {@link
14243      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
14244      *
14245      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
14246      * excluded carrier list with the priority between the two lists. Returns {@code null}
14247      * in case of error.
14248      *
14249      * @throws UnsupportedOperationException If the device does not have
14250      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
14251      * @hide
14252      */
14253     @SystemApi
14254     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14255     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
14256     @Nullable
getCarrierRestrictionRules()14257     public CarrierRestrictionRules getCarrierRestrictionRules() {
14258         try {
14259             ITelephony service = getITelephony();
14260             if (service != null) {
14261                 return service.getAllowedCarriers();
14262             }
14263         } catch (RemoteException e) {
14264             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
14265         } catch (NullPointerException e) {
14266             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
14267         }
14268         return null;
14269     }
14270 
14271     /**
14272      * Carrier restriction status value is unknown, in case modem did not provide any
14273      * information about carrier restriction status.
14274      */
14275     public static final int CARRIER_RESTRICTION_STATUS_UNKNOWN = 0;
14276 
14277     /** The device is not restricted to a carrier */
14278     public static final int CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED = 1;
14279 
14280     /** The device is restricted to a carrier. */
14281     public static final int CARRIER_RESTRICTION_STATUS_RESTRICTED = 2;
14282 
14283     /** The device is restricted to the carrier of the calling application. */
14284     public static final int CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER = 3;
14285 
14286     /** @hide */
14287     @IntDef(prefix = {"CARRIER_RESTRICTION_STATUS_"}, value = {
14288             CARRIER_RESTRICTION_STATUS_UNKNOWN,
14289             CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED,
14290             CARRIER_RESTRICTION_STATUS_RESTRICTED,
14291             CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER
14292     })
14293     @Retention(RetentionPolicy.SOURCE)
14294     public @interface CarrierRestrictionStatus {
14295     }
14296 
14297     /**
14298      * Get the carrier restriction status of the device.
14299      * <p>To fetch the carrier restriction status of the device the calling application needs to be
14300      * allowlisted to Android at <a href="https://android.googlesource.com/platform/packages/services/Telephony/+/master/assets/CarrierRestrictionOperatorDetails.json">here</a>.
14301      * The calling application also needs the READ_PHONE_STATE permission.
14302      * The return value of the API is as follows.
14303      * <ul>
14304      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_RESTRICTED_TO_CALLER} if the caller
14305      *      and the device locked by the network are same</li>
14306      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_RESTRICTED} if the caller and the
14307      *      device locked by the network are different</li>
14308      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_NOT_RESTRICTED} if the device is
14309      *      not locked</li>
14310      *      <li>return {@link #CARRIER_RESTRICTION_STATUS_UNKNOWN} if the device locking
14311      *      state is unavailable or radio does not supports the feature</li>
14312      * </ul>
14313      *
14314      * @param executor The executor on which the result listener will be called.
14315      * @param resultListener {@link Consumer} that will be called with the carrier restriction
14316      *                       status result fetched from the radio
14317      * @throws SecurityException if the caller does not have the required permission/privileges or
14318      *                           if the caller is not pre-registered.
14319      * @throws UnsupportedOperationException If the device does not have
14320      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
14321      */
14322     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
14323     @RequiresPermission(anyOf = {
14324             android.Manifest.permission.READ_BASIC_PHONE_STATE,
14325             android.Manifest.permission.READ_PHONE_STATE
14326     })
getCarrierRestrictionStatus(@onNull Executor executor, @NonNull @CarrierRestrictionStatus Consumer<Integer> resultListener)14327     public void getCarrierRestrictionStatus(@NonNull Executor executor,
14328             @NonNull @CarrierRestrictionStatus
14329                     Consumer<Integer> resultListener) {
14330         Objects.requireNonNull(executor);
14331         Objects.requireNonNull(resultListener);
14332 
14333         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
14334             @Override
14335             public void accept(@CarrierRestrictionStatus int result) {
14336                 executor.execute(() -> Binder.withCleanCallingIdentity(
14337                         () -> resultListener.accept(result)));
14338             }
14339         };
14340         try {
14341             ITelephony service = getITelephony();
14342             if (service != null) {
14343                 service.getCarrierRestrictionStatus(internalCallback, getOpPackageName());
14344             }
14345         } catch (RemoteException ex) {
14346             Rlog.e(TAG, "getCarrierRestrictionStatus: RemoteException = " + ex);
14347             throw ex.rethrowAsRuntimeException();
14348         }
14349     }
14350 
14351     /**
14352      * Test API to verify carrier restriction status allow list i.e.
14353      * packages/services/Telephony/assets/CarrierRestrictionOperatorDetails.json.
14354      *
14355      * @param pkgName : packaga name of the entry to verify
14356      * @param carrierId : carrier Id of the entry
14357      * @return {@code List<String>} : list of registered shaIds
14358      * @hide
14359      */
14360     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getShaIdFromAllowList(String pkgName, int carrierId)14361     public List<String> getShaIdFromAllowList(String pkgName, int carrierId) {
14362         try {
14363             ITelephony service = getITelephony();
14364             if (service != null) {
14365                 return service.getShaIdFromAllowList(pkgName, carrierId);
14366             }
14367         } catch (RemoteException ex) {
14368             Rlog.e(TAG, "getShaIdFromAllowList: RemoteException = " + ex);
14369             throw ex.rethrowAsRuntimeException();
14370         }
14371         return Collections.EMPTY_LIST;
14372     }
14373 
14374     /**
14375      * Used to enable or disable carrier data by the system based on carrier signalling or
14376      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
14377      * user settings, carrier data on/off won't affect user settings but will bypass the
14378      * settings and turns off data internally if set to {@code false}.
14379      *
14380      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14381      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14382      *
14383      * <p>Requires Permission:
14384      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14385      *
14386      * @param enabled control enable or disable carrier data.
14387      * @see #resetAllCarrierActions()
14388      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
14389      * reason {@link #DATA_ENABLED_REASON_CARRIER}} instead.
14390      *
14391      * @throws UnsupportedOperationException If the device does not have
14392      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14393      * @hide
14394      */
14395     @Deprecated
14396     @SystemApi
14397     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14398     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setCarrierDataEnabled(boolean enabled)14399     public void setCarrierDataEnabled(boolean enabled) {
14400         try {
14401             setDataEnabledForReason(DATA_ENABLED_REASON_CARRIER, enabled);
14402         } catch (RuntimeException e) {
14403             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
14404         }
14405     }
14406 
14407     /**
14408      * Carrier action to enable or disable the radio.
14409      *
14410      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14411      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14412      *
14413      * <p>Requires Permission:
14414      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14415      *
14416      * @param enabled control enable or disable radio.
14417      * @see #resetAllCarrierActions()
14418      *
14419      * @deprecated - use the APIs {@link requestRadioPowerOffForReason} and
14420      * {@link clearRadioPowerOffForReason}.
14421      *
14422      * @throws UnsupportedOperationException If the device does not have
14423      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14424      * @hide
14425      */
14426     @Deprecated
14427     @SystemApi
14428     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14429     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setRadioEnabled(boolean enabled)14430     public void setRadioEnabled(boolean enabled) {
14431         if (enabled) {
14432             clearRadioPowerOffForReason(RADIO_POWER_REASON_CARRIER);
14433         } else {
14434             requestRadioPowerOffForReason(RADIO_POWER_REASON_CARRIER);
14435         }
14436     }
14437 
14438     /**
14439      * No error. Operation succeeded.
14440      * @hide
14441      */
14442     public static final int ENABLE_VONR_SUCCESS = 0;
14443 
14444     /**
14445      * Radio is not available.
14446      * @hide
14447      */
14448     public static final int ENABLE_VONR_RADIO_NOT_AVAILABLE = 2;
14449 
14450     /**
14451      * Internal Radio error.
14452      * @hide
14453      */
14454     public static final int ENABLE_VONR_RADIO_ERROR = 3;
14455 
14456     /**
14457      * Voice over NR enable/disable request is received when system is in invalid state.
14458      * @hide
14459      */
14460     public static final int ENABLE_VONR_RADIO_INVALID_STATE = 4;
14461 
14462     /**
14463      * Voice over NR enable/disable request is not supported.
14464      * @hide
14465      */
14466     public static final int ENABLE_VONR_REQUEST_NOT_SUPPORTED = 5;
14467 
14468     /** @hide */
14469     @Retention(RetentionPolicy.SOURCE)
14470     @IntDef(prefix = {"EnableVoNrResult"}, value = {
14471             ENABLE_VONR_SUCCESS,
14472             ENABLE_VONR_RADIO_NOT_AVAILABLE,
14473             ENABLE_VONR_RADIO_ERROR,
14474             ENABLE_VONR_RADIO_INVALID_STATE,
14475             ENABLE_VONR_REQUEST_NOT_SUPPORTED})
14476     public @interface EnableVoNrResult {}
14477 
14478     /**
14479      * Enable or disable Voice over NR (VoNR)
14480      *
14481      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14482      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14483      *
14484      * <p>Requires Permission:
14485      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14486      *
14487      * @param enabled  enable or disable VoNR.
14488      * @throws IllegalStateException if the Telephony process is not currently available.
14489      * @hide
14490      */
14491     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoNrEnabled(boolean enabled)14492     public @EnableVoNrResult int setVoNrEnabled(boolean enabled) {
14493         try {
14494             ITelephony service = getITelephony();
14495             if (service != null) {
14496                 return service.setVoNrEnabled(
14497                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
14498             } else {
14499                 throw new IllegalStateException("telephony service is null.");
14500             }
14501         } catch (RemoteException e) {
14502             Log.e(TAG, "Error calling ITelephony#setVoNrEnabled", e);
14503         }
14504 
14505         return ENABLE_VONR_RADIO_INVALID_STATE;
14506     }
14507 
14508     /**
14509      * Is Voice over NR (VoNR) enabled.
14510      * @return true if Voice over NR (VoNR) is enabled else false. Enabled state does not mean
14511      *  voice call over NR is active or voice ove NR is available. It means the device is allowed to
14512      *  register IMS over NR.
14513      * @throws IllegalStateException if the Telephony process is not currently available.
14514      * @hide
14515      */
14516     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isVoNrEnabled()14517     public boolean isVoNrEnabled() {
14518         try {
14519             ITelephony telephony = getITelephony();
14520             if (telephony != null) {
14521                 return telephony.isVoNrEnabled(getSubId());
14522             } else {
14523                 throw new IllegalStateException("telephony service is null.");
14524             }
14525         } catch (RemoteException ex) {
14526             Rlog.e(TAG, "isVoNrEnabled RemoteException", ex);
14527             ex.rethrowFromSystemServer();
14528         }
14529         return false;
14530     }
14531 
14532     /**
14533      * Carrier action to start or stop reporting default network available events.
14534      *
14535      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14536      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14537      *
14538      * <p>Requires Permission:
14539      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14540      *
14541      * @param report control start/stop reporting network status.
14542      * @see #resetAllCarrierActions()
14543      *
14544      * @throws UnsupportedOperationException If the device does not have
14545      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14546      * @hide
14547      */
14548     @SystemApi
14549     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14550     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
reportDefaultNetworkStatus(boolean report)14551     public void reportDefaultNetworkStatus(boolean report) {
14552         try {
14553             ITelephony service = getITelephony();
14554             if (service != null) {
14555                 service.carrierActionReportDefaultNetworkStatus(
14556                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
14557             }
14558         } catch (RemoteException e) {
14559             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
14560         }
14561     }
14562 
14563     /**
14564      * Reset all carrier actions previously set by {@link #setRadioEnabled},
14565      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
14566      *
14567      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14568      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14569      *
14570      * <p>Requires Permission:
14571      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
14572      * @throws UnsupportedOperationException If the device does not have
14573      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
14574      * @hide
14575      */
14576     @SystemApi
14577     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14578     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
resetAllCarrierActions()14579     public void resetAllCarrierActions() {
14580         try {
14581             ITelephony service = getITelephony();
14582             if (service != null) {
14583                 service.carrierActionResetAll(
14584                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
14585             }
14586         } catch (RemoteException e) {
14587             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
14588         }
14589     }
14590 
14591     /**
14592      * Policy control of data connection. Usually used when data limit is passed.
14593      * @param enabled True if enabling the data, otherwise disabling.
14594      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
14595      * reason {@link #DATA_ENABLED_REASON_POLICY}} instead.
14596      * @hide
14597      */
14598     @Deprecated
14599     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setPolicyDataEnabled(boolean enabled)14600     public void setPolicyDataEnabled(boolean enabled) {
14601         try {
14602             setDataEnabledForReason(DATA_ENABLED_REASON_POLICY, enabled);
14603         } catch (RuntimeException e) {
14604             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
14605         }
14606     }
14607 
14608     /** @hide */
14609     @IntDef({
14610             DATA_ENABLED_REASON_USER,
14611             DATA_ENABLED_REASON_POLICY,
14612             DATA_ENABLED_REASON_CARRIER,
14613             DATA_ENABLED_REASON_THERMAL
14614     })
14615     @Retention(RetentionPolicy.SOURCE)
14616     public @interface DataEnabledReason{}
14617 
14618     /** @hide */
14619     @IntDef({
14620             DATA_ENABLED_REASON_UNKNOWN,
14621             DATA_ENABLED_REASON_USER,
14622             DATA_ENABLED_REASON_POLICY,
14623             DATA_ENABLED_REASON_CARRIER,
14624             DATA_ENABLED_REASON_THERMAL,
14625             DATA_ENABLED_REASON_OVERRIDE
14626     })
14627     @Retention(RetentionPolicy.SOURCE)
14628     public @interface DataEnabledChangedReason{}
14629 
14630     /**
14631      * To indicate that data was enabled or disabled due to an unknown reason.
14632      * Note that this is not a valid reason for {@link #setDataEnabledForReason(int, boolean)} and
14633      * is only used to indicate that data enabled was changed.
14634      */
14635     public static final int DATA_ENABLED_REASON_UNKNOWN = -1;
14636 
14637     /**
14638      * To indicate that user enabled or disabled data.
14639      */
14640     public static final int DATA_ENABLED_REASON_USER = 0;
14641 
14642     /**
14643      * To indicate that data control due to policy. Usually used when data limit is passed.
14644      * Policy data on/off won't affect user settings but will bypass the
14645      * settings and turns off data internally if set to {@code false}.
14646      */
14647     public static final int DATA_ENABLED_REASON_POLICY = 1;
14648 
14649     /**
14650      * To indicate enable or disable carrier data by the system based on carrier signalling or
14651      * carrier privileged apps. Carrier data on/off won't affect user settings but will bypass the
14652      * settings and turns off data internally if set to {@code false}.
14653      */
14654     public static final int DATA_ENABLED_REASON_CARRIER = 2;
14655 
14656     /**
14657      * To indicate enable or disable data by thermal service.
14658      * Thermal data on/off won't affect user settings but will bypass the
14659      * settings and turns off data internally if set to {@code false}.
14660      */
14661     public static final int DATA_ENABLED_REASON_THERMAL = 3;
14662 
14663     /**
14664      * To indicate data was enabled or disabled due to mobile data policy overrides.
14665      * Note that this is not a valid reason for {@link #setDataEnabledForReason(int, boolean)} and
14666      * is only used to indicate that data enabled was changed due to an override.
14667      */
14668     public static final int DATA_ENABLED_REASON_OVERRIDE = 4;
14669 
14670     /**
14671      * Control of data connection and provide the reason triggering the data connection control.
14672      * This can be called for following reasons
14673      * <ol>
14674      * <li>data limit is passed {@link #DATA_ENABLED_REASON_POLICY}
14675      * <li>data disabled by carrier {@link #DATA_ENABLED_REASON_CARRIER}
14676      * <li>data disabled by user {@link #DATA_ENABLED_REASON_USER}
14677      * <li>data disabled due to thermal {@link #DATA_ENABLED_REASON_THERMAL}
14678      * </ol>
14679      * If any of the reason is off, then it will result in
14680      * bypassing user preference and result in data to be turned off.
14681      *
14682      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
14683      *      to the given subId. Otherwise, applies to
14684      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14685      *
14686      *
14687      * @param reason the reason the data enable change is taking place
14688      * @param enabled True if enabling the data, otherwise disabling.
14689      *
14690      * <p>Requires Permission:
14691      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) if the reason is
14692      * {@link #DATA_ENABLED_REASON_USER} or {@link #DATA_ENABLED_REASON_CARRIER} or the call app
14693      * has {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} irrespective of
14694      * the reason.
14695      * @throws IllegalStateException if the Telephony process is not currently available.
14696      * @throws UnsupportedOperationException If the device does not have
14697      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14698      */
14699     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
14700     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setDataEnabledForReason(@ataEnabledReason int reason, boolean enabled)14701     public void setDataEnabledForReason(@DataEnabledReason int reason, boolean enabled) {
14702         setDataEnabledForReason(getSubId(), reason, enabled);
14703     }
14704 
setDataEnabledForReason(int subId, @DataEnabledReason int reason, boolean enabled)14705     private void setDataEnabledForReason(int subId, @DataEnabledReason int reason,
14706             boolean enabled) {
14707         try {
14708             ITelephony service = getITelephony();
14709             if (service != null) {
14710                 service.setDataEnabledForReason(subId, reason, enabled, getOpPackageName());
14711             } else {
14712                 throw new IllegalStateException("telephony service is null.");
14713             }
14714         } catch (RemoteException ex) {
14715             Log.e(TAG, "Telephony#setDataEnabledForReason RemoteException", ex);
14716             ex.rethrowFromSystemServer();
14717         }
14718     }
14719 
14720     /**
14721      * Return whether data is enabled for certain reason .
14722      *
14723      * If {@link #isDataEnabledForReason} returns false, it means in data enablement for a
14724      * specific reason is turned off. If any of the reason is off, then it will result in
14725      * bypassing user preference and result in data to be turned off. Call
14726      * {@link #isDataConnectionAllowed} in order to know whether
14727      * data connection is allowed on the device.
14728      *
14729      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
14730      *      to the given subId. Otherwise, applies to
14731      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
14732      * @param reason the reason the data enable change is taking place
14733      * @return whether data is enabled for a reason.
14734      * <p>Requires Permission:
14735      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) or
14736      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or
14737      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE} or
14738      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}
14739      * {@link android.Manifest.permission#READ_BASIC_PHONE_STATE}
14740      * @throws IllegalStateException if the Telephony process is not currently available.
14741      * @throws UnsupportedOperationException If the device does not have
14742      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14743      */
14744     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
14745             android.Manifest.permission.READ_PHONE_STATE,
14746             android.Manifest.permission.MODIFY_PHONE_STATE,
14747             android.Manifest.permission.READ_BASIC_PHONE_STATE
14748     })
14749     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabledForReason(@ataEnabledReason int reason)14750     public boolean isDataEnabledForReason(@DataEnabledReason int reason) {
14751         return isDataEnabledForReason(getSubId(), reason);
14752     }
14753 
isDataEnabledForReason(int subId, @DataEnabledReason int reason)14754     private boolean isDataEnabledForReason(int subId, @DataEnabledReason int reason) {
14755         try {
14756             ITelephony service = getITelephony();
14757             if (service != null) {
14758                 return service.isDataEnabledForReason(subId, reason);
14759             } else {
14760                 throw new IllegalStateException("telephony service is null.");
14761             }
14762         } catch (RemoteException ex) {
14763             Log.e(TAG, "Telephony#isDataEnabledForReason RemoteException", ex);
14764             ex.rethrowFromSystemServer();
14765         }
14766         return false;
14767     }
14768 
14769     /**
14770      * Get Client request stats which will contain statistical information
14771      * on each request made by client.
14772      * Callers require either READ_PRIVILEGED_PHONE_STATE or
14773      * READ_PHONE_STATE to retrieve the information.
14774      * @param subId sub id
14775      * @return List of Client Request Stats
14776      * @hide
14777      */
getClientRequestStats(int subId)14778     public List<ClientRequestStats> getClientRequestStats(int subId) {
14779         try {
14780             ITelephony service = getITelephony();
14781             if (service != null) {
14782                 return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
14783                         subId);
14784             }
14785         } catch (RemoteException e) {
14786             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
14787         }
14788 
14789         return null;
14790     }
14791 
14792     /**
14793      * Checks if phone is in emergency callback mode.
14794      *
14795      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14796      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
14797      *
14798      * @return true if phone is in emergency callback mode.
14799      *
14800      * @throws UnsupportedOperationException If the device does not have
14801      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
14802      * @hide
14803      */
14804     @SystemApi
14805     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14806     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getEmergencyCallbackMode()14807     public boolean getEmergencyCallbackMode() {
14808         return getEmergencyCallbackMode(getSubId());
14809     }
14810 
14811     /**
14812      * Check if phone is in emergency callback mode
14813      * @return true if phone is in emergency callback mode
14814      * @param subId the subscription ID that this action applies to.
14815      * @hide
14816      */
getEmergencyCallbackMode(int subId)14817     public boolean getEmergencyCallbackMode(int subId) {
14818         try {
14819             ITelephony telephony = getITelephony();
14820             if (telephony == null) {
14821                 return false;
14822             }
14823             return telephony.getEmergencyCallbackMode(subId);
14824         } catch (RemoteException e) {
14825             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
14826         }
14827         return false;
14828     }
14829 
14830     /**
14831      * Checks if manual network selection is allowed.
14832      *
14833      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
14834      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
14835      * (see {@link #hasCarrierPrivileges})
14836      *
14837      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
14838      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
14839      *
14840      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
14841      *
14842      * @throws UnsupportedOperationException If the device does not have
14843      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14844      */
14845     @SuppressAutoDoc // No support carrier privileges (b/72967236).
14846     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRECISE_PHONE_STATE,
14847             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
14848     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isManualNetworkSelectionAllowed()14849     public boolean isManualNetworkSelectionAllowed() {
14850         try {
14851             ITelephony telephony = getITelephony();
14852             if (telephony != null) {
14853                 return telephony.isManualNetworkSelectionAllowed(getSubId());
14854             }
14855         } catch (RemoteException e) {
14856             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
14857         }
14858         return true;
14859     }
14860 
14861     /**
14862      * Get the most recently available signal strength information.
14863      *
14864      * Get the most recent SignalStrength information reported by the modem. Due
14865      * to power saving this information may not always be current.
14866      * @return the most recent cached signal strength info from the modem
14867      *
14868      * @throws UnsupportedOperationException If the device does not have
14869      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
14870      */
14871     @Nullable
14872     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSignalStrength()14873     public SignalStrength getSignalStrength() {
14874         try {
14875             ITelephony service = getITelephony();
14876             if (service != null) {
14877                 return service.getSignalStrength(getSubId());
14878             }
14879         } catch (RemoteException e) {
14880             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
14881         }
14882         return null;
14883     }
14884 
14885     /**
14886      * Checks whether cellular data connection is allowed in the device.
14887      *
14888      * <p>Whether cellular data connection is allowed considers all factors below:
14889      * <UL>
14890      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
14891      *   <LI>Carrier allows data to be on.</LI>
14892      *   <LI>Network policy.</LI>
14893      *   <LI>And possibly others.</LI>
14894      * </UL>
14895      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
14896      *
14897      * @throws UnsupportedOperationException If the device does not have
14898      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
14899      */
14900     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
14901             android.Manifest.permission.READ_PHONE_STATE,
14902             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
14903             android.Manifest.permission.READ_BASIC_PHONE_STATE})
14904     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataConnectionAllowed()14905     public boolean isDataConnectionAllowed() {
14906         boolean retVal = false;
14907         try {
14908             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
14909             ITelephony telephony = getITelephony();
14910             if (telephony != null)
14911                 retVal = telephony.isDataEnabled(subId);
14912         } catch (RemoteException e) {
14913             Log.e(TAG, "Error isDataConnectionAllowed", e);
14914         }
14915         return retVal;
14916     }
14917 
14918     /**
14919      * @return true if the current device is "data capable" over a radio on the device.
14920      * <p>
14921      * "Data capable" means that this device supports packet-switched
14922      * data connections over the telephony network.
14923      * <p>
14924      */
isDataCapable()14925     public boolean isDataCapable() {
14926         return hasCapability(PackageManager.FEATURE_TELEPHONY_DATA,
14927                 com.android.internal.R.bool.config_mobile_data_capable);
14928     }
14929 
14930     /**
14931      * The indication for signal strength update.
14932      * @hide
14933      */
14934     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
14935 
14936     /**
14937      * The indication for full network state update.
14938      * @hide
14939      */
14940     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
14941 
14942     /**
14943      * The indication for data call dormancy changed update.
14944      * @hide
14945      */
14946     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
14947 
14948     /**
14949      * The indication for link capacity estimate update.
14950      * @hide
14951      */
14952     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
14953 
14954     /**
14955      * The indication for physical channel config update.
14956      * @hide
14957      */
14958     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
14959 
14960     /**
14961      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
14962      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
14963      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
14964      *
14965      * <p>Requires Permission:
14966      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14967      *
14968      *
14969      * @deprecated
14970      * @hide
14971      */
14972     @Deprecated
14973     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)14974     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
14975             String gid2, String plmn, String spn) {
14976         try {
14977             ITelephony telephony = getITelephony();
14978             if (telephony != null) {
14979                 telephony.setCarrierTestOverride(
14980                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
14981                         null, null);
14982             }
14983         } catch (RemoteException ex) {
14984             // This could happen if binder process crashes.
14985         }
14986     }
14987 
14988     /**
14989      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
14990      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
14991      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
14992      * a test SIM with a call box.
14993      *
14994      * <p>Requires Permission:
14995      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
14996      *
14997      * @hide
14998      */
14999     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)15000     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
15001                                        String gid2, String plmn, String spn,
15002                                        String carrierPriviledgeRules, String apn) {
15003         try {
15004             ITelephony telephony = getITelephony();
15005             if (telephony != null) {
15006                 telephony.setCarrierTestOverride(
15007                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
15008                         carrierPriviledgeRules, apn);
15009             }
15010         } catch (RemoteException ex) {
15011             // This could happen if binder process crashes.
15012         }
15013     }
15014 
15015     /**
15016      * A test API to return installed carrier id list version
15017      *
15018      * <p>Requires Permission:
15019      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
15020      *
15021      * @hide
15022      */
15023     @UnsupportedAppUsage
15024     @TestApi
getCarrierIdListVersion()15025     public int getCarrierIdListVersion() {
15026         try {
15027             ITelephony telephony = getITelephony();
15028             if (telephony != null) {
15029                 return telephony.getCarrierIdListVersion(getSubId());
15030             }
15031         } catch (RemoteException ex) {
15032             // This could happen if binder process crashes.
15033         }
15034         return UNKNOWN_CARRIER_ID_LIST_VERSION;
15035     }
15036 
15037     /**
15038      * How many modems can have simultaneous data connections.
15039      * @hide
15040      */
15041     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()15042     public int getNumberOfModemsWithSimultaneousDataConnections() {
15043         try {
15044             ITelephony telephony = getITelephony();
15045             if (telephony != null) {
15046                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
15047                         getSubId(), getOpPackageName(), getAttributionTag());
15048             }
15049         } catch (RemoteException ex) {
15050             // This could happen if binder process crashes.
15051         }
15052         return 0;
15053     }
15054 
15055     /**
15056      * Enable or disable OpportunisticNetworkService.
15057      *
15058      * This method should be called to enable or disable
15059      * OpportunisticNetwork service on the device.
15060      *
15061      * <p>
15062      * Requires Permission:
15063      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
15064      *
15065      * @param enable enable(True) or disable(False)
15066      * @return returns true if successfully set.
15067      *
15068      * @throws UnsupportedOperationException If the device does not have
15069      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
15070      * @hide
15071      */
15072     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15073     @SystemApi
15074     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setOpportunisticNetworkState(boolean enable)15075     public boolean setOpportunisticNetworkState(boolean enable) {
15076         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15077         boolean ret = false;
15078         try {
15079             IOns iOpportunisticNetworkService = getIOns();
15080             if (iOpportunisticNetworkService != null) {
15081                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
15082             }
15083         } catch (RemoteException ex) {
15084             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
15085         }
15086 
15087         return ret;
15088     }
15089 
15090     /**
15091      * is OpportunisticNetworkService enabled
15092      *
15093      * This method should be called to determine if the OpportunisticNetworkService is
15094      * enabled
15095      *
15096      * <p>
15097      * Requires Permission:
15098      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
15099      *
15100      * @throws UnsupportedOperationException If the device does not have
15101      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
15102      * @hide
15103      */
15104     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15105     @SystemApi
15106     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isOpportunisticNetworkEnabled()15107     public boolean isOpportunisticNetworkEnabled() {
15108         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15109         boolean isEnabled = false;
15110 
15111         try {
15112             IOns iOpportunisticNetworkService = getIOns();
15113             if (iOpportunisticNetworkService != null) {
15114                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
15115             }
15116         } catch (RemoteException ex) {
15117             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
15118         }
15119 
15120         return isEnabled;
15121     }
15122 
15123     /** @hide */
15124     @Retention(RetentionPolicy.SOURCE)
15125     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
15126             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
15127                     NETWORK_TYPE_BITMASK_GSM,
15128                     NETWORK_TYPE_BITMASK_GPRS,
15129                     NETWORK_TYPE_BITMASK_EDGE,
15130                     NETWORK_TYPE_BITMASK_CDMA,
15131                     NETWORK_TYPE_BITMASK_1xRTT,
15132                     NETWORK_TYPE_BITMASK_EVDO_0,
15133                     NETWORK_TYPE_BITMASK_EVDO_A,
15134                     NETWORK_TYPE_BITMASK_EVDO_B,
15135                     NETWORK_TYPE_BITMASK_EHRPD,
15136                     NETWORK_TYPE_BITMASK_HSUPA,
15137                     NETWORK_TYPE_BITMASK_HSDPA,
15138                     NETWORK_TYPE_BITMASK_HSPA,
15139                     NETWORK_TYPE_BITMASK_HSPAP,
15140                     NETWORK_TYPE_BITMASK_UMTS,
15141                     NETWORK_TYPE_BITMASK_TD_SCDMA,
15142                     NETWORK_TYPE_BITMASK_LTE,
15143                     NETWORK_TYPE_BITMASK_LTE_CA,
15144                     NETWORK_TYPE_BITMASK_NR,
15145                     NETWORK_TYPE_BITMASK_IWLAN,
15146                     NETWORK_TYPE_BITMASK_IDEN
15147             })
15148     public @interface NetworkTypeBitMask {}
15149 
15150     // 2G
15151     /**
15152      * network type bitmask unknown.
15153      */
15154     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
15155     /**
15156      * network type bitmask indicating the support of radio tech GSM.
15157      */
15158     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
15159     /**
15160      * network type bitmask indicating the support of radio tech GPRS.
15161      */
15162     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
15163     /**
15164      * network type bitmask indicating the support of radio tech EDGE.
15165      */
15166     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
15167     /**
15168      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
15169      * @deprecated Legacy CDMA is unsupported.
15170      */
15171     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
15172     @Deprecated
15173     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
15174     /**
15175      * network type bitmask indicating the support of radio tech 1xRTT.
15176      */
15177     @SuppressLint("AllUpper")
15178     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
15179     // 3G
15180     /**
15181      * network type bitmask indicating the support of radio tech EVDO 0.
15182      */
15183     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
15184     /**
15185      * network type bitmask indicating the support of radio tech EVDO A.
15186      */
15187     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
15188     /**
15189      * network type bitmask indicating the support of radio tech EVDO B.
15190      */
15191     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
15192     /**
15193      * network type bitmask indicating the support of radio tech EHRPD.
15194      * @deprecated Legacy CDMA is unsupported.
15195      */
15196     @FlaggedApi(Flags.FLAG_DEPRECATE_CDMA)
15197     @Deprecated
15198     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
15199     /**
15200      * network type bitmask indicating the support of radio tech HSUPA.
15201      */
15202     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
15203     /**
15204      * network type bitmask indicating the support of radio tech HSDPA.
15205      */
15206     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
15207     /**
15208      * network type bitmask indicating the support of radio tech HSPA.
15209      */
15210     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
15211     /**
15212      * network type bitmask indicating the support of radio tech iDen.
15213      * @hide
15214      */
15215     public static final long NETWORK_TYPE_BITMASK_IDEN = (1 << (NETWORK_TYPE_IDEN - 1));
15216     /**
15217      * network type bitmask indicating the support of radio tech HSPAP.
15218      */
15219     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
15220     /**
15221      * network type bitmask indicating the support of radio tech UMTS.
15222      */
15223     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
15224     /**
15225      * network type bitmask indicating the support of radio tech TD_SCDMA.
15226      */
15227     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
15228     // 4G
15229     /**
15230      * network type bitmask indicating the support of radio tech LTE.
15231      */
15232     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
15233     /**
15234      * NOT USED; this bitmask is exposed accidentally.
15235      * If used, will be converted to {@link #NETWORK_TYPE_BITMASK_LTE}.
15236      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
15237      *
15238      * @deprecated Please use {@link #NETWORK_TYPE_BITMASK_LTE} instead. Deprecated in Android U.
15239      */
15240     @Deprecated
15241     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
15242 
15243     /**
15244      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
15245      */
15246     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
15247 
15248     /**
15249      * network type bitmask indicating the support of radio tech IWLAN.
15250      */
15251     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
15252 
15253     /** @hide */
15254     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
15255                 | NETWORK_TYPE_BITMASK_GPRS
15256                 | NETWORK_TYPE_BITMASK_EDGE
15257                 | NETWORK_TYPE_BITMASK_CDMA
15258                 | NETWORK_TYPE_BITMASK_1xRTT;
15259 
15260     /** @hide */
15261     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
15262             | NETWORK_TYPE_BITMASK_EVDO_A
15263             | NETWORK_TYPE_BITMASK_EVDO_B
15264             | NETWORK_TYPE_BITMASK_EHRPD
15265             | NETWORK_TYPE_BITMASK_HSUPA
15266             | NETWORK_TYPE_BITMASK_HSDPA
15267             | NETWORK_TYPE_BITMASK_HSPA
15268             | NETWORK_TYPE_BITMASK_HSPAP
15269             | NETWORK_TYPE_BITMASK_UMTS
15270             | NETWORK_TYPE_BITMASK_TD_SCDMA;
15271 
15272     /** @hide */
15273     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
15274             | NETWORK_TYPE_BITMASK_LTE_CA
15275             | NETWORK_TYPE_BITMASK_IWLAN;
15276 
15277     /** @hide */
15278     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
15279 
15280     /** @hide */
15281     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
15282             | NETWORK_TYPE_BITMASK_GPRS
15283             | NETWORK_TYPE_BITMASK_EDGE
15284             | NETWORK_TYPE_BITMASK_HSUPA
15285             | NETWORK_TYPE_BITMASK_HSDPA
15286             | NETWORK_TYPE_BITMASK_HSPA
15287             | NETWORK_TYPE_BITMASK_HSPAP
15288             | NETWORK_TYPE_BITMASK_UMTS
15289             | NETWORK_TYPE_BITMASK_TD_SCDMA
15290             | NETWORK_TYPE_BITMASK_LTE
15291             | NETWORK_TYPE_BITMASK_LTE_CA
15292             | NETWORK_TYPE_BITMASK_NR;
15293 
15294     /** @hide
15295      * @deprecated Legacy CDMA is unsupported.
15296      */
15297     @Deprecated
15298     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
15299             | NETWORK_TYPE_BITMASK_1xRTT
15300             | NETWORK_TYPE_BITMASK_EVDO_0
15301             | NETWORK_TYPE_BITMASK_EVDO_A
15302             | NETWORK_TYPE_BITMASK_EVDO_B
15303             | NETWORK_TYPE_BITMASK_EHRPD;
15304 
15305     /**
15306      * @return Modem supported radio access family bitmask
15307      *
15308      * <p>Requires permission: android.Manifest.READ_PRIVILEGED_PHONE_STATE or
15309      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15310      *
15311      * @throws SecurityException if the caller does not have the required permission
15312      * @throws UnsupportedOperationException If the device does not have
15313      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
15314      */
15315     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15316     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSupportedRadioAccessFamily()15317     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
15318         try {
15319             ITelephony telephony = getITelephony();
15320             if (telephony != null) {
15321                 return telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
15322             } else {
15323                 // This can happen when the ITelephony interface is not up yet.
15324                 return NETWORK_TYPE_BITMASK_UNKNOWN;
15325             }
15326         } catch (RemoteException ex) {
15327             // This shouldn't happen in the normal case
15328             return NETWORK_TYPE_BITMASK_UNKNOWN;
15329         } catch (NullPointerException ex) {
15330             // This could happen before phone restarts due to crashing
15331             return NETWORK_TYPE_BITMASK_UNKNOWN;
15332         }
15333     }
15334 
15335     /**
15336      * Indicates Emergency number database version is invalid.
15337      *
15338      * @hide
15339      */
15340     @SystemApi
15341     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
15342 
15343     /**
15344      * Notify Telephony for OTA emergency number database installation complete.
15345      *
15346      * <p> Requires permission:
15347      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
15348      *
15349      * @throws UnsupportedOperationException If the device does not have
15350      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15351      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15352      * @hide
15353      */
15354     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15355     @RequiresFeature(anyOf = {
15356         PackageManager.FEATURE_TELEPHONY_CALLING,
15357         PackageManager.FEATURE_TELEPHONY_MESSAGING
15358     })
15359     @SystemApi
notifyOtaEmergencyNumberDbInstalled()15360     public void notifyOtaEmergencyNumberDbInstalled() {
15361         try {
15362             ITelephony telephony = getITelephony();
15363             if (telephony != null) {
15364                 telephony.notifyOtaEmergencyNumberDbInstalled();
15365             } else {
15366                 throw new IllegalStateException("telephony service is null.");
15367             }
15368         } catch (RemoteException ex) {
15369             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
15370             ex.rethrowAsRuntimeException();
15371         }
15372     }
15373 
15374     /**
15375      * Override the file path for OTA emergency number database in a file partition.
15376      *
15377      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
15378      *
15379      * <p> Requires permission:
15380      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
15381      *
15382      * @throws UnsupportedOperationException If the device does not have
15383      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15384      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15385      * @hide
15386      */
15387     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
15388     @RequiresFeature(anyOf = {
15389         PackageManager.FEATURE_TELEPHONY_CALLING,
15390         PackageManager.FEATURE_TELEPHONY_MESSAGING
15391     })
15392     @SystemApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)15393     public void updateOtaEmergencyNumberDbFilePath(
15394             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
15395         try {
15396             ITelephony telephony = getITelephony();
15397             if (telephony != null) {
15398                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
15399             } else {
15400                 throw new IllegalStateException("telephony service is null.");
15401             }
15402         } catch (RemoteException ex) {
15403             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
15404             ex.rethrowAsRuntimeException();
15405         }
15406     }
15407 
15408     /**
15409      * Reset the file path to default for OTA emergency number database in a file partition.
15410      *
15411      * <p> Requires permission:
15412      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
15413      *
15414      * @throws UnsupportedOperationException If the device does not have
15415      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15416      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15417      * @hide
15418      */
15419     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
15420     @RequiresFeature(anyOf = {
15421         PackageManager.FEATURE_TELEPHONY_CALLING,
15422         PackageManager.FEATURE_TELEPHONY_MESSAGING
15423     })
15424     @SystemApi
resetOtaEmergencyNumberDbFilePath()15425     public void resetOtaEmergencyNumberDbFilePath() {
15426         try {
15427             ITelephony telephony = getITelephony();
15428             if (telephony != null) {
15429                 telephony.resetOtaEmergencyNumberDbFilePath();
15430             } else {
15431                 throw new IllegalStateException("telephony service is null.");
15432             }
15433         } catch (RemoteException ex) {
15434             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
15435             ex.rethrowAsRuntimeException();
15436         }
15437     }
15438 
15439     /**
15440      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
15441      * available on the device.
15442      * <p>
15443      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
15444      *
15445      * @return {@code true} if emergency assistance is available, {@code false} otherwise
15446      *
15447      * @hide
15448      */
15449     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15450     @SuppressWarnings("AndroidFrameworkClientSidePermissionCheck")
15451     @SystemApi
isEmergencyAssistanceEnabled()15452     public boolean isEmergencyAssistanceEnabled() {
15453         mContext.enforceCallingOrSelfPermission(
15454                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
15455                 "isEmergencyAssistanceEnabled");
15456         return EMERGENCY_ASSISTANCE_ENABLED;
15457     }
15458 
15459     /**
15460      * Get the emergency assistance package name.
15461      *
15462      * @return the package name of the emergency assistance app, or {@code null} if no app
15463      * supports emergency assistance.
15464      * @throws IllegalStateException if emergency assistance is not enabled or the device is
15465      * not voice capable.
15466      *
15467      * @hide
15468      */
15469     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15470     @FlaggedApi(android.permission.flags.Flags.FLAG_GET_EMERGENCY_ROLE_HOLDER_API_ENABLED)
15471     @Nullable
15472     @SystemApi
getEmergencyAssistancePackageName()15473     public String getEmergencyAssistancePackageName() {
15474         if (!isEmergencyAssistanceEnabled() || !isVoiceCapable()) {
15475             throw new IllegalStateException("isEmergencyAssistanceEnabled() is false or device"
15476                 + " not voice capable.");
15477         }
15478         return mContext.getSystemService(RoleManager.class)
15479                 .getEmergencyRoleHolder(mContext.getUserId());
15480     }
15481 
15482     /**
15483      * Get the emergency number list based on current locale, sim, default, modem and network.
15484      *
15485      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
15486      * priority sources will be located at the smaller index; the priority order of sources are:
15487      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
15488      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
15489      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
15490      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
15491      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
15492      *
15493      * <p>The subscriptions which the returned list would be based on, are all the active
15494      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15495      *
15496      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
15497      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
15498      *
15499      * @return Map including the keys as the active subscription IDs (Note: if there is no active
15500      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
15501      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
15502      * or throw a SecurityException if the caller does not have the permission.
15503      *
15504      * @throws UnsupportedOperationException If the device does not have
15505      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15506      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15507      */
15508     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
15509     @NonNull
15510     @RequiresFeature(anyOf = {
15511         PackageManager.FEATURE_TELEPHONY_CALLING,
15512         PackageManager.FEATURE_TELEPHONY_MESSAGING
15513     })
getEmergencyNumberList()15514     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
15515         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
15516         try {
15517             ITelephony telephony = getITelephony();
15518             if (telephony != null) {
15519                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
15520                         mContext.getAttributionTag());
15521             } else {
15522                 throw new IllegalStateException("telephony service is null.");
15523             }
15524         } catch (RemoteException ex) {
15525             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
15526             ex.rethrowAsRuntimeException();
15527         }
15528         return emergencyNumberList;
15529     }
15530 
15531     /**
15532      * Get the per-category emergency number list based on current locale, sim, default, modem
15533      * and network.
15534      *
15535      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
15536      * priority sources will be located at the smaller index; the priority order of sources are:
15537      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
15538      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
15539      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
15540      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
15541      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
15542      *
15543      * <p>The subscriptions which the returned list would be based on, are all the active
15544      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15545      *
15546      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
15547      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
15548      *
15549      * @param categories the emergency service categories which are the bitwise-OR combination of
15550      * the following constants:
15551      * <ol>
15552      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
15553      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
15554      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
15555      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
15556      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
15557      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
15558      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
15559      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
15560      * </ol>
15561      * @return Map including the keys as the active subscription IDs (Note: if there is no active
15562      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
15563      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
15564      * or throw a SecurityException if the caller does not have the permission.
15565      * @throws IllegalStateException if the Telephony process is not currently available.
15566      * @throws UnsupportedOperationException If the device does not have
15567      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15568      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15569      */
15570     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
15571     @NonNull
15572     @RequiresFeature(anyOf = {
15573         PackageManager.FEATURE_TELEPHONY_CALLING,
15574         PackageManager.FEATURE_TELEPHONY_MESSAGING
15575     })
getEmergencyNumberList( @mergencyServiceCategories int categories)15576     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
15577             @EmergencyServiceCategories int categories) {
15578         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
15579         try {
15580             ITelephony telephony = getITelephony();
15581             if (telephony != null) {
15582                 Map<Integer, List<EmergencyNumber>> emergencyNumberList =
15583                         telephony.getEmergencyNumberList(mContext.getOpPackageName(),
15584                                 mContext.getAttributionTag());
15585                 emergencyNumberListForCategories =
15586                         filterEmergencyNumbersByCategories(emergencyNumberList, categories);
15587             } else {
15588                 throw new IllegalStateException("telephony service is null.");
15589             }
15590         } catch (RemoteException ex) {
15591             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
15592             ex.rethrowAsRuntimeException();
15593         }
15594         return emergencyNumberListForCategories;
15595     }
15596 
15597     /**
15598      * Filter emergency numbers with categories.
15599      *
15600      * @hide
15601      */
15602     @VisibleForTesting
filterEmergencyNumbersByCategories( Map<Integer, List<EmergencyNumber>> emergencyNumberList, @EmergencyServiceCategories int categories)15603     public Map<Integer, List<EmergencyNumber>> filterEmergencyNumbersByCategories(
15604             Map<Integer, List<EmergencyNumber>> emergencyNumberList,
15605                     @EmergencyServiceCategories int categories) {
15606         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
15607         if (emergencyNumberList != null) {
15608             for (Integer subscriptionId : emergencyNumberList.keySet()) {
15609                 List<EmergencyNumber> allNumbersForSub = emergencyNumberList.get(
15610                         subscriptionId);
15611                 List<EmergencyNumber> numbersForCategoriesPerSub = new ArrayList<>();
15612                 for (EmergencyNumber number : allNumbersForSub) {
15613                     if (number.isInEmergencyServiceCategories(categories)) {
15614                         numbersForCategoriesPerSub.add(number);
15615                     }
15616                 }
15617                 emergencyNumberListForCategories.put(
15618                         subscriptionId, numbersForCategoriesPerSub);
15619             }
15620         }
15621         return emergencyNumberListForCategories;
15622     }
15623 
15624     /**
15625      * Identifies if the supplied phone number is an emergency number that matches a known
15626      * emergency number based on current locale, SIM card(s), Android database, modem, network,
15627      * or defaults.
15628      *
15629      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
15630      * numbers are not considered emergency numbers. A dialable phone number consists only
15631      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
15632      *
15633      * <p>The subscriptions which the identification would be based on, are all the active
15634      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15635      *
15636      * @param number - the number to look up
15637      * @return {@code true} if the given number is an emergency number based on current locale,
15638      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
15639      * @throws IllegalStateException if the Telephony process is not currently available.
15640      * @throws UnsupportedOperationException If the device does not have
15641      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15642      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15643      */
15644     @RequiresFeature(anyOf = {
15645         PackageManager.FEATURE_TELEPHONY_CALLING,
15646         PackageManager.FEATURE_TELEPHONY_MESSAGING
15647     })
isEmergencyNumber(@onNull String number)15648     public boolean isEmergencyNumber(@NonNull String number) {
15649         try {
15650             ITelephony telephony = getITelephony();
15651             if (telephony != null) {
15652                 return telephony.isEmergencyNumber(number, true);
15653             } else {
15654                 throw new IllegalStateException("telephony service is null.");
15655             }
15656         } catch (RemoteException ex) {
15657             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
15658             ex.rethrowAsRuntimeException();
15659         }
15660         return false;
15661     }
15662 
15663     /**
15664      * Checks if the supplied number is an emergency number based on current locale, sim, default,
15665      * modem and network.
15666      *
15667      * <p> Specifically, this method will return {@code true} if the specified number is an
15668      * emergency number, *or* if the number simply starts with the same digits as any current
15669      * emergency number.
15670      *
15671      * <p>The subscriptions which the identification would be based on, are all the active
15672      * subscriptions, no matter which subscription could be used to create TelephonyManager.
15673      *
15674      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
15675      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15676      *
15677      * @param number - the number to look up
15678      * @return {@code true} if the given number is an emergency number or it simply starts with
15679      * the same digits of any current emergency number based on current locale, sim, modem and
15680      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
15681      * have the required permission/privileges
15682      * @throws IllegalStateException if the Telephony process is not currently available.
15683      * @throws UnsupportedOperationException If the device does not have
15684      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15685      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15686      *
15687      * @deprecated Please use {@link TelephonyManager#isEmergencyNumber(String)} instead.
15688      * @hide
15689      */
15690     @Deprecated
15691     @SystemApi
15692     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15693     @RequiresFeature(anyOf = {
15694         PackageManager.FEATURE_TELEPHONY_CALLING,
15695         PackageManager.FEATURE_TELEPHONY_MESSAGING
15696     })
isPotentialEmergencyNumber(@onNull String number)15697     public boolean isPotentialEmergencyNumber(@NonNull String number) {
15698         try {
15699             ITelephony telephony = getITelephony();
15700             if (telephony != null) {
15701                 return telephony.isEmergencyNumber(number, false);
15702             } else {
15703                 throw new IllegalStateException("telephony service is null.");
15704             }
15705         } catch (RemoteException ex) {
15706             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
15707             ex.rethrowAsRuntimeException();
15708         }
15709         return false;
15710     }
15711 
15712     /**
15713      * Returns the emergency number database version.
15714      *
15715      * <p>Requires Permission:
15716      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
15717      *
15718      * @throws UnsupportedOperationException If the device does not have
15719      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING} or
15720      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
15721      * @hide
15722      */
15723     @SystemApi
15724     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
15725     @RequiresFeature(anyOf = {
15726         PackageManager.FEATURE_TELEPHONY_CALLING,
15727         PackageManager.FEATURE_TELEPHONY_MESSAGING
15728     })
getEmergencyNumberDbVersion()15729     public int getEmergencyNumberDbVersion() {
15730         try {
15731             ITelephony telephony = getITelephony();
15732             if (telephony != null) {
15733                 return telephony.getEmergencyNumberDbVersion(getSubId());
15734             }
15735         } catch (RemoteException ex) {
15736             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
15737             ex.rethrowAsRuntimeException();
15738         }
15739         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
15740     }
15741 
15742     /** @hide */
15743     @Retention(RetentionPolicy.SOURCE)
15744     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
15745             SET_OPPORTUNISTIC_SUB_SUCCESS,
15746             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
15747             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
15748             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
15749             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
15750     public @interface SetOpportunisticSubscriptionResult {}
15751 
15752     /**
15753      * No error. Operation succeeded.
15754      */
15755     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
15756 
15757     /**
15758      * Validation failed when trying to switch to preferred subscription.
15759      */
15760     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
15761 
15762     /**
15763      * The subscription is not valid. It must be an active opportunistic subscription.
15764      */
15765     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
15766 
15767     /**
15768      * The subscription is not valid. It must be an opportunistic subscription.
15769      */
15770     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
15771 
15772     /**
15773      * Subscription service happened remote exception.
15774      */
15775     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
15776 
15777 
15778     /** @hide */
15779     @Retention(RetentionPolicy.SOURCE)
15780     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
15781             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
15782             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
15783             UPDATE_AVAILABLE_NETWORKS_ABORTED,
15784             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
15785             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
15786             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
15787             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
15788             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
15789             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
15790             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
15791             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED,
15792             UPDATE_AVAILABLE_NETWORKS_SIM_PORT_NOT_AVAILABLE})
15793     public @interface UpdateAvailableNetworksResult {}
15794 
15795     /**
15796      * No error. Operation succeeded.
15797      */
15798     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
15799 
15800     /**
15801      * There is a unknown failure happened.
15802      */
15803     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
15804 
15805     /**
15806      * The request is aborted.
15807      */
15808     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
15809 
15810     /**
15811      * The parameter passed in is invalid.
15812      */
15813     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
15814 
15815     /**
15816      * No carrier privilege.
15817      */
15818     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
15819 
15820     /**
15821      * Disable modem fail.
15822      */
15823     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
15824 
15825     /**
15826      * Enable modem fail.
15827      */
15828     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
15829 
15830     /**
15831      * Carrier app does not support multiple available networks.
15832      */
15833     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
15834 
15835     /**
15836      * The subscription is not valid. It must be an opportunistic subscription.
15837      */
15838     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
15839 
15840     /**
15841      * There is no OpportunisticNetworkService.
15842      */
15843     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
15844 
15845     /**
15846      * OpportunisticNetworkService is disabled.
15847      */
15848     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
15849 
15850     /**
15851      * SIM port is not available to switch to opportunistic subscription.
15852      * @hide
15853      */
15854     public static final int UPDATE_AVAILABLE_NETWORKS_SIM_PORT_NOT_AVAILABLE = 11;
15855 
15856     /**
15857      * Set preferred opportunistic data subscription id.
15858      *
15859      * Switch internet data to preferred opportunistic data subscription id. This api
15860      * can result in lose of internet connectivity for short period of time while internet data
15861      * is handed over.
15862      * <p>Requires that the calling app has carrier privileges on both primary and
15863      * secondary subscriptions (see
15864      * {@link #hasCarrierPrivileges}), or has permission
15865      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
15866      *
15867      * @param subId which opportunistic subscription
15868      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
15869      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
15870      * @param needValidation whether validation is needed before switch happens.
15871      * @param executor The executor of where the callback will execute.
15872      * @param callback Callback will be triggered once it succeeds or failed.
15873      *                 See the {@code SET_OPPORTUNISTIC_SUB_*} constants
15874      *                 for more details. Pass null if don't care about the result.
15875      *
15876      * @throws UnsupportedOperationException If the device does not have
15877      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
15878      */
15879     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)15880     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
15881             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
15882         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15883         try {
15884             IOns iOpportunisticNetworkService = getIOns();
15885             if (iOpportunisticNetworkService == null) {
15886                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
15887                     throw new IllegalStateException("Opportunistic Network Service is null");
15888                 } else {
15889                     // Let the general remote exception handling catch this.
15890                     throw new RemoteException("Null Opportunistic Network Service!");
15891                 }
15892             }
15893             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
15894                 @Override
15895                 public void onComplete(int result) {
15896                     if (executor == null || callback == null) {
15897                         return;
15898                     }
15899                     final long identity = Binder.clearCallingIdentity();
15900                     try {
15901                         executor.execute(() -> {
15902                             callback.accept(result);
15903                         });
15904                     } finally {
15905                         Binder.restoreCallingIdentity(identity);
15906                     }
15907                 }
15908             };
15909 
15910             iOpportunisticNetworkService
15911                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
15912                             pkgForDebug);
15913         } catch (RemoteException ex) {
15914             Rlog.e(TAG, "setPreferredOpportunisticDataSubscription RemoteException", ex);
15915             if (executor == null || callback == null) {
15916                 return;
15917             }
15918             runOnBackgroundThread(() -> executor.execute(() -> {
15919                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
15920                     callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
15921                 } else {
15922                     callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
15923                 }
15924             }));
15925         }
15926     }
15927 
15928     /**
15929      * Get preferred opportunistic data subscription Id
15930      *
15931      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
15932      * or has either READ_PRIVILEGED_PHONE_STATE
15933      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
15934      * @return subId preferred opportunistic subscription id or
15935      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
15936      * subscription id
15937      *
15938      * @throws UnsupportedOperationException If the device does not have
15939      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
15940      */
15941     @RequiresPermission(anyOf = {
15942             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
15943             android.Manifest.permission.READ_PHONE_STATE
15944     })
15945     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
getPreferredOpportunisticDataSubscription()15946     public int getPreferredOpportunisticDataSubscription() {
15947         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15948         String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
15949         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
15950         try {
15951             IOns iOpportunisticNetworkService = getIOns();
15952             if (iOpportunisticNetworkService != null) {
15953                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
15954                         packageName, attributionTag);
15955             }
15956         } catch (RemoteException ex) {
15957             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
15958         }
15959         return subId;
15960     }
15961 
15962     /**
15963      * Update availability of a list of networks in the current location.
15964      *
15965      * This api should be called to inform OpportunisticNetwork Service about the availability
15966      * of a network at the current location. This information will be used by OpportunisticNetwork
15967      * service to enable modem stack and to attach to the network. If an empty list is passed,
15968      * it is assumed that no network is available and will result in disabling the modem stack
15969      * to save power. This api do not switch internet data once network attach is completed.
15970      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
15971      * to switch internet data after network attach is complete.
15972      * Requires that the calling app has carrier privileges on both primary and
15973      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
15974      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
15975      * @param availableNetworks is a list of available network information.
15976      * @param executor The executor of where the callback will execute.
15977      * @param callback Callback will be triggered once it succeeds or failed.
15978      *
15979      * @throws UnsupportedOperationException If the device does not have
15980      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
15981      */
15982     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15983     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)15984     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
15985             @Nullable @CallbackExecutor Executor executor,
15986             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
15987         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
15988         Objects.requireNonNull(availableNetworks, "availableNetworks must not be null.");
15989         try {
15990             IOns iOpportunisticNetworkService = getIOns();
15991             if (iOpportunisticNetworkService == null) {
15992                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
15993                     throw new IllegalStateException("Opportunistic Network Service is null");
15994                 } else {
15995                     // Let the general remote exception handling catch this.
15996                     throw new RemoteException("Null Opportunistic Network Service!");
15997                 }
15998             }
15999 
16000             IUpdateAvailableNetworksCallback callbackStub =
16001                     new IUpdateAvailableNetworksCallback.Stub() {
16002                         @Override
16003                         public void onComplete(int result) {
16004                             if (executor == null || callback == null) {
16005                                 return;
16006                             }
16007                             Binder.withCleanCallingIdentity(() -> {
16008                                 executor.execute(() -> callback.accept(result));
16009                             });
16010                         }
16011                     };
16012             iOpportunisticNetworkService
16013                     .updateAvailableNetworks(availableNetworks, callbackStub, pkgForDebug);
16014         } catch (RemoteException ex) {
16015             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
16016             if (executor == null || callback == null) {
16017                 return;
16018             }
16019             runOnBackgroundThread(() -> executor.execute(() -> {
16020                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
16021                     callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
16022                 } else {
16023                     callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
16024                 }
16025             }));
16026         }
16027     }
16028 
16029     /**
16030      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
16031      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
16032      * For example, we will disable a modem when user or system believes the corresponding SIM
16033      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
16034      *
16035      * Requires that the calling app has permission
16036      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
16037      * @param slotIndex which corresponding modem will operate on.
16038      * @param enable whether to enable or disable the modem stack.
16039      * @return whether the operation is successful.
16040      *
16041      * @throws UnsupportedOperationException If the device does not have
16042      *          {@link PackageManager#FEATURE_TELEPHONY}.
16043      * @hide
16044      */
16045     @SystemApi
16046     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16047     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
enableModemForSlot(int slotIndex, boolean enable)16048     public boolean enableModemForSlot(int slotIndex, boolean enable) {
16049         boolean ret = false;
16050         try {
16051             ITelephony telephony = getITelephony();
16052             if (telephony != null) {
16053                 ret = telephony.enableModemForSlot(slotIndex, enable);
16054             }
16055         } catch (RemoteException ex) {
16056             Log.e(TAG, "enableModem RemoteException", ex);
16057         }
16058         return ret;
16059     }
16060 
16061     /**
16062      * Indicates whether or not there is a modem stack enabled for the given SIM slot.
16063      *
16064      * <p>Requires Permission:
16065      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE},
16066      * READ_PRIVILEGED_PHONE_STATE or that the calling app has carrier privileges (see
16067      * {@link #hasCarrierPrivileges()}).
16068      *
16069      * @param slotIndex which slot it's checking.
16070      *
16071      * @throws UnsupportedOperationException If the device does not have
16072      *          {@link PackageManager#FEATURE_TELEPHONY}.
16073      */
16074     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
16075     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PHONE_STATE,
16076             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
16077     @RequiresFeature(PackageManager.FEATURE_TELEPHONY)
isModemEnabledForSlot(int slotIndex)16078     public boolean isModemEnabledForSlot(int slotIndex) {
16079         try {
16080             ITelephony telephony = getITelephony();
16081             if (telephony != null) {
16082                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
16083                         mContext.getAttributionTag());
16084             }
16085         } catch (RemoteException ex) {
16086             Log.e(TAG, "enableModem RemoteException", ex);
16087         }
16088         return false;
16089     }
16090 
16091     /**
16092      * Broadcast intent action for network country code changes.
16093      *
16094      * <p>
16095      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
16096      * network returned by {@link #getNetworkCountryIso()}.
16097      *
16098      * <p>There may be a delay of several minutes before reporting that no country is detected.
16099      *
16100      * @see #EXTRA_NETWORK_COUNTRY
16101      * @see #getNetworkCountryIso()
16102      */
16103     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
16104             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
16105 
16106     /**
16107      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
16108      * the country code in ISO-3166-1 alpha-2 format. This is the same country code returned by
16109      * {@link #getNetworkCountryIso()}. This might be an empty string when the country code is not
16110      * available.
16111      *
16112      * <p class="note">
16113      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
16114      */
16115     public static final String EXTRA_NETWORK_COUNTRY =
16116             "android.telephony.extra.NETWORK_COUNTRY";
16117 
16118     /**
16119      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
16120      * last known the country code in ISO-3166-1 alpha-2 format. This might be an empty string when
16121      * the country code was never available. The last known country code persists across reboot.
16122      *
16123      * <p class="note">
16124      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
16125      */
16126     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
16127             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
16128 
16129     /**
16130      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
16131      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
16132      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
16133      * policies of the carrier.
16134      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
16135      * access to the network.
16136      *
16137      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
16138      * otherwise.
16139      *
16140      * @throws UnsupportedOperationException If the device does not have
16141      *          {@link PackageManager#FEATURE_TELEPHONY_CARRIERLOCK}.
16142      * @hide
16143      */
16144     @SystemApi
16145     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16146     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CARRIERLOCK)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)16147     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
16148         try {
16149             ITelephony service = getITelephony();
16150             if (service != null) {
16151                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
16152             }
16153         } catch (RemoteException e) {
16154             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
16155         }
16156     }
16157 
16158     /**
16159      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
16160      * Standby or Dual Active) is supported.
16161      */
16162     public static final int MULTISIM_ALLOWED = 0;
16163 
16164     /**
16165      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
16166      * Standby or Dual Active) is not supported by the hardware.
16167      */
16168     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
16169 
16170     /**
16171      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
16172      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
16173      */
16174     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
16175 
16176     /** @hide */
16177     @Retention(RetentionPolicy.SOURCE)
16178     @IntDef(prefix = {"MULTISIM_"},
16179             value = {
16180                     MULTISIM_ALLOWED,
16181                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
16182                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
16183             })
16184     public @interface IsMultiSimSupportedResult {}
16185 
16186     /**
16187      * Returns if the usage of multiple SIM cards at the same time to register on the network
16188      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
16189      *
16190      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
16191      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16192      *
16193      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
16194      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
16195      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
16196      * functionality is restricted by the carrier.
16197      *
16198      * @throws UnsupportedOperationException If the device does not have
16199      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16200      */
16201     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
16202     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
16203     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
16204     @IsMultiSimSupportedResult
isMultiSimSupported()16205     public int isMultiSimSupported() {
16206         if (getSupportedModemCount() < 2) {
16207             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
16208         }
16209         try {
16210             ITelephony service = getITelephony();
16211             if (service != null) {
16212                 return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
16213             }
16214         } catch (RemoteException e) {
16215             Log.e(TAG, "isMultiSimSupported RemoteException", e);
16216         }
16217         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
16218     }
16219 
16220     /**
16221      * Switch configs to enable multi-sim or switch back to single-sim
16222      * <p>Requires Permission:
16223      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
16224      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16225      *
16226      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
16227      * to single-sim
16228      *
16229      * @param numOfSims number of live SIMs we want to switch to
16230      * @throws android.os.RemoteException
16231      * @throws UnsupportedOperationException If the device does not have
16232      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16233      */
16234     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
16235     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16236     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
switchMultiSimConfig(int numOfSims)16237     public void switchMultiSimConfig(int numOfSims) {
16238         try {
16239             ITelephony telephony = getITelephony();
16240             if (telephony != null) {
16241                 telephony.switchMultiSimConfig(numOfSims);
16242             }
16243         } catch (RemoteException ex) {
16244             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
16245         }
16246     }
16247 
16248     /**
16249      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
16250      * trigger device reboot.
16251      * The modem configuration change refers to switching from single SIM configuration to DSDS
16252      * or the other way around.
16253      *
16254      *  <p>Requires Permission:
16255      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
16256      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16257      *
16258      * @return {@code true} if reboot will be triggered after making changes to modem
16259      * configurations, otherwise return {@code false}.
16260      *
16261      * @throws UnsupportedOperationException If the device does not have
16262      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16263      */
16264     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
16265     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
doesSwitchMultiSimConfigTriggerReboot()16266     public boolean doesSwitchMultiSimConfigTriggerReboot() {
16267         try {
16268             ITelephony service = getITelephony();
16269             if (service != null) {
16270                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
16271                         getOpPackageName(), getAttributionTag());
16272             }
16273         } catch (RemoteException e) {
16274             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
16275         }
16276         return false;
16277     }
16278 
16279     /**
16280      * Retrieve the Radio HAL Version for this device.
16281      *
16282      * Get the HAL version for the IRadio interface for test purposes.
16283      *
16284      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
16285      *
16286      * @hide
16287      *
16288      * @deprecated Use {@link #getHalVersion} instead.
16289      */
16290     @Deprecated
16291     @UnsupportedAppUsage
16292     @TestApi
getRadioHalVersion()16293     public Pair<Integer, Integer> getRadioHalVersion() {
16294         return getHalVersion(HAL_SERVICE_RADIO);
16295     }
16296 
16297     /** @hide */
16298     public static final int HAL_SERVICE_RADIO = 0;
16299 
16300     /**
16301      * HAL service type that supports the HAL APIs implementation of IRadioData
16302      * {@link RadioDataProxy}
16303      * @hide
16304      */
16305     @TestApi
16306     public static final int HAL_SERVICE_DATA = 1;
16307 
16308     /**
16309      * HAL service type that supports the HAL APIs implementation of IRadioMessaging
16310      * {@link RadioMessagingProxy}
16311      * @hide
16312      */
16313     @TestApi
16314     public static final int HAL_SERVICE_MESSAGING = 2;
16315 
16316     /**
16317      * HAL service type that supports the HAL APIs implementation of IRadioModem
16318      * {@link RadioModemProxy}
16319      * @hide
16320      */
16321     @TestApi
16322     public static final int HAL_SERVICE_MODEM = 3;
16323 
16324     /**
16325      * HAL service type that supports the HAL APIs implementation of IRadioNetwork
16326      * {@link RadioNetworkProxy}
16327      * @hide
16328      */
16329     @TestApi
16330     public static final int HAL_SERVICE_NETWORK = 4;
16331 
16332     /**
16333      * HAL service type that supports the HAL APIs implementation of IRadioSim
16334      * {@link RadioSimProxy}
16335      * @hide
16336      */
16337     @TestApi
16338     public static final int HAL_SERVICE_SIM = 5;
16339 
16340     /**
16341      * HAL service type that supports the HAL APIs implementation of IRadioVoice
16342      * {@link RadioVoiceProxy}
16343      * @hide
16344      */
16345     @TestApi
16346     public static final int HAL_SERVICE_VOICE = 6;
16347 
16348     /**
16349      * HAL service type that supports the HAL APIs implementation of IRadioIms
16350      * {@link RadioImsProxy}
16351      * @hide
16352      */
16353     @TestApi
16354     public static final int HAL_SERVICE_IMS = 7;
16355 
16356     /** @hide */
16357     @Retention(RetentionPolicy.SOURCE)
16358     @IntDef(prefix = {"HAL_SERVICE_"},
16359             value = {
16360                     HAL_SERVICE_RADIO,
16361                     HAL_SERVICE_DATA,
16362                     HAL_SERVICE_MESSAGING,
16363                     HAL_SERVICE_MODEM,
16364                     HAL_SERVICE_NETWORK,
16365                     HAL_SERVICE_SIM,
16366                     HAL_SERVICE_VOICE,
16367                     HAL_SERVICE_IMS,
16368             })
16369     public @interface HalService {}
16370 
16371     /**
16372      * The HAL Version indicating that the version is unknown or invalid.
16373      * @hide
16374      */
16375     @TestApi
16376     public static final Pair HAL_VERSION_UNKNOWN = new Pair(-1, -1);
16377 
16378     /**
16379      * The HAL Version indicating that the version is unsupported.
16380      * @hide
16381      */
16382     @TestApi
16383     public static final Pair HAL_VERSION_UNSUPPORTED = new Pair(-2, -2);
16384 
16385     /**
16386      * Retrieve the HAL Version of a specific service for this device.
16387      *
16388      * Get the HAL version for a specific HAL interface for test purposes.
16389      *
16390      * @param halService the service id to query.
16391      * @return a Pair of (major version, minor version), HAL_VERSION_UNKNOWN if unknown
16392      * or HAL_VERSION_UNSUPPORTED if unsupported.
16393      *
16394      * @hide
16395      */
16396     @TestApi
getHalVersion(@alService int halService)16397     public @NonNull Pair<Integer, Integer> getHalVersion(@HalService int halService) {
16398         try {
16399             ITelephony service = getITelephony();
16400             if (service != null) {
16401                 int version = service.getHalVersion(halService);
16402                 if (version != -1) {
16403                     return new Pair<Integer, Integer>(version / 100, version % 100);
16404                 }
16405             } else {
16406                 throw new IllegalStateException("telephony service is null.");
16407             }
16408         } catch (RemoteException e) {
16409             Log.e(TAG, "getHalVersion() RemoteException", e);
16410             e.rethrowAsRuntimeException();
16411         }
16412         return HAL_VERSION_UNKNOWN;
16413     }
16414 
16415     /**
16416      * Get the calling application status about carrier privileges for the subscription created
16417      * in TelephonyManager. Used by Telephony Module for permission checking.
16418      *
16419      * @param uid Uid to check.
16420      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
16421      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
16422      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
16423      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
16424      *
16425      * @throws UnsupportedOperationException If the device does not have
16426      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16427      * @hide
16428      */
16429     @SystemApi
16430     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16431     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getCarrierPrivilegeStatus(int uid)16432     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
16433         try {
16434             ITelephony telephony = getITelephony();
16435             if (telephony != null) {
16436                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
16437             }
16438         } catch (RemoteException ex) {
16439             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
16440         }
16441         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
16442     }
16443 
16444     /**
16445      * Returns a list of APNs set as overrides by the device policy manager via
16446      * {@link #addDevicePolicyOverrideApn}.
16447      * This method must only be called from the system or phone processes.
16448      *
16449      * @param context Context to use.
16450      * @return {@link List} of APNs that have been set as overrides.
16451      * @throws {@link SecurityException} if the caller is not the system or phone process.
16452      * @hide
16453      */
16454     @TestApi
16455     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)16456     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
16457         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
16458             if (cursor == null) {
16459                 return Collections.emptyList();
16460             }
16461             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
16462             cursor.moveToPosition(-1);
16463             while (cursor.moveToNext()) {
16464                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
16465                 apnList.add(apn);
16466             }
16467             return apnList;
16468         }
16469     }
16470 
16471     /**
16472      * Used by the device policy manager to add a new override APN.
16473      * This method must only be called from the system or phone processes.
16474      *
16475      * @param context Context to use.
16476      * @param apnSetting The {@link ApnSetting} describing the new APN.
16477      * @return An integer, corresponding to a primary key in a database, that allows the caller to
16478      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
16479      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
16480      *         failed.
16481      * @throws {@link SecurityException} if the caller is not the system or phone process.
16482      * @hide
16483      */
16484     @TestApi
16485     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)16486     public int addDevicePolicyOverrideApn(@NonNull Context context,
16487             @NonNull ApnSetting apnSetting) {
16488         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
16489 
16490         int resultId = INVALID_APN_ID;
16491         if (resultUri != null) {
16492             try {
16493                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
16494             } catch (NumberFormatException e) {
16495                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
16496                         + resultUri.getLastPathSegment());
16497             }
16498         }
16499         return resultId;
16500     }
16501 
16502     /**
16503      * Used by the device policy manager to modify an override APN.
16504      * This method must only be called from the system or phone processes.
16505      *
16506      * @param context Context to use.
16507      * @param apnId The integer key of the APN to modify, as returned by
16508      *              {@link #addDevicePolicyOverrideApn}
16509      * @param apnSetting The {@link ApnSetting} describing the updated APN.
16510      * @return {@code true} if successful, {@code false} otherwise.
16511      * @throws {@link SecurityException} if the caller is not the system or phone process.
16512      * @hide
16513      */
16514     @TestApi
16515     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)16516     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
16517             @NonNull ApnSetting apnSetting) {
16518         return context.getContentResolver().update(
16519                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
16520                 apnSetting.toContentValues(), null, null) > 0;
16521     }
16522 
16523     /**
16524      * Return whether data is enabled for certain APN type. This will tell if framework will accept
16525      * corresponding network requests on a subId.
16526      *
16527      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
16528      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
16529      *
16530      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
16531      * It will return true if:
16532      *
16533      *  1) User data is turned on, or
16534      *  2) APN is un-metered for this subscription, or
16535      *  3) APN type is allowlisted. E.g. MMS is allowlisted if
16536      *  {@link #MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED} is enabled.
16537      *
16538      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
16539      * @return whether data is enabled for a apn type.
16540      *
16541      * @throws UnsupportedOperationException If the device does not have
16542      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
16543      * @hide
16544      */
16545     @SystemApi
16546     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16547     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isDataEnabledForApn(@pnType int apnType)16548     public boolean isDataEnabledForApn(@ApnType int apnType) {
16549         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
16550         try {
16551             ITelephony service = getITelephony();
16552             if (service != null) {
16553                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
16554             }
16555         } catch (RemoteException ex) {
16556             Rlog.e(TAG, "Telephony#isDataEnabledForApn RemoteException" + ex);
16557         }
16558         return false;
16559     }
16560 
16561     /**
16562      * Whether an APN type is metered or not. It will be evaluated with the subId associated
16563      * with the TelephonyManager instance.
16564      *
16565      * @throws UnsupportedOperationException If the device does not have
16566      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
16567      * @hide
16568      */
16569     @SystemApi
16570     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16571     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isApnMetered(@pnType int apnType)16572     public boolean isApnMetered(@ApnType int apnType) {
16573         try {
16574             ITelephony service = getITelephony();
16575             if (service != null) {
16576                 return service.isApnMetered(apnType, getSubId());
16577             }
16578         } catch (RemoteException ex) {
16579             Rlog.e(TAG, "Telephony#isApnMetered RemoteException" + ex);
16580         }
16581         return true;
16582     }
16583 
16584     /**
16585      * Specify which bands modem's background scan must act on.
16586      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
16587      * Otherwise, it scans all bands.
16588      *
16589      * For example, CBRS is only on LTE band 48. By specifying this band,
16590      * modem saves more power.
16591      *
16592      * @param specifiers which bands to scan.
16593      * @param executor The executor to execute the callback on
16594      * @param callback The callback that gets invoked when the radio responds to the request. Called
16595      *                 with {@code true} if the request succeeded, {@code false} otherwise.
16596      *
16597      * @throws UnsupportedOperationException If the device does not have
16598      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
16599      * @hide
16600      */
16601     @SystemApi
16602     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16603     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)16604     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
16605             @NonNull @CallbackExecutor Executor executor,
16606             @NonNull Consumer<Boolean> callback) {
16607         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
16608         Objects.requireNonNull(executor, "Executor must not be null.");
16609         Objects.requireNonNull(callback, "Callback must not be null.");
16610         setSystemSelectionChannelsInternal(specifiers, executor, callback);
16611     }
16612 
16613     /**
16614      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
16615      * used when the caller does not need feedback on the results of the operation.
16616      * @param specifiers which bands to scan.
16617      *
16618      * @throws UnsupportedOperationException If the device does not have
16619      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
16620      * @hide
16621      */
16622     @SystemApi
16623     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16624     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)16625     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
16626         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
16627         setSystemSelectionChannelsInternal(specifiers, null, null);
16628     }
16629 
16630 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)16631     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
16632             @Nullable @CallbackExecutor Executor executor,
16633             @Nullable Consumer<Boolean> callback) {
16634         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
16635             @Override
16636             public void accept(boolean result) {
16637                 final long identity = Binder.clearCallingIdentity();
16638                 try {
16639                     executor.execute(() -> callback.accept(result));
16640                 } finally {
16641                     Binder.restoreCallingIdentity(identity);
16642                 }
16643             }
16644         };
16645 
16646         try {
16647             ITelephony service = getITelephony();
16648             if (service != null) {
16649                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
16650             }
16651         } catch (RemoteException ex) {
16652             Rlog.e(TAG, "Telephony#setSystemSelectionChannels RemoteException" + ex);
16653         }
16654     }
16655 
16656     /**
16657      * Get which bands the modem's background scan is acting on, specified by
16658      * {@link #setSystemSelectionChannels}.
16659      *
16660      * <p>Requires Permission:
16661      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
16662      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
16663      *
16664      * @return a list of {@link RadioAccessSpecifier}, or an empty list if no bands are specified.
16665      * @throws IllegalStateException if the Telephony process is not currently available.
16666      *
16667      * @throws UnsupportedOperationException If the device does not have
16668      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
16669      * @hide
16670      */
16671     @SystemApi
16672     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16673     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
getSystemSelectionChannels()16674     public @NonNull List<RadioAccessSpecifier> getSystemSelectionChannels() {
16675         try {
16676             ITelephony service = getITelephony();
16677             if (service != null) {
16678                 return service.getSystemSelectionChannels(getSubId());
16679             } else {
16680                 throw new IllegalStateException("telephony service is null.");
16681             }
16682         } catch (RemoteException ex) {
16683             Rlog.e(TAG, "Telephony#getSystemSelectionChannels RemoteException" + ex);
16684         }
16685         return new ArrayList<>();
16686     }
16687 
16688     /**
16689      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
16690      *
16691      * @param mccmnc the carrier's mccmnc that you want to match
16692      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
16693      * @param mvnoMatchData the MVNO match data
16694      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
16695      * {@code false} otherwise.
16696      *
16697      * @throws UnsupportedOperationException If the device does not have
16698      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
16699      * {@hide}
16700      */
16701     @SystemApi
16702     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16703     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
matchesCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)16704     public boolean matchesCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
16705             @Nullable String mvnoMatchData) {
16706         try {
16707             if (!mccmnc.equals(getSimOperator())) {
16708                 return false;
16709             }
16710             ITelephony service = getITelephony();
16711             if (service != null) {
16712                 return service.isMvnoMatched(getSlotIndex(), mvnoType, mvnoMatchData);
16713             }
16714         } catch (RemoteException ex) {
16715             Rlog.e(TAG, "Telephony#matchesCurrentSimOperator RemoteException" + ex);
16716         }
16717         return false;
16718     }
16719 
16720     /**
16721      * Callback to be used with {@link #getCallForwarding}
16722      * @hide
16723      */
16724     @SystemApi
16725     public interface CallForwardingInfoCallback {
16726         /**
16727          * Indicates that the operation was successful.
16728          */
16729         int RESULT_SUCCESS = 0;
16730 
16731         /**
16732          * Indicates that setting or retrieving the call forwarding info failed with an unknown
16733          * error.
16734          */
16735         int RESULT_ERROR_UNKNOWN = 1;
16736 
16737         /**
16738          * Indicates that call forwarding is not enabled because the recipient is not on a
16739          * Fixed Dialing Number (FDN) list.
16740          */
16741         int RESULT_ERROR_FDN_CHECK_FAILURE = 2;
16742 
16743         /**
16744          * Indicates that call forwarding is not supported on the network at this time.
16745          */
16746         int RESULT_ERROR_NOT_SUPPORTED = 3;
16747 
16748         /**
16749          * Call forwarding errors
16750          * @hide
16751          */
16752         @IntDef(prefix = { "RESULT_ERROR_" }, value = {
16753                 RESULT_ERROR_UNKNOWN,
16754                 RESULT_ERROR_NOT_SUPPORTED,
16755                 RESULT_ERROR_FDN_CHECK_FAILURE
16756         })
16757         @Retention(RetentionPolicy.SOURCE)
16758         @interface CallForwardingError{
16759         }
16760         /**
16761          * Called when the call forwarding info is successfully retrieved from the network.
16762          * @param info information about how calls are forwarded
16763          */
onCallForwardingInfoAvailable(@onNull CallForwardingInfo info)16764         void onCallForwardingInfoAvailable(@NonNull CallForwardingInfo info);
16765 
16766         /**
16767          * Called when there was an error retrieving the call forwarding information.
16768          * @param error
16769          */
onError(@allForwardingError int error)16770         void onError(@CallForwardingError int error);
16771     }
16772 
16773     /**
16774      * Gets the voice call forwarding info for a given call forwarding reason.
16775      *
16776      * This method queries the network for the currently set call forwarding configuration for the
16777      * provided call forwarding reason. When the network has provided its response, the result will
16778      * be supplied via the provided {@link Executor} on the provided
16779      * {@link CallForwardingInfoCallback}.
16780      *
16781      * @param callForwardingReason the call forwarding reason to query.
16782      * @param executor The executor on which to execute the callback once the result is ready.
16783      * @param callback The callback the results should be delivered on.
16784      *
16785      * @throws IllegalArgumentException if callForwardingReason is not any of
16786      * {@link CallForwardingInfo#REASON_UNCONDITIONAL}, {@link CallForwardingInfo#REASON_BUSY},
16787      * {@link CallForwardingInfo#REASON_NO_REPLY}, {@link CallForwardingInfo#REASON_NOT_REACHABLE},
16788      * {@link CallForwardingInfo#REASON_ALL}, or {@link CallForwardingInfo#REASON_ALL_CONDITIONAL}
16789      * @throws UnsupportedOperationException If the device does not have
16790      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16791      *
16792      * @hide
16793      */
16794     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
16795     @SystemApi
16796     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallForwarding(@allForwardingReason int callForwardingReason, @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback)16797     public void getCallForwarding(@CallForwardingReason int callForwardingReason,
16798             @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback) {
16799         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
16800                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
16801             throw new IllegalArgumentException("callForwardingReason is out of range");
16802         }
16803 
16804         ICallForwardingInfoCallback internalCallback = new ICallForwardingInfoCallback.Stub() {
16805             @Override
16806             public void onCallForwardingInfoAvailable(CallForwardingInfo info) {
16807                 executor.execute(() ->
16808                         Binder.withCleanCallingIdentity(() ->
16809                                 callback.onCallForwardingInfoAvailable(info)));
16810             }
16811 
16812             @Override
16813             public void onError(int error) {
16814                 executor.execute(() ->
16815                         Binder.withCleanCallingIdentity(() ->
16816                                 callback.onError(error)));
16817             }
16818         };
16819 
16820         try {
16821             ITelephony telephony = getITelephony();
16822             if (telephony != null) {
16823                 telephony.getCallForwarding(getSubId(), callForwardingReason, internalCallback);
16824             }
16825         } catch (RemoteException ex) {
16826             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
16827             ex.rethrowAsRuntimeException();
16828         }
16829     }
16830 
16831     /**
16832      * Sets voice call forwarding behavior as described by the provided {@link CallForwardingInfo}.
16833      *
16834      * This method will enable call forwarding if the provided {@link CallForwardingInfo} returns
16835      * {@code true} from its {@link CallForwardingInfo#isEnabled()} method, and disables call
16836      * forwarding otherwise.
16837      *
16838      * If you wish to be notified about the results of this operation, provide an {@link Executor}
16839      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
16840      *
16841      * @param callForwardingInfo Info about whether calls should be forwarded and where they
16842      *                           should be forwarded to.
16843      * @param executor The executor on which the listener will be called. Must be non-null if
16844      *                 {@code listener} is non-null.
16845      * @param resultListener Asynchronous listener that'll be called when the operation completes.
16846      *                      Called with {@link CallForwardingInfoCallback#RESULT_SUCCESS} if the
16847      *                      operation succeeded and an error code from
16848      *                      {@link CallForwardingInfoCallback} it failed.
16849      *
16850      * @throws IllegalArgumentException if any of the following are true for the parameter
16851      * callForwardingInfo:
16852      * <ul>
16853      * <li>it is {@code null}.</li>
16854      * <li>{@link CallForwardingInfo#getReason()} is not any of:
16855      *     <ul>
16856      *         <li>{@link CallForwardingInfo#REASON_UNCONDITIONAL}</li>
16857      *         <li>{@link CallForwardingInfo#REASON_BUSY}</li>
16858      *         <li>{@link CallForwardingInfo#REASON_NO_REPLY}</li>
16859      *         <li>{@link CallForwardingInfo#REASON_NOT_REACHABLE}</li>
16860      *         <li>{@link CallForwardingInfo#REASON_ALL}</li>
16861      *         <li>{@link CallForwardingInfo#REASON_ALL_CONDITIONAL}</li>
16862      *     </ul>
16863      * <li>{@link CallForwardingInfo#getNumber()} returns {@code null} when enabling call
16864      * forwarding</li>
16865      * <li>{@link CallForwardingInfo#getTimeoutSeconds()} returns a non-positive value when
16866      * enabling call forwarding</li>
16867      * </ul>
16868      * @throws UnsupportedOperationException If the device does not have
16869      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16870      * @hide
16871      */
16872     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
16873     @SystemApi
16874     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo, @Nullable @CallbackExecutor Executor executor, @Nullable @CallForwardingInfoCallback.CallForwardingError Consumer<Integer> resultListener)16875     public void setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo,
16876             @Nullable @CallbackExecutor Executor executor,
16877             @Nullable @CallForwardingInfoCallback.CallForwardingError
16878                     Consumer<Integer> resultListener) {
16879         if (callForwardingInfo == null) {
16880             throw new IllegalArgumentException("callForwardingInfo is null");
16881         }
16882         int callForwardingReason = callForwardingInfo.getReason();
16883         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
16884                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
16885             throw new IllegalArgumentException("callForwardingReason is out of range");
16886         }
16887         if (callForwardingInfo.isEnabled()) {
16888             if (callForwardingInfo.getNumber() == null) {
16889                 throw new IllegalArgumentException("callForwarding number is null");
16890             }
16891             if (callForwardingReason == CallForwardingInfo.REASON_NO_REPLY
16892                         && callForwardingInfo.getTimeoutSeconds() <= 0) {
16893                 throw new IllegalArgumentException("callForwarding timeout isn't positive");
16894             }
16895         }
16896         if (resultListener != null) {
16897             Objects.requireNonNull(executor);
16898         }
16899 
16900         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
16901             @Override
16902             public void accept(int result) {
16903                 executor.execute(() ->
16904                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
16905             }
16906         };
16907 
16908         try {
16909             ITelephony telephony = getITelephony();
16910             if (telephony != null) {
16911                 telephony.setCallForwarding(getSubId(), callForwardingInfo, internalCallback);
16912             }
16913         } catch (RemoteException ex) {
16914             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
16915             ex.rethrowAsRuntimeException();
16916         } catch (NullPointerException ex) {
16917             Rlog.e(TAG, "setCallForwarding NPE", ex);
16918             throw ex;
16919         }
16920     }
16921 
16922     /**
16923      * Indicates that call waiting is enabled.
16924      *
16925      * @hide
16926      */
16927     @SystemApi
16928     public static final int CALL_WAITING_STATUS_ENABLED = 1;
16929 
16930     /**
16931      * Indicates that call waiting is disabled.
16932      *
16933      * @hide
16934      */
16935     @SystemApi
16936     public static final int CALL_WAITING_STATUS_DISABLED = 2;
16937 
16938     /**
16939      * Indicates there was an unknown error retrieving the call waiting status.
16940      *
16941      * @hide
16942      */
16943     @SystemApi
16944     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
16945 
16946     /**
16947      * Indicates the call waiting is not supported on the current network.
16948      *
16949      * @hide
16950      */
16951     @SystemApi
16952     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
16953 
16954     /**
16955      * Indicates the call waiting status could not be set or queried because the Fixed Dialing
16956      * Numbers (FDN) feature is enabled.
16957      *
16958      * @hide
16959      */
16960     @SystemApi
16961     public static final int CALL_WAITING_STATUS_FDN_CHECK_FAILURE = 5;
16962 
16963     /**
16964      * @hide
16965      */
16966     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
16967             CALL_WAITING_STATUS_ENABLED,
16968             CALL_WAITING_STATUS_DISABLED,
16969             CALL_WAITING_STATUS_UNKNOWN_ERROR,
16970             CALL_WAITING_STATUS_NOT_SUPPORTED,
16971             CALL_WAITING_STATUS_FDN_CHECK_FAILURE,
16972     })
16973     @Retention(RetentionPolicy.SOURCE)
16974     public @interface CallWaitingStatus {
16975     }
16976 
16977     /**
16978      * Retrieves the call waiting status of this device from the network.
16979      *
16980      * When call waiting is enabled, an incoming call that arrives when the user is already on
16981      * an active call will be held in a waiting state while the user is notified instead of being
16982      * rejected with a busy signal.
16983      *
16984      * @param executor The executor on which the result listener will be called.
16985      * @param resultListener A {@link Consumer} that will be called with the result fetched
16986      *                       from the network. The result will be one of:
16987      *                       <ul>
16988      *                          <li>{@link #CALL_WAITING_STATUS_ENABLED}}</li>
16989      *                          <li>{@link #CALL_WAITING_STATUS_DISABLED}}</li>
16990      *                          <li>{@link #CALL_WAITING_STATUS_UNKNOWN_ERROR}}</li>
16991      *                          <li>{@link #CALL_WAITING_STATUS_NOT_SUPPORTED}}</li>
16992      *                          <li>{@link #CALL_WAITING_STATUS_FDN_CHECK_FAILURE}}</li>
16993      *                       </ul>
16994      *
16995      * @throws UnsupportedOperationException If the device does not have
16996      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
16997      * @hide
16998      */
16999     @SystemApi
17000     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
17001     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
getCallWaitingStatus(@onNull Executor executor, @NonNull @CallWaitingStatus Consumer<Integer> resultListener)17002     public void getCallWaitingStatus(@NonNull Executor executor,
17003             @NonNull @CallWaitingStatus Consumer<Integer> resultListener) {
17004         Objects.requireNonNull(executor);
17005         Objects.requireNonNull(resultListener);
17006 
17007         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
17008             @Override
17009             public void accept(int result) {
17010                 executor.execute(() -> Binder.withCleanCallingIdentity(
17011                         () -> resultListener.accept(result)));
17012             }
17013         };
17014 
17015         try {
17016             ITelephony telephony = getITelephony();
17017             if (telephony != null) {
17018                 telephony.getCallWaitingStatus(getSubId(), internalCallback);
17019             }
17020         } catch (RemoteException ex) {
17021             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
17022             ex.rethrowAsRuntimeException();
17023         } catch (NullPointerException ex) {
17024             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
17025             throw ex;
17026         }
17027     }
17028 
17029     /**
17030      * Sets the call waiting status of this device with the network.
17031      *
17032      * If you wish to be notified about the results of this operation, provide an {@link Executor}
17033      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
17034      *
17035      * @see #getCallWaitingStatus for a description of the call waiting functionality.
17036      *
17037      * @param enabled {@code true} to enable; {@code false} to disable.
17038      * @param executor The executor on which the listener will be called. Must be non-null if
17039      *                 {@code listener} is non-null.
17040      * @param resultListener Asynchronous listener that'll be called when the operation completes.
17041      *                       Called with the new call waiting status (either
17042      *                       {@link #CALL_WAITING_STATUS_ENABLED} or
17043      *                       {@link #CALL_WAITING_STATUS_DISABLED} if the operation succeeded and
17044      *                       {@link #CALL_WAITING_STATUS_NOT_SUPPORTED} or
17045      *                       {@link #CALL_WAITING_STATUS_UNKNOWN_ERROR} or
17046      *                       {@link #CALL_WAITING_STATUS_FDN_CHECK_FAILURE} if it failed.
17047      *
17048      * @throws UnsupportedOperationException If the device does not have
17049      *          {@link PackageManager#FEATURE_TELEPHONY_CALLING}.
17050      * @hide
17051      */
17052     @SystemApi
17053     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17054     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
setCallWaitingEnabled(boolean enabled, @Nullable Executor executor, @Nullable Consumer<Integer> resultListener)17055     public void setCallWaitingEnabled(boolean enabled, @Nullable Executor executor,
17056             @Nullable Consumer<Integer> resultListener) {
17057         if (resultListener != null) {
17058             Objects.requireNonNull(executor);
17059         }
17060 
17061         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
17062             @Override
17063             public void accept(int result) {
17064                 executor.execute(() ->
17065                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
17066             }
17067         };
17068 
17069         try {
17070             ITelephony telephony = getITelephony();
17071             if (telephony != null) {
17072                 telephony.setCallWaitingStatus(getSubId(), enabled, internalCallback);
17073             }
17074         } catch (RemoteException ex) {
17075             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
17076             ex.rethrowAsRuntimeException();
17077         } catch (NullPointerException ex) {
17078             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
17079             throw ex;
17080         }
17081     }
17082 
17083     /**
17084      * Controls whether mobile data  on the non-default SIM is allowed during a voice call.
17085      *
17086      * This is used for allowing data on the non-default data SIM when a voice call is placed on
17087      * the non-default data SIM on DSDS devices. If this policy is disabled, users will not be able
17088      * to use mobile data via the non-default data SIM during the call, which may mean no mobile
17089      * data at all since some modem implementations disallow mobile data via the default data SIM
17090      * during voice calls.
17091      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM
17092      * during any voice calls.
17093      *
17094      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
17095      * @hide
17096      */
17097     @SystemApi
17098     public static final int MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL = 1;
17099 
17100     /**
17101      * Controls whether MMS messages bypass the user-specified "mobile data" toggle.
17102      *
17103      * When enabled, requests for connections to the MMS APN will be accepted by telephony even if
17104      * the user has turned "mobile data" off on this specific sim card. {@link #isDataEnabledForApn}
17105      * will also return true for {@link ApnSetting#TYPE_MMS}.
17106      * When disabled, the MMS APN will be governed by the same rules as all other APNs.
17107      *
17108      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
17109      * @hide
17110      */
17111     @SystemApi
17112     public static final int MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED = 2;
17113 
17114     /**
17115      * Allow switching mobile data to the non-default SIM if the non-default SIM has better
17116      * availability.
17117      *
17118      * This is used for temporarily allowing data on the non-default data SIM when on-default SIM
17119      * has better availability on DSDS devices, where better availability means strong
17120      * signal/connectivity.
17121      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM,
17122      * including during any voice calls(equivalent to enabling
17123      * {@link #MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL}).
17124      *
17125      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
17126      * @hide
17127      */
17128     @SystemApi
17129     public static final int MOBILE_DATA_POLICY_AUTO_DATA_SWITCH = 3;
17130 
17131     /**
17132      * @hide
17133      */
17134     @IntDef(prefix = { "MOBILE_DATA_POLICY_" }, value = {
17135             MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL,
17136             MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED,
17137             MOBILE_DATA_POLICY_AUTO_DATA_SWITCH,
17138     })
17139     @Retention(RetentionPolicy.SOURCE)
17140     public @interface MobileDataPolicy { }
17141 
17142     /**
17143      * Enables or disables a piece of mobile data policy.
17144      *
17145      * Enables or disables the mobile data policy specified in {@code policy}. See the detailed
17146      * description of each policy constant for what they do.
17147      *
17148      * @param policy The data policy to enable.
17149      * @param enabled Whether to enable or disable the policy.
17150      *
17151      * @throws UnsupportedOperationException If the device does not have
17152      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
17153      * @hide
17154      */
17155     @SystemApi
17156     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17157     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
setMobileDataPolicyEnabled(@obileDataPolicy int policy, boolean enabled)17158     public void setMobileDataPolicyEnabled(@MobileDataPolicy int policy, boolean enabled) {
17159         try {
17160             ITelephony service = getITelephony();
17161             if (service != null) {
17162                 service.setMobileDataPolicyEnabled(getSubId(), policy, enabled);
17163             }
17164         } catch (RemoteException ex) {
17165             Rlog.e(TAG, "Telephony#setMobileDataPolicyEnabled RemoteException" + ex);
17166         }
17167     }
17168 
17169     /**
17170      * Fetches the status of a piece of mobile data policy.
17171      *
17172      * @param policy The data policy that you want the status for.
17173      * @return {@code true} if enabled, {@code false} otherwise.
17174      *
17175      * @throws UnsupportedOperationException If the device does not have
17176      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
17177      * @hide
17178      */
17179     @SystemApi
17180     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
17181     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isMobileDataPolicyEnabled(@obileDataPolicy int policy)17182     public boolean isMobileDataPolicyEnabled(@MobileDataPolicy int policy) {
17183         try {
17184             ITelephony service = getITelephony();
17185             if (service != null) {
17186                 return service.isMobileDataPolicyEnabled(getSubId(), policy);
17187             }
17188         } catch (RemoteException ex) {
17189             Rlog.e(TAG, "Telephony#isMobileDataPolicyEnabled RemoteException" + ex);
17190         }
17191         return false;
17192     }
17193 
17194     /**
17195      * Indicates that the ICC PIN lock state or PIN was changed successfully.
17196      * @hide
17197      */
17198     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
17199 
17200     /**
17201      * Check whether ICC PIN lock is enabled.
17202      * This is a sync call which returns the cached PIN enabled state.
17203      *
17204      * @return {@code true} if ICC PIN lock enabled, {@code false} if disabled.
17205      * @throws SecurityException if the caller doesn't have the permission.
17206      * @throws IllegalStateException if the Telephony process is not currently available.
17207      *
17208      * <p>Requires Permission:
17209      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
17210      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
17211      *
17212      * @throws UnsupportedOperationException If the device does not have
17213      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
17214      * @hide
17215      */
17216     @WorkerThread
17217     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
17218     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
17219     @SystemApi
isIccLockEnabled()17220     public boolean isIccLockEnabled() {
17221         try {
17222             ITelephony telephony = getITelephony();
17223             if (telephony != null) {
17224                 return telephony.isIccLockEnabled(getSubId());
17225             } else {
17226                 throw new IllegalStateException("telephony service is null.");
17227             }
17228         } catch (RemoteException e) {
17229             Log.e(TAG, "isIccLockEnabled RemoteException", e);
17230             e.rethrowFromSystemServer();
17231         }
17232         return false;
17233     }
17234 
17235     /**
17236      * Enable or disable the ICC PIN lock.
17237      *
17238      * @param enabled "true" for locked, "false" for unlocked.
17239      * @param pin needed to change the ICC PIN lock, aka. Pin1.
17240      * @return the result of enabling or disabling the ICC PIN lock.
17241      * @throws SecurityException if the caller doesn't have the permission.
17242      * @throws IllegalStateException if the Telephony process is not currently available.
17243      *
17244      * <p>Requires Permission:
17245      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
17246      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
17247      *
17248      * @throws UnsupportedOperationException If the device does not have
17249      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
17250      * @hide
17251      */
17252     @SystemApi
17253     @NonNull
17254     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17255     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
setIccLockEnabled(boolean enabled, @NonNull String pin)17256     public PinResult setIccLockEnabled(boolean enabled, @NonNull String pin) {
17257         checkNotNull(pin, "setIccLockEnabled pin can't be null.");
17258         try {
17259             ITelephony telephony = getITelephony();
17260             if (telephony != null) {
17261                 int result = telephony.setIccLockEnabled(getSubId(), enabled, pin);
17262                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
17263                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
17264                 } else if (result < 0) {
17265                     return PinResult.getDefaultFailedResult();
17266                 } else {
17267                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
17268                 }
17269             } else {
17270                 throw new IllegalStateException("telephony service is null.");
17271             }
17272         } catch (RemoteException e) {
17273             Log.e(TAG, "setIccLockEnabled RemoteException", e);
17274             e.rethrowFromSystemServer();
17275         }
17276         return PinResult.getDefaultFailedResult();
17277     }
17278 
17279     /**
17280      * Change the ICC lock PIN.
17281      *
17282      * @param oldPin is the old PIN
17283      * @param newPin is the new PIN
17284      * @return The result of changing the ICC lock PIN.
17285      * @throws SecurityException if the caller doesn't have the permission.
17286      * @throws IllegalStateException if the Telephony process is not currently available.
17287      *
17288      * <p>Requires Permission:
17289      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
17290      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
17291      *
17292      * @throws UnsupportedOperationException If the device does not have
17293      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
17294      * @hide
17295      */
17296     @SystemApi
17297     @NonNull
17298     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17299     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
changeIccLockPin(@onNull String oldPin, @NonNull String newPin)17300     public PinResult changeIccLockPin(@NonNull String oldPin, @NonNull String newPin) {
17301         checkNotNull(oldPin, "changeIccLockPin oldPin can't be null.");
17302         checkNotNull(newPin, "changeIccLockPin newPin can't be null.");
17303         try {
17304             ITelephony telephony = getITelephony();
17305             if (telephony != null) {
17306                 int result = telephony.changeIccLockPassword(getSubId(), oldPin, newPin);
17307                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
17308                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
17309                 } else if (result < 0) {
17310                     return PinResult.getDefaultFailedResult();
17311                 } else {
17312                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
17313                 }
17314             } else {
17315                 throw new IllegalStateException("telephony service is null.");
17316             }
17317         } catch (RemoteException e) {
17318             Log.e(TAG, "changeIccLockPin RemoteException", e);
17319             e.rethrowFromSystemServer();
17320         }
17321         return PinResult.getDefaultFailedResult();
17322     }
17323 
17324     /**
17325      * Called when userActivity is signalled in the power manager.
17326      * This should only be called from system Uid.
17327      * @hide
17328      */
17329     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
notifyUserActivity()17330     public void notifyUserActivity() {
17331         try {
17332             ITelephony service = getITelephony();
17333             if (service != null) {
17334                 service.userActivity();
17335             }
17336         } catch (RemoteException e) {
17337             // one-way notification, if telephony is not available, it is okay to not throw
17338             // exception here.
17339             Log.w(TAG, "notifyUserActivity exception: " + e.getMessage());
17340         }
17341     }
17342 
17343     /**
17344      * No error. Operation succeeded.
17345      * @hide
17346      */
17347     @SystemApi
17348     public static final int ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS = 0;
17349 
17350     /**
17351      * NR Dual connectivity enablement is not supported.
17352      * @hide
17353      */
17354     @SystemApi
17355     public static final int ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED = 1;
17356 
17357     /**
17358      * Radio is not available.
17359      * @hide
17360      */
17361     @SystemApi
17362     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE = 2;
17363 
17364     /**
17365      * Internal Radio error.
17366      * @hide
17367      */
17368     @SystemApi
17369     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR = 3;
17370 
17371     /**
17372      * Currently in invalid state. Not able to process the request.
17373      * @hide
17374      */
17375     @SystemApi
17376     public static final int ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE = 4;
17377 
17378     /** @hide */
17379     @Retention(RetentionPolicy.SOURCE)
17380     @IntDef(prefix = {"ENABLE_NR_DUAL_CONNECTIVITY"}, value = {
17381             ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS,
17382             ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED,
17383             ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE,
17384             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE,
17385             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR})
17386     public @interface EnableNrDualConnectivityResult {}
17387 
17388     /**
17389      * Enable NR dual connectivity. Enabled state does not mean dual connectivity
17390      * is active. It means device is allowed to connect to both primary and secondary.
17391      *
17392      * @hide
17393      */
17394     @SystemApi
17395     public static final int NR_DUAL_CONNECTIVITY_ENABLE = 1;
17396 
17397     /**
17398      * Disable NR dual connectivity. Disabled state does not mean the secondary cell is released.
17399      * Modem will release it only if the current bearer is released to avoid radio link failure.
17400      * @hide
17401      */
17402     @SystemApi
17403     public static final int NR_DUAL_CONNECTIVITY_DISABLE = 2;
17404 
17405     /**
17406      * Disable NR dual connectivity and force the secondary cell to be released if dual connectivity
17407      * was active. This will result in radio link failure.
17408      * @hide
17409      */
17410     @SystemApi
17411     public static final int NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE = 3;
17412 
17413     /**
17414      * @hide
17415      */
17416     @IntDef(prefix = { "NR_DUAL_CONNECTIVITY_" }, value = {
17417             NR_DUAL_CONNECTIVITY_ENABLE,
17418             NR_DUAL_CONNECTIVITY_DISABLE,
17419             NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE,
17420     })
17421     @Retention(RetentionPolicy.SOURCE)
17422     public @interface NrDualConnectivityState {
17423     }
17424 
17425     /**
17426      * Enable/Disable E-UTRA-NR Dual Connectivity.
17427      *
17428      * This api is supported only if
17429      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
17430      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
17431      * returns true.
17432      * @param nrDualConnectivityState expected NR dual connectivity state
17433      * This can be passed following states
17434      * <ol>
17435      * <li>Enable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_ENABLE}
17436      * <li>Disable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_DISABLE}
17437      * <li>Disable NR dual connectivity and force secondary cell to be released
17438      * {@link #NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE}
17439      * </ol>
17440      * @return operation result.
17441      * @throws IllegalStateException if the Telephony process is not currently available.
17442      * @throws UnsupportedOperationException If the device does not have
17443      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17444      * @hide
17445      */
17446     @SystemApi
17447     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17448     @RequiresFeature(
17449             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
17450             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
setNrDualConnectivityState( @rDualConnectivityState int nrDualConnectivityState)17451     public @EnableNrDualConnectivityResult int setNrDualConnectivityState(
17452             @NrDualConnectivityState int nrDualConnectivityState) {
17453         try {
17454             ITelephony telephony = getITelephony();
17455             if (telephony != null) {
17456                 return telephony.setNrDualConnectivityState(getSubId(), nrDualConnectivityState);
17457             } else {
17458                 throw new IllegalStateException("telephony service is null.");
17459             }
17460         } catch (RemoteException ex) {
17461             Rlog.e(TAG, "setNrDualConnectivityState RemoteException", ex);
17462             ex.rethrowFromSystemServer();
17463         }
17464 
17465         return ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE;
17466     }
17467 
17468     /**
17469      * Is E-UTRA-NR Dual Connectivity enabled.
17470      * This api is supported only if
17471      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
17472      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
17473      * returns true.
17474      * @return true if dual connectivity is enabled else false. Enabled state does not mean dual
17475      * connectivity is active. It means the device is allowed to connect to both primary and
17476      * secondary cell.
17477      * @throws IllegalStateException if the Telephony process is not currently available.
17478      * @throws UnsupportedOperationException If the device does not have
17479      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17480      * @hide
17481      */
17482     @SystemApi
17483     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
17484     @RequiresFeature(
17485             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
17486             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
isNrDualConnectivityEnabled()17487     public boolean isNrDualConnectivityEnabled() {
17488         try {
17489             ITelephony telephony = getITelephony();
17490             if (telephony != null) {
17491                 return telephony.isNrDualConnectivityEnabled(getSubId());
17492             } else {
17493                 throw new IllegalStateException("telephony service is null.");
17494             }
17495         } catch (RemoteException ex) {
17496             Rlog.e(TAG, "isNRDualConnectivityEnabled RemoteException", ex);
17497             ex.rethrowFromSystemServer();
17498         }
17499         return false;
17500     }
17501 
17502     private static class DeathRecipient implements IBinder.DeathRecipient {
17503         @Override
binderDied()17504         public void binderDied() {
17505             resetServiceCache();
17506         }
17507     }
17508 
17509    /**
17510     * Reset everything in the service cache; if one handle died then they are
17511     * all probably broken.
17512     * @hide
17513     */
resetServiceCache()17514     private static void resetServiceCache() {
17515         synchronized (sCacheLock) {
17516             if (sITelephony != null) {
17517                 sITelephony.asBinder().unlinkToDeath(sServiceDeath, 0);
17518                 sITelephony = null;
17519             }
17520             if (sISub != null) {
17521                 sISub.asBinder().unlinkToDeath(sServiceDeath, 0);
17522                 sISub = null;
17523                 SubscriptionManager.clearCaches();
17524             }
17525             if (sISms != null) {
17526                 sISms.asBinder().unlinkToDeath(sServiceDeath, 0);
17527                 sISms = null;
17528             }
17529             if (sIPhoneSubInfo != null) {
17530                 sIPhoneSubInfo.asBinder().unlinkToDeath(sServiceDeath, 0);
17531                 sIPhoneSubInfo = null;
17532             }
17533         }
17534     }
17535 
17536     /**
17537      * @hide
17538      */
getSubscriberInfoService()17539     static IPhoneSubInfo getSubscriberInfoService() {
17540         // Keeps cache disabled until test fixes are checked into AOSP.
17541         if (!sServiceHandleCacheEnabled) {
17542             return IPhoneSubInfo.Stub.asInterface(
17543                 TelephonyFrameworkInitializer
17544                         .getTelephonyServiceManager()
17545                         .getPhoneSubServiceRegisterer()
17546                         .get());
17547         }
17548 
17549         if (sIPhoneSubInfo == null) {
17550             IPhoneSubInfo temp = IPhoneSubInfo.Stub.asInterface(
17551                     TelephonyFrameworkInitializer
17552                         .getTelephonyServiceManager()
17553                         .getPhoneSubServiceRegisterer()
17554                         .get());
17555             synchronized (sCacheLock) {
17556                 if (sIPhoneSubInfo == null && temp != null) {
17557                     try {
17558                         sIPhoneSubInfo = temp;
17559                         sIPhoneSubInfo.asBinder().linkToDeath(sServiceDeath, 0);
17560                     } catch (Exception e) {
17561                         // something has gone horribly wrong
17562                         sIPhoneSubInfo = null;
17563                     }
17564                 }
17565             }
17566         }
17567         return sIPhoneSubInfo;
17568     }
17569 
17570    /**
17571     * @hide
17572     */
getSubscriptionService()17573     static ISub getSubscriptionService() {
17574         // Keeps cache disabled until test fixes are checked into AOSP.
17575         if (!sServiceHandleCacheEnabled) {
17576             return ISub.Stub.asInterface(
17577                     TelephonyFrameworkInitializer
17578                             .getTelephonyServiceManager()
17579                             .getSubscriptionServiceRegisterer()
17580                             .get());
17581         }
17582 
17583         if (sISub == null) {
17584             ISub temp = ISub.Stub.asInterface(
17585                     TelephonyFrameworkInitializer
17586                             .getTelephonyServiceManager()
17587                             .getSubscriptionServiceRegisterer()
17588                             .get());
17589             synchronized (sCacheLock) {
17590                 if (sISub == null && temp != null) {
17591                     try {
17592                         sISub = temp;
17593                         sISub.asBinder().linkToDeath(sServiceDeath, 0);
17594                     } catch (Exception e) {
17595                         // something has gone horribly wrong
17596                         sISub = null;
17597                     }
17598                 }
17599             }
17600         }
17601         return sISub;
17602     }
17603 
17604     /**
17605     * @hide
17606     */
getSmsService()17607     static ISms getSmsService() {
17608         // Keeps cache disabled until test fixes are checked into AOSP.
17609         if (!sServiceHandleCacheEnabled) {
17610             return ISms.Stub.asInterface(
17611                     TelephonyFrameworkInitializer
17612                             .getTelephonyServiceManager()
17613                             .getSmsServiceRegisterer()
17614                             .get());
17615         }
17616 
17617         if (sISms == null) {
17618             ISms temp = ISms.Stub.asInterface(
17619                     TelephonyFrameworkInitializer
17620                             .getTelephonyServiceManager()
17621                             .getSmsServiceRegisterer()
17622                             .get());
17623             synchronized (sCacheLock) {
17624                 if (sISms == null && temp != null) {
17625                     try {
17626                         sISms = temp;
17627                         sISms.asBinder().linkToDeath(sServiceDeath, 0);
17628                     } catch (Exception e) {
17629                         // something has gone horribly wrong
17630                         sISms = null;
17631                     }
17632                 }
17633             }
17634         }
17635         return sISms;
17636     }
17637 
17638     /**
17639      * Disables service handle caching for tests that utilize mock services.
17640      * @hide
17641      */
17642     @VisibleForTesting
disableServiceHandleCaching()17643     public static void disableServiceHandleCaching() {
17644         sServiceHandleCacheEnabled = false;
17645     }
17646 
17647     /**
17648      * Reenables service handle caching.
17649      * @hide
17650      */
17651     @VisibleForTesting
enableServiceHandleCaching()17652     public static void enableServiceHandleCaching() {
17653         sServiceHandleCacheEnabled = true;
17654     }
17655 
17656     /**
17657      * Setup sITelephony for testing.
17658      * @hide
17659      */
17660     @VisibleForTesting
setupITelephonyForTest(ITelephony telephony)17661     public static void setupITelephonyForTest(ITelephony telephony) {
17662         sITelephony = telephony;
17663     }
17664 
17665     /**
17666      * Setup sIPhoneSubInfo for testing.
17667      *
17668      * @hide
17669      */
17670     @VisibleForTesting
setupIPhoneSubInfoForTest(IPhoneSubInfo iPhoneSubInfo)17671     public static void setupIPhoneSubInfoForTest(IPhoneSubInfo iPhoneSubInfo) {
17672         synchronized (sCacheLock) {
17673             sIPhoneSubInfo = iPhoneSubInfo;
17674         }
17675     }
17676 
17677     /**
17678      * Setup sISub for testing.
17679      *
17680      * @hide
17681      */
17682     @VisibleForTesting
setupISubForTest(ISub iSub)17683     public static void setupISubForTest(ISub iSub) {
17684         synchronized (sCacheLock) {
17685             sISub = iSub;
17686         }
17687     }
17688 
17689     /**
17690      * Setup sISms for testing.
17691      *
17692      * @hide
17693      */
17694     @VisibleForTesting
setupISmsForTest(ISms iSms)17695     public static void setupISmsForTest(ISms iSms) {
17696         synchronized (sCacheLock) {
17697             sISms = iSms;
17698         }
17699     }
17700 
17701     /**
17702      * Whether device can connect to 5G network when two SIMs are active.
17703      *
17704      * @hide TODO b/153669716: remove or make system API.
17705      */
canConnectTo5GInDsdsMode()17706     public boolean canConnectTo5GInDsdsMode() {
17707         ITelephony telephony = getITelephony();
17708         if (telephony == null) return true;
17709         try {
17710             return telephony.canConnectTo5GInDsdsMode();
17711         } catch (RemoteException ex) {
17712             return true;
17713         } catch (NullPointerException ex) {
17714             return true;
17715         }
17716     }
17717 
17718     /**
17719      * Returns a list of the equivalent home PLMNs (EF_EHPLMN) from the USIM app.
17720      *
17721      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
17722      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
17723      *
17724      * @return A list of equivalent home PLMNs. Returns an empty list if EF_EHPLMN is empty or
17725      * does not exist on the SIM card.
17726      *
17727      * @throws IllegalStateException if the Telephony process is not currently available.
17728      * @throws SecurityException if the caller doesn't have the permission.
17729      * @throws UnsupportedOperationException If the device does not have
17730      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
17731      *
17732      */
17733     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
17734     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getEquivalentHomePlmns()17735     public @NonNull List<String> getEquivalentHomePlmns() {
17736         try {
17737             ITelephony telephony = getITelephony();
17738             if (telephony != null) {
17739                 return telephony.getEquivalentHomePlmns(getSubId(), mContext.getOpPackageName(),
17740                         getAttributionTag());
17741             } else {
17742                 throw new IllegalStateException("telephony service is null.");
17743             }
17744         } catch (RemoteException ex) {
17745             Rlog.e(TAG, "Telephony#getEquivalentHomePlmns RemoteException" + ex);
17746         }
17747 
17748         return Collections.emptyList();
17749     }
17750 
17751     /**
17752      * Indicates whether {@link CarrierBandwidth#getSecondaryDownlinkCapacityKbps()} and
17753      * {@link CarrierBandwidth#getSecondaryUplinkCapacityKbps()} are visible.  See comments
17754      * on respective methods for more information.
17755      *
17756      * @hide
17757      */
17758     @SystemApi
17759     public static final String CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE =
17760             "CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE";
17761 
17762     /**
17763      * Indicates whether {@link #setPreferredNetworkType}, {@link
17764      * #setPreferredNetworkTypeBitmask}, {@link #setAllowedNetworkTypes} and
17765      * {@link #setAllowedNetworkTypesForReason} rely on
17766      * setAllowedNetworkTypesBitmap instead of setPreferredNetworkTypesBitmap on the radio
17767      * interface.
17768      *
17769      * @hide
17770      */
17771     @SystemApi
17772     public static final String CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK =
17773             "CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK";
17774 
17775     /**
17776      * Indicates whether {@link #setNrDualConnectivityState()} and
17777      * {@link #isNrDualConnectivityEnabled()} ()} are available.  See comments
17778      * on respective methods for more information.
17779      *
17780      * @hide
17781      */
17782     @SystemApi
17783     public static final String CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE =
17784             "CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE";
17785 
17786     /**
17787      * Indicates whether a data throttling request sent with {@link #sendThermalMitigationRequest}
17788      * is supported. See comments on {@link #sendThermalMitigationRequest} for more information.
17789      *
17790      * @hide
17791      */
17792     @SystemApi
17793     public static final String CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING =
17794             "CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING";
17795 
17796     /**
17797      * Indicates whether {@link #getNetworkSlicingConfiguration} is supported. See comments on
17798      * respective methods for more information.
17799      */
17800     public static final String CAPABILITY_SLICING_CONFIG_SUPPORTED =
17801             "CAPABILITY_SLICING_CONFIG_SUPPORTED";
17802 
17803     /**
17804      * Indicates whether PHYSICAL_CHANNEL_CONFIG HAL1.6 is supported. See comments on
17805      * respective methods for more information.
17806      *
17807      * @hide
17808      */
17809     public static final String CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED =
17810             "CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED";
17811 
17812     /**
17813      * Indicates whether modem supports handling parsed SIM phonebook records through the RIL,
17814      * both batched reads and individual writes.
17815      *
17816      * @hide
17817      */
17818     public static final String CAPABILITY_SIM_PHONEBOOK_IN_MODEM =
17819             "CAPABILITY_SIM_PHONEBOOK_IN_MODEM";
17820 
17821     /**
17822      * A list of the radio interface capability values with public valid constants.
17823      *
17824      * Here is a related list for the systemapi-only valid constants:
17825      *     CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE
17826      *     CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK
17827      *     CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE
17828      *     CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING
17829      *
17830      * @hide
17831      * TODO(b/185508047): Doc generation for mixed public/systemapi StringDefs formats badly.
17832      */
17833     @Retention(RetentionPolicy.SOURCE)
17834     @StringDef(prefix = "CAPABILITY_", value = {
17835             CAPABILITY_SLICING_CONFIG_SUPPORTED,
17836             CAPABILITY_SIM_PHONEBOOK_IN_MODEM,
17837     })
17838     public @interface RadioInterfaceCapability {}
17839 
17840     /**
17841      * Whether the device supports a given capability on the radio interface.
17842      *
17843      * If the capability is not in the set of radio interface capabilities, false is returned.
17844      *
17845      * @param capability the name of the capability to check for
17846      * @return the availability of the capability
17847      *
17848      * @throws UnsupportedOperationException If the device does not have
17849      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17850      */
17851     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
isRadioInterfaceCapabilitySupported( @onNull @adioInterfaceCapability String capability)17852     public boolean isRadioInterfaceCapabilitySupported(
17853             @NonNull @RadioInterfaceCapability String capability) {
17854         try {
17855             if (capability == null) return false;
17856 
17857             ITelephony telephony = getITelephony();
17858             if (telephony != null) {
17859                 return telephony.isRadioInterfaceCapabilitySupported(capability);
17860             } else {
17861                 throw new IllegalStateException("telephony service is null.");
17862             }
17863         } catch (RemoteException ex) {
17864             Rlog.e(TAG, "Telephony#isRadioInterfaceCapabilitySupported RemoteException" + ex);
17865         }
17866         return false;
17867     }
17868 
17869     /**
17870      * Indicates that the thermal mitigation request was completed successfully.
17871      *
17872      * @hide
17873      */
17874     @SystemApi
17875     public static final int THERMAL_MITIGATION_RESULT_SUCCESS = 0;
17876 
17877     /**
17878      * Indicates that the thermal mitigation request was not completed because of a modem error.
17879      *
17880      * @hide
17881      */
17882     @SystemApi
17883     public static final int THERMAL_MITIGATION_RESULT_MODEM_ERROR = 1;
17884 
17885     /**
17886      * Indicates that the thermal mitigation request was not completed because the modem is not
17887      * available.
17888      *
17889      * @hide
17890      */
17891     @SystemApi
17892     public static final int THERMAL_MITIGATION_RESULT_MODEM_NOT_AVAILABLE = 2;
17893 
17894     /**
17895      * Indicates that the thermal mitigation request could not power off the radio due to the device
17896      * either being in an active emergency voice call, device pending an emergency call, or any
17897      * other state that would disallow powering off of radio.
17898      *
17899      * @hide
17900      */
17901     @SystemApi
17902     public static final int THERMAL_MITIGATION_RESULT_INVALID_STATE = 3;
17903 
17904     /**
17905      * Indicates that the thermal mitigation request resulted an unknown error.
17906      *
17907      * @hide
17908      */
17909     @SystemApi
17910     public static final int THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR = 4;
17911 
17912     /**
17913      * Thermal mitigation request to control functionalities at modem. Thermal mitigation is done
17914      * per-subscription. Caller must be sure to bind the TelephonyManager instance to subId by
17915      * calling {@link #createForSubscriptionId(int)} if they want thermal mitigation on a specific
17916      * subscription Id. Otherwise, TelephonyManager will use the default subscription.
17917      *
17918      * Calling this does not guarantee that the thermal mitigation action requested was done to
17919      * completion. A thermal module should actively monitor the temperature levels and request an
17920      * appropriate thermal mitigation action. Every action is assumed to be done 'on top of' the
17921      * previous action, where the order of actions from least thermal mitigation to most is as
17922      * follows:
17923      * <ol>
17924      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_DATA_THROTTLING}</li>
17925      *   <ol>
17926      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING}</li>
17927      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}</li>
17928      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER}</li>
17929      *   </ol>
17930      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY}</li>
17931      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}</li>
17932      * </ol>
17933      *
17934      * So, for example, requesting {@link
17935      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will ensure that the
17936      * data on secondary carrier has been disabled before throttling on primary carrier. {@link
17937      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} will ensure that data on both
17938      * primary and secondary have been disabled. {@link
17939      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF} will ensure that voice is
17940      * disabled and that data on both primary and secondary carriers are disabled before turning
17941      * radio off. {@link DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD} is not part of the order
17942      * and can be used at any time during data throttling to hold onto the current level of data
17943      * throttling.
17944      *
17945      * <p> If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}({@link
17946      * #CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING}) returns false, then sending a {@link
17947      * DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD}, {@link
17948      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}, or {@link
17949      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will result in {@link
17950      * IllegalArgumentException} being thrown. However, on devices that do not
17951      * support data throttling, {@link
17952      * DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING} can still be requested in
17953      * order to undo the mitigations above it (i.e {@link
17954      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} and/or {@link
17955      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}). </p>
17956      *
17957      * <p> In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of
17958      * this API must also be listed in the device configuration as an authorized app in
17959      * {@code packages/services/Telephony/res/values/config.xml} under the
17960      * {@code thermal_mitigation_allowlisted_packages} key. </p>
17961      *
17962      * @param thermalMitigationRequest Thermal mitigation request. See {@link
17963      * ThermalMitigationRequest} for details.
17964      *
17965      * @throws IllegalStateException if the Telephony process is not currently available.
17966      * @throws IllegalArgumentException if the thermalMitigationRequest had invalid parameters or
17967      * if the device's modem does not support data throttling.
17968      *
17969      * @throws UnsupportedOperationException If the device does not have
17970      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
17971      * @hide
17972      */
17973     @SystemApi
17974     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
17975     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
17976     @ThermalMitigationResult
sendThermalMitigationRequest( @onNull ThermalMitigationRequest thermalMitigationRequest)17977     public int sendThermalMitigationRequest(
17978             @NonNull ThermalMitigationRequest thermalMitigationRequest) {
17979         try {
17980             ITelephony telephony = getITelephony();
17981             if (telephony != null) {
17982                 return telephony.sendThermalMitigationRequest(getSubId(), thermalMitigationRequest,
17983                         getOpPackageName());
17984             }
17985             throw new IllegalStateException("telephony service is null.");
17986         } catch (RemoteException ex) {
17987             Log.e(TAG, "Telephony#thermalMitigationRequest RemoteException", ex);
17988             ex.rethrowFromSystemServer();
17989         }
17990         return THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR;
17991     }
17992 
17993     /**
17994      * Registers a callback object to receive notification of changes in specified telephony states.
17995      * <p>
17996      * To register a callback, pass a {@link TelephonyCallback} which implements
17997      * interfaces of events. For example,
17998      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
17999      * {@link TelephonyCallback.ServiceStateListener}.
18000      *
18001      * At registration, and when a specified telephony state changes, the telephony manager invokes
18002      * the appropriate callback method on the callback object and passes the current (updated)
18003      * values.
18004      * <p>
18005      * Note: Be aware of the permission requirements stated on the {@link TelephonyCallback}
18006      * listeners you implement.  Your application must be granted these permissions in order to
18007      * register a {@link TelephonyCallback} which requires them; a {@link SecurityException} will be
18008      * thrown if you do not hold the required permissions for all {@link TelephonyCallback}
18009      * listeners you implement.
18010      * <p>
18011      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
18012      * applies to the given subId. Otherwise, applies to
18013      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
18014      * subIds, pass a separate callback object to each TelephonyManager object created with
18015      * {@link #createForSubscriptionId}.
18016      *
18017      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
18018      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
18019      * {@link SecurityException} will be thrown otherwise.
18020      *
18021      * This API should be used sparingly -- large numbers of callbacks will cause system
18022      * instability. If a process has registered too many callbacks without unregistering them, it
18023      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
18024      *
18025      * @param executor The executor of where the callback will execute.
18026      * @param callback The {@link TelephonyCallback} object to register. The caller should hold a
18027      * reference to the callback. The framework only holds a weak reference.
18028      */
registerTelephonyCallback(@onNull @allbackExecutor Executor executor, @NonNull TelephonyCallback callback)18029     public void registerTelephonyCallback(@NonNull @CallbackExecutor Executor executor,
18030             @NonNull TelephonyCallback callback) {
18031         registerTelephonyCallback(getLocationData(), executor, callback);
18032     }
18033 
getLocationData()18034     private int getLocationData() {
18035         boolean renounceCoarseLocation =
18036                 getRenouncedPermissions().contains(Manifest.permission.ACCESS_COARSE_LOCATION);
18037         boolean renounceFineLocation =
18038                 getRenouncedPermissions().contains(Manifest.permission.ACCESS_FINE_LOCATION);
18039         if (renounceCoarseLocation) {
18040             return INCLUDE_LOCATION_DATA_NONE;
18041         } else if (renounceFineLocation) {
18042             return INCLUDE_LOCATION_DATA_COARSE;
18043         } else {
18044             return INCLUDE_LOCATION_DATA_FINE;
18045         }
18046     }
18047 
18048     /** @hide */
18049     @Retention(RetentionPolicy.SOURCE)
18050     @IntDef(prefix = {"INCLUDE_LOCATION_DATA_"}, value = {
18051             INCLUDE_LOCATION_DATA_NONE,
18052             INCLUDE_LOCATION_DATA_COARSE,
18053             INCLUDE_LOCATION_DATA_FINE})
18054     public @interface IncludeLocationData {}
18055 
18056     /**
18057      * Specifies to not include any location related data.
18058      *
18059      * Indicates whether the caller would not like to receive
18060      * location related information which will be sent if the caller already possess
18061      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the
18062      * permissions.
18063      */
18064     public static final int INCLUDE_LOCATION_DATA_NONE = 0;
18065 
18066     /**
18067      * Include coarse location data.
18068      *
18069      * Indicates whether the caller would not like to receive
18070      * location related information which will be sent if the caller already possess
18071      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and do not renounce the
18072      * permissions.
18073      */
18074     public static final int INCLUDE_LOCATION_DATA_COARSE = 1;
18075 
18076     /**
18077      * Include fine location data.
18078      *
18079      * Indicates whether the caller would not like to receive
18080      * location related information which will be sent if the caller already possess
18081      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and do not renounce the
18082      * permissions.
18083      */
18084     public static final int INCLUDE_LOCATION_DATA_FINE = 2;
18085 
18086     /**
18087      * Registers a callback object to receive notification of changes in specified telephony states.
18088      * <p>
18089      * To register a callback, pass a {@link TelephonyCallback} which implements
18090      * interfaces of events. For example,
18091      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
18092      * {@link TelephonyCallback.ServiceStateListener}.
18093      *
18094      * At registration, and when a specified telephony state changes, the telephony manager invokes
18095      * the appropriate callback method on the callback object and passes the current (updated)
18096      * values.
18097      * <p>
18098      *
18099      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
18100      * applies to the given subId. Otherwise, applies to
18101      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
18102      * subIds, pass a separate callback object to each TelephonyManager object created with
18103      * {@link #createForSubscriptionId}.
18104      *
18105      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
18106      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
18107      * {@link SecurityException} will be thrown otherwise.
18108      *
18109      * This API should be used sparingly -- large numbers of callbacks will cause system
18110      * instability. If a process has registered too many callbacks without unregistering them, it
18111      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
18112      *
18113      * <p>
18114      * There's another way to renounce permissions with a custom context
18115      * {@code AttributionSource.Builder#setRenouncedPermissions(Set<String>)} but only for system
18116      * apps. To avoid confusion, calling this method supersede renouncing permissions with a
18117      * custom context.
18118      *
18119      * @param includeLocationData Specifies if the caller would like to receive
18120      * location related information.
18121      * @param executor The executor of where the callback will execute.
18122      * @param callback The {@link TelephonyCallback} object to register. The caller should hold a
18123      * reference to the callback. The framework only holds a weak reference.
18124      */
registerTelephonyCallback(@ncludeLocationData int includeLocationData, @NonNull @CallbackExecutor Executor executor, @NonNull TelephonyCallback callback)18125     public void registerTelephonyCallback(@IncludeLocationData int includeLocationData,
18126             @NonNull @CallbackExecutor Executor executor,
18127             @NonNull TelephonyCallback callback) {
18128         if (mContext == null) {
18129             throw new IllegalStateException("telephony service is null.");
18130         }
18131 
18132         if (executor == null || callback == null) {
18133             throw new IllegalArgumentException("TelephonyCallback and executor must be non-null");
18134         }
18135         mTelephonyRegistryMgr = (TelephonyRegistryManager)
18136                 mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
18137         if (mTelephonyRegistryMgr != null) {
18138             mTelephonyRegistryMgr.registerTelephonyCallback(
18139                     includeLocationData != INCLUDE_LOCATION_DATA_FINE,
18140                     includeLocationData == INCLUDE_LOCATION_DATA_NONE,
18141                     executor, mSubId, getOpPackageName(),
18142                     getAttributionTag(), callback, getITelephony() != null);
18143         } else {
18144             throw new IllegalStateException("telephony service is null.");
18145         }
18146     }
18147 
18148     /**
18149      * Unregister an existing {@link TelephonyCallback}.
18150      *
18151      * @param callback The {@link TelephonyCallback} object to unregister.
18152      */
unregisterTelephonyCallback(@onNull TelephonyCallback callback)18153     public void unregisterTelephonyCallback(@NonNull TelephonyCallback callback) {
18154 
18155         if (mContext == null) {
18156             throw new IllegalStateException("telephony service is null.");
18157         }
18158 
18159         if (callback.callback == null) {
18160             return;
18161         }
18162 
18163         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
18164         if (mTelephonyRegistryMgr != null) {
18165             mTelephonyRegistryMgr.unregisterTelephonyCallback(mSubId, getOpPackageName(),
18166                     getAttributionTag(), callback, getITelephony() != null);
18167         } else {
18168             throw new IllegalStateException("telephony service is null.");
18169         }
18170     }
18171 
18172     /** @hide */
18173     @Retention(RetentionPolicy.SOURCE)
18174     @IntDef(prefix = {"GBA_FAILURE_REASON_"}, value = {
18175             GBA_FAILURE_REASON_UNKNOWN,
18176             GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED,
18177             GBA_FAILURE_REASON_FEATURE_NOT_READY,
18178             GBA_FAILURE_REASON_NETWORK_FAILURE,
18179             GBA_FAILURE_REASON_INCORRECT_NAF_ID,
18180             GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED})
18181     public @interface AuthenticationFailureReason {}
18182 
18183     /**
18184      * GBA Authentication has failed for an unknown reason.
18185      *
18186      * <p>The caller should retry a message that failed with this response.
18187      * @hide
18188      */
18189     @SystemApi
18190     public static final int GBA_FAILURE_REASON_UNKNOWN = 0;
18191 
18192     /**
18193      * GBA Authentication is not supported by the carrier, SIM or android.
18194      *
18195      * <p>Application should use other authentication mechanisms if possible.
18196      * @hide
18197      */
18198     @SystemApi
18199     public static final int GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED = 1;
18200 
18201     /**
18202      * GBA Authentication service is not ready for use.
18203      *
18204      * <p>Application could try again at a later time.
18205      * @hide
18206      */
18207     @SystemApi
18208     public static final int GBA_FAILURE_REASON_FEATURE_NOT_READY = 2;
18209 
18210     /**
18211      * GBA Authentication has been failed by the network.
18212      * @hide
18213      */
18214     @SystemApi
18215     public static final int GBA_FAILURE_REASON_NETWORK_FAILURE = 3;
18216 
18217     /**
18218      * GBA Authentication has failed due to incorrect NAF URL.
18219      * @hide
18220      */
18221     @SystemApi
18222     public static final int GBA_FAILURE_REASON_INCORRECT_NAF_ID = 4;
18223 
18224     /**
18225      * GBA Authentication has failed due to unsupported security protocol
18226      * @hide
18227      */
18228     @SystemApi
18229     public static final int GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED = 5;
18230 
18231     /**
18232      * The callback associated with a {@link #bootstrapAuthenticationRequest()}.
18233      * @hide
18234      */
18235     @SystemApi
18236     public static class BootstrapAuthenticationCallback {
18237 
18238         /**
18239          * Invoked when the previously requested GBA keys are available (@see
18240          * bootstrapAuthenticationRequest()).
18241          * @param gbaKey Ks_NAF/Ks_ext_NAF Response
18242          * @param transactionId Bootstrapping Transaction Identifier
18243          */
onKeysAvailable(@onNull byte[] gbaKey, @NonNull String transactionId)18244         public void onKeysAvailable(@NonNull byte[] gbaKey, @NonNull String transactionId) {}
18245 
18246         /**
18247          * @param reason The reason for the authentication failure.
18248          */
onAuthenticationFailure(@uthenticationFailureReason int reason)18249         public void onAuthenticationFailure(@AuthenticationFailureReason int reason) {}
18250     }
18251 
18252     /**
18253      * Used to get the Generic Bootstrapping Architecture authentication keys
18254      * KsNAF/Ks_ext_NAF for a particular NAF as defined in 3GPP spec TS 33.220 for
18255      * the specified sub id.
18256      *
18257      * <p>Application must be prepared to wait for receiving the Gba keys through the
18258      * registered callback and not invoke the API on the main application thread.
18259      * Application also must call the api to get the fresh key every time instead
18260      * of caching the key.
18261      *
18262      * Following steps may be invoked on the API call depending on the state of the
18263      * underlying GBA implementation:
18264      * <ol>
18265      *     <li>Resolve and bind to a Gba implementation.</li>
18266      *     <li>Run bootstrapping if no valid keys are available or bootstrapping is forced.</li>
18267      *     <li>Generate the ks_NAF/ ks_Ext_NAF to be returned via the callback.</li>
18268      * </ol>
18269      *
18270      * <p> Requires Permission:
18271      * <ul>
18272      *     <li>{@link android.Manifest.permission#MODIFY_PHONE_STATE},</li>
18273      *     <li>{@link android.Manifest.permission#PERFORM_IMS_SINGLE_REGISTRATION},</li>
18274      *     <li>or that the caller has carrier privileges (see
18275      *         {@link TelephonyManager#hasCarrierPrivileges()}).</li>
18276      * </ul>
18277      * @param appType icc application type, like {@link #APPTYPE_USIM} or {@link
18278      * #APPTYPE_ISIM} or {@link#APPTYPE_UNKNOWN}
18279      * @param nafId A URI to specify Network Application Function(NAF) fully qualified domain
18280      * name (FQDN) and the selected GBA mode. The authority of the URI must contain two parts
18281      * delimited by "@" sign. The first part is the constant string "3GPP-bootstrapping" (GBA_ME),
18282      * "3GPP-bootstrapping-uicc" (GBA_ U), or "3GPP-bootstrapping-digest" (GBA_Digest).
18283      * The second part shall be the FQDN of the NAF. The scheme of the URI is not actually used
18284      * for the authentication, which may be set the same as the resource that the application is
18285      * going to access. For example, the nafId can be
18286      * "https://3GPP-bootstrapping@naf1.operator.com",
18287      * "https://3GPP-bootstrapping-uicc@naf1.operator.com",
18288      * "https://3GPP-bootstrapping-digest@naf1.operator.com",
18289      * "ftps://3GPP-bootstrapping-digest@naf1.operator.com".
18290      * @param securityProtocol Security protocol identifier between UE and NAF.  See
18291      * 3GPP TS 33.220 Annex H. Application can use
18292      * {@link UaSecurityProtocolIdentifier#createDefaultUaSpId},
18293      * {@link UaSecurityProtocolIdentifier#create3GppUaSpId},
18294      * to create the ua security protocol identifier as needed
18295      * @param forceBootStrapping true=force bootstrapping, false=do not force
18296      * bootstrapping. Bootstrapping shouldn't be forced unless the application sees
18297      * authentication errors from the server.
18298      * @param e The {@link Executor} that will be used to call the Gba callback.
18299      * @param callback A callback called on the supplied {@link Executor} that will
18300      * contain the GBA Ks_NAF/Ks_ext_NAF when available. If the NAF keys are
18301      * available and valid at the time of call and bootstrapping is not requested,
18302      * then the callback shall be invoked with the available keys.
18303      *
18304      * @throws UnsupportedOperationException If the device does not have
18305      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
18306      * @hide
18307      */
18308     @SystemApi
18309     @WorkerThread
18310     @RequiresPermission(anyOf = {android.Manifest.permission.MODIFY_PHONE_STATE,
18311             Manifest.permission.PERFORM_IMS_SINGLE_REGISTRATION})
18312     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
bootstrapAuthenticationRequest( @iccAppTypeExt int appType, @NonNull Uri nafId, @NonNull UaSecurityProtocolIdentifier securityProtocol, boolean forceBootStrapping, @NonNull Executor e, @NonNull BootstrapAuthenticationCallback callback)18313     public void bootstrapAuthenticationRequest(
18314             @UiccAppTypeExt int appType, @NonNull Uri nafId,
18315             @NonNull UaSecurityProtocolIdentifier securityProtocol,
18316             boolean forceBootStrapping, @NonNull Executor e,
18317             @NonNull BootstrapAuthenticationCallback callback) {
18318         try {
18319             ITelephony service = getITelephony();
18320             if (service == null) {
18321                 e.execute(() -> callback.onAuthenticationFailure(
18322                         GBA_FAILURE_REASON_FEATURE_NOT_READY));
18323                 return;
18324             }
18325             service.bootstrapAuthenticationRequest(
18326                     getSubId(), appType, nafId, securityProtocol, forceBootStrapping,
18327                     new IBootstrapAuthenticationCallback.Stub() {
18328                         @Override
18329                         public void onKeysAvailable(int token, byte[] gbaKey,
18330                                 String transactionId) {
18331                             final long identity = Binder.clearCallingIdentity();
18332                             try {
18333                                 e.execute(() -> callback.onKeysAvailable(gbaKey, transactionId));
18334                             } finally {
18335                                 Binder.restoreCallingIdentity(identity);
18336                             }
18337                         }
18338 
18339                         @Override
18340                         public void onAuthenticationFailure(int token, int reason) {
18341                             final long identity = Binder.clearCallingIdentity();
18342                             try {
18343                                 e.execute(() -> callback.onAuthenticationFailure(reason));
18344                             } finally {
18345                                 Binder.restoreCallingIdentity(identity);
18346                             }
18347                         }
18348                     });
18349         } catch (RemoteException exception) {
18350             Log.e(TAG, "Error calling ITelephony#bootstrapAuthenticationRequest", exception);
18351             e.execute(() -> callback.onAuthenticationFailure(GBA_FAILURE_REASON_FEATURE_NOT_READY));
18352         }
18353     }
18354 
18355     /**
18356      * The network type is valid or not.
18357      *
18358      * @param networkType The network type {@link NetworkType}.
18359      * @return {@code true} if valid, {@code false} otherwise.
18360      *
18361      * @hide
18362      */
isNetworkTypeValid(@etworkType int networkType)18363     public static boolean isNetworkTypeValid(@NetworkType int networkType) {
18364         return networkType >= TelephonyManager.NETWORK_TYPE_UNKNOWN &&
18365                 networkType <= TelephonyManager.NETWORK_TYPE_NR;
18366     }
18367 
18368     /**
18369      * Set a {@link SignalStrengthUpdateRequest} to receive notification when signal quality
18370      * measurements breach the specified thresholds.
18371      *
18372      * To be notified, set the signal strength update request and then register
18373      * {@link TelephonyCallback} that implements {@link TelephonyCallback.SignalStrengthsListener}
18374      * through {@link #registerTelephonyCallback}. The notification will arrive through
18375      * {@link TelephonyCallback.SignalStrengthsListener#onSignalStrengthsChanged(SignalStrength)}.
18376      *
18377      * To stop receiving the notification over the specified thresholds, pass the same
18378      * {@link SignalStrengthUpdateRequest} object to
18379      * {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
18380      *
18381      * System will clean up the {@link SignalStrengthUpdateRequest} if the caller process died
18382      * without calling {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
18383      *
18384      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
18385      * applies to the given subId. Otherwise, applies to
18386      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To request for multiple subIds,
18387      * pass a request object to each TelephonyManager object created with
18388      * {@link #createForSubscriptionId}.
18389      *
18390      * <p>Requires Permission:
18391      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
18392      * or that the calling app has carrier privileges (see
18393      * {@link TelephonyManager#hasCarrierPrivileges}).
18394      *
18395      * Note that the thresholds in the request will be used on a best-effort basis; the system may
18396      * modify requests to multiplex various request sources or to optimize power consumption. The
18397      * caller should not expect to be notified with the exactly the same thresholds.
18398      *
18399      * @see #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
18400      *
18401      * @param request the SignalStrengthUpdateRequest to be set into the System
18402      *
18403      * @throws IllegalStateException if a new request is set with same subId from the same caller
18404      * @throws UnsupportedOperationException If the device does not have
18405      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
18406      */
18407     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
18408     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
18409     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
setSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)18410     public void setSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
18411         Objects.requireNonNull(request, "request must not be null");
18412 
18413         try {
18414             ITelephony service = getITelephony();
18415             if (service != null) {
18416                 service.setSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
18417             }
18418         } catch (RemoteException e) {
18419             Log.e(TAG, "Error calling ITelephony#setSignalStrengthUpdateRequest", e);
18420         }
18421     }
18422 
18423     /**
18424      * Clear a {@link SignalStrengthUpdateRequest} from the system.
18425      *
18426      * <p>Requires Permission:
18427      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
18428      * or that the calling app has carrier privileges (see
18429      * {@link TelephonyManager#hasCarrierPrivileges}).
18430      *
18431      * <p>If the given request was not set before, this operation is a no-op.
18432      *
18433      * @see #setSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
18434      *
18435      * @param request the SignalStrengthUpdateRequest to be cleared from the System
18436      *
18437      * @throws UnsupportedOperationException If the device does not have
18438      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
18439      */
18440     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
18441     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
18442     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS)
clearSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)18443     public void clearSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
18444         Objects.requireNonNull(request, "request must not be null");
18445 
18446         try {
18447             ITelephony service = getITelephony();
18448             if (service != null) {
18449                 service.clearSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
18450             }
18451         } catch (RemoteException e) {
18452             Log.e(TAG, "Error calling ITelephony#clearSignalStrengthUpdateRequest", e);
18453         }
18454     }
18455 
18456     /**
18457      * Gets the current phone capability.
18458      *
18459      * @return the PhoneCapability which describes the data connection capability of modem.
18460      * It's used to evaluate possible phone config change, for example from single
18461      * SIM device to multi-SIM device.
18462      *
18463      * @throws UnsupportedOperationException If the device does not have
18464      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
18465      * @hide
18466      */
18467     @SystemApi
18468     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
18469     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
getPhoneCapability()18470     public @NonNull PhoneCapability getPhoneCapability() {
18471         try {
18472             ITelephony telephony = getITelephony();
18473             if (telephony != null) {
18474                 return telephony.getPhoneCapability();
18475             } else {
18476                 throw new IllegalStateException("telephony service is null.");
18477             }
18478         } catch (RemoteException ex) {
18479             ex.rethrowAsRuntimeException();
18480         }
18481         if (getActiveModemCount() > 1) {
18482             return PhoneCapability.DEFAULT_DSDS_CAPABILITY;
18483         } else {
18484             return PhoneCapability.DEFAULT_SSSS_CAPABILITY;
18485         }
18486     }
18487 
18488     /**
18489      * The unattended reboot was prepared successfully.
18490      * @hide
18491      */
18492     @SystemApi
18493     public static final int PREPARE_UNATTENDED_REBOOT_SUCCESS = 0;
18494 
18495     /**
18496      * The unattended reboot was prepared, but the user will need to manually
18497      * enter the PIN code of at least one SIM card present in the device.
18498      * @hide
18499      */
18500     @SystemApi
18501     public static final int PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED = 1;
18502 
18503     /**
18504      * The unattended reboot was not prepared due to a non-recoverable error. After this error,
18505      * the client that manages the unattended reboot should not try to invoke the API again
18506      * until the next power cycle.
18507      * @hide
18508      */
18509     @SystemApi
18510     public static final int PREPARE_UNATTENDED_REBOOT_ERROR = 2;
18511 
18512     /** @hide */
18513     @Retention(RetentionPolicy.SOURCE)
18514     @IntDef(prefix = {"PREPARE_UNATTENDED_REBOOT_"},
18515             value = {
18516                     PREPARE_UNATTENDED_REBOOT_SUCCESS,
18517                     PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED,
18518                     PREPARE_UNATTENDED_REBOOT_ERROR
18519             })
18520     public @interface PrepareUnattendedRebootResult {}
18521 
18522     /**
18523      * Prepare TelephonyManager for an unattended reboot. The reboot is required to be done
18524      * shortly (e.g. within 15 seconds) after the API is invoked.
18525      *
18526      * <p>Requires Permission:
18527      *   {@link android.Manifest.permission#REBOOT}
18528      *
18529      * @return {@link #PREPARE_UNATTENDED_REBOOT_SUCCESS} in case of success.
18530      * {@link #PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED} if the device contains
18531      * at least one SIM card for which the user needs to manually enter the PIN
18532      * code after the reboot. {@link #PREPARE_UNATTENDED_REBOOT_ERROR} in case
18533      * of error.
18534      *
18535      * @throws UnsupportedOperationException If the device does not have
18536      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
18537      * @hide
18538      */
18539     @SystemApi
18540     @RequiresPermission(android.Manifest.permission.REBOOT)
18541     @PrepareUnattendedRebootResult
18542     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
prepareForUnattendedReboot()18543     public int prepareForUnattendedReboot() {
18544         try {
18545             ITelephony service = getITelephony();
18546             if (service != null) {
18547                 return service.prepareForUnattendedReboot();
18548             }
18549         } catch (RemoteException e) {
18550             Log.e(TAG, "Telephony#prepareForUnattendedReboot RemoteException", e);
18551             e.rethrowFromSystemServer();
18552         }
18553         return PREPARE_UNATTENDED_REBOOT_ERROR;
18554     }
18555 
18556     /**
18557      * Exception that may be supplied to the callback in {@link #getNetworkSlicingConfiguration} if
18558      * something goes awry.
18559      */
18560     public static class NetworkSlicingException extends Exception {
18561         /**
18562          * Getting the current slicing configuration successfully. Used internally only.
18563          * @hide
18564          */
18565         public static final int SUCCESS = 0;
18566 
18567         /**
18568          * The system timed out waiting for a response from the Radio.
18569          * @hide
18570          */
18571         public static final int ERROR_TIMEOUT = 1;
18572 
18573         /**
18574          * The modem returned a failure.
18575          * @hide
18576          */
18577         public static final int ERROR_MODEM_ERROR = 2;
18578 
18579         /** @hide */
18580         @IntDef(prefix = {"ERROR_"}, value = {
18581                 ERROR_TIMEOUT,
18582                 ERROR_MODEM_ERROR,
18583         })
18584         @Retention(RetentionPolicy.SOURCE)
18585         public @interface NetworkSlicingError {}
18586 
18587         private final int mErrorCode;
18588 
18589         /** @hide */
NetworkSlicingException(@etworkSlicingError int errorCode)18590         public NetworkSlicingException(@NetworkSlicingError int errorCode) {
18591             mErrorCode = errorCode;
18592         }
18593 
18594         @Override
toString()18595         public String toString() {
18596             switch (mErrorCode) {
18597                 case ERROR_TIMEOUT: return "ERROR_TIMEOUT";
18598                 case ERROR_MODEM_ERROR: return "ERROR_MODEM_ERROR";
18599                 default: return "UNDEFINED";
18600             }
18601         }
18602     }
18603 
18604     /**
18605      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
18606      * system timed out waiting for a response from the Radio.
18607      */
18608     public class TimeoutException extends NetworkSlicingException {
18609         /** @hide */
TimeoutException(int errorCode)18610         public TimeoutException(int errorCode) {
18611             super(errorCode);
18612         }
18613     }
18614 
18615     /**
18616      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
18617      * modem returned a failure.
18618      */
18619     public class ModemErrorException extends NetworkSlicingException {
18620         /** @hide */
ModemErrorException(int errorCode)18621         public ModemErrorException(int errorCode) {
18622             super(errorCode);
18623         }
18624     }
18625 
18626     /** @hide */
18627     public static final String KEY_SLICING_CONFIG_HANDLE = "slicing_config_handle";
18628 
18629     /**
18630      * Request to get the current slicing configuration including URSP rules and
18631      * NSSAIs (configured, allowed and rejected).
18632      *
18633      * This method can be invoked if one of the following requirements is met:
18634      * <ul>
18635      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
18636      *     is a privileged permission that can only be granted to apps preloaded on the device.
18637      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
18638      * </ul>
18639      *
18640      * This will be invalid if the device does not support
18641      * android.telephony.TelephonyManager#CAPABILITY_SLICING_CONFIG_SUPPORTED.
18642      *
18643      * @param executor the executor on which callback will be invoked.
18644      * @param callback a callback to receive the current slicing configuration.
18645      *
18646      * @throws UnsupportedOperationException If the device does not have
18647      *          {@link PackageManager#FEATURE_TELEPHONY_RADIO_ACCESS}.
18648      */
18649     @RequiresFeature(
18650             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
18651             value = TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED)
18652     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
18653     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNetworkSlicingConfiguration( @onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback)18654     public void getNetworkSlicingConfiguration(
18655             @NonNull @CallbackExecutor Executor executor,
18656             @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback) {
18657         Objects.requireNonNull(executor);
18658         Objects.requireNonNull(callback);
18659 
18660         try {
18661             ITelephony telephony = getITelephony();
18662             if (telephony == null) {
18663                 throw new IllegalStateException("telephony service is null.");
18664             }
18665             telephony.getSlicingConfig(new ResultReceiver(null) {
18666                     @Override
18667                     protected void onReceiveResult(int resultCode, Bundle result) {
18668                         if (resultCode == NetworkSlicingException.ERROR_TIMEOUT) {
18669                             executor.execute(() -> callback.onError(
18670                                     new TimeoutException(resultCode)));
18671                             return;
18672                         } else if (resultCode == NetworkSlicingException.ERROR_MODEM_ERROR) {
18673                             executor.execute(() -> callback.onError(
18674                                     new ModemErrorException(resultCode)));
18675                             return;
18676                         }
18677 
18678                         NetworkSlicingConfig slicingConfig =
18679                                 result.getParcelable(KEY_SLICING_CONFIG_HANDLE, android.telephony.data.NetworkSlicingConfig.class);
18680                         executor.execute(() -> callback.onResult(slicingConfig));
18681                     }
18682             });
18683         } catch (RemoteException ex) {
18684             ex.rethrowAsRuntimeException();
18685         }
18686     }
18687 
18688     /**
18689      * A premium capability that boosts the network to allow for real-time interactive traffic
18690      * by prioritizing low latency communication.
18691      * Corresponds to {@link NetworkCapabilities#NET_CAPABILITY_PRIORITIZE_LATENCY}.
18692      */
18693     public static final int PREMIUM_CAPABILITY_PRIORITIZE_LATENCY =
18694             NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY;
18695 
18696     /**
18697      * Purchasable premium capabilities.
18698      * @hide
18699      */
18700     @Retention(RetentionPolicy.SOURCE)
18701     @IntDef(prefix = { "PREMIUM_CAPABILITY_" }, value = {
18702             PREMIUM_CAPABILITY_PRIORITIZE_LATENCY})
18703     public @interface PremiumCapability {}
18704 
18705     /**
18706      * Returns the premium capability {@link PremiumCapability} as a String.
18707      *
18708      * @param capability The premium capability.
18709      * @return The premium capability as a String.
18710      * @hide
18711      */
convertPremiumCapabilityToString(@remiumCapability int capability)18712     public static String convertPremiumCapabilityToString(@PremiumCapability int capability) {
18713         switch (capability) {
18714             case PREMIUM_CAPABILITY_PRIORITIZE_LATENCY:
18715                 return "PRIORITIZE_LATENCY";
18716             default:
18717                 return "UNKNOWN (" + capability + ")";
18718         }
18719     }
18720 
18721     /**
18722      * Check whether the given premium capability is available for purchase from the carrier.
18723      * If this is {@code true}, the capability can be purchased from the carrier using
18724      * {@link #purchasePremiumCapability(int, Executor, Consumer)}.
18725      *
18726      * @param capability The premium capability to check.
18727      * @return Whether the given premium capability is available to purchase.
18728      * @throws SecurityException if the caller does not hold permission READ_BASIC_PHONE_STATE.
18729      * @throws UnsupportedOperationException If the device does not have
18730      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
18731      */
18732     @RequiresPermission(android.Manifest.permission.READ_BASIC_PHONE_STATE)
18733     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
isPremiumCapabilityAvailableForPurchase(@remiumCapability int capability)18734     public boolean isPremiumCapabilityAvailableForPurchase(@PremiumCapability int capability) {
18735         try {
18736             ITelephony telephony = getITelephony();
18737             if (telephony == null) {
18738                 throw new IllegalStateException("telephony service is null.");
18739             }
18740             return telephony.isPremiumCapabilityAvailableForPurchase(capability, getSubId());
18741         } catch (RemoteException ex) {
18742             ex.rethrowAsRuntimeException();
18743         }
18744         return false;
18745     }
18746 
18747     /**
18748      * Purchase premium capability request was successful.
18749      * Once the purchase result is successful, the network must set up a slicing configuration
18750      * for the purchased premium capability within the timeout specified by
18751      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NETWORK_SETUP_TIME_MILLIS_LONG}.
18752      * During the setup time, subsequent attempts will return
18753      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP}.
18754      * After setup is complete, subsequent attempts will return
18755      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED} until the boost expires.
18756      * The expiry time is determined by the type or duration of boost purchased from the carrier,
18757      * provided at {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_PURCHASE_URL_STRING}.
18758      */
18759     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS = 1;
18760 
18761     /**
18762      * Purchase premium capability failed because the request is throttled.
18763      * If purchasing premium capabilities is throttled, it will be for the amount of time
18764      * specified by {@link CarrierConfigManager
18765      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}.
18766      * If displaying the performance boost notification is throttled, it will be for the amount of
18767      * time specified by {@link CarrierConfigManager
18768      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}.
18769      * We will show the performance boost notification to the user up to the daily and monthly
18770      * maximum number of times specified by
18771      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_MAXIMUM_DAILY_NOTIFICATION_COUNT_INT} and
18772      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_MAXIMUM_MONTHLY_NOTIFICATION_COUNT_INT}.
18773      * Subsequent attempts will return the same error until the request is no longer throttled
18774      * or throttling conditions change.
18775      */
18776     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED = 2;
18777 
18778     /**
18779      * Purchase premium capability failed because it is already purchased and available.
18780      * Subsequent attempts will return the same error until the performance boost expires.
18781      */
18782     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED = 3;
18783 
18784     /**
18785      * Purchase premium capability failed because a request was already made and is in progress.
18786      * This may have been requested by either the same app or another app.
18787      * Subsequent attempts will return the same error until the previous request completes.
18788      */
18789     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS = 4;
18790 
18791     /**
18792      * Purchase premium capability failed because the requesting application is not in the
18793      * foreground. Subsequent attempts will return the same error until the requesting application
18794      * moves to the foreground.
18795      */
18796     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND = 5;
18797 
18798     /**
18799      * Purchase premium capability failed because the user canceled the operation.
18800      * Subsequent attempts will be throttled for the amount of time specified by
18801      * {@link CarrierConfigManager
18802      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18803      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18804      */
18805     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED = 6;
18806 
18807     /**
18808      * Purchase premium capability failed because the carrier disabled or does not support
18809      * the capability, as specified in
18810      * {@link CarrierConfigManager#KEY_SUPPORTED_PREMIUM_CAPABILITIES_INT_ARRAY}.
18811      * Subsequent attempts will return the same error until the carrier enables the feature.
18812      */
18813     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED = 7;
18814 
18815     /**
18816      * Purchase premium capability failed because the carrier app did not indicate success.
18817      * Subsequent attempts will be throttled for the amount of time specified by
18818      * {@link CarrierConfigManager
18819      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18820      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18821      */
18822     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR = 8;
18823 
18824     /**
18825      * Purchase premium capability failed because we did not receive a response from the user
18826      * for the performance boost notification within the time specified by
18827      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NOTIFICATION_DISPLAY_TIMEOUT_MILLIS_LONG}.
18828      * The performance boost notification will be automatically dismissed and subsequent attempts
18829      * will be throttled for the amount of time specified by
18830      * {@link CarrierConfigManager
18831      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18832      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18833      */
18834     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT = 9;
18835 
18836     /**
18837      * Purchase premium capability failed because the device does not support the feature.
18838      * Subsequent attempts will return the same error.
18839      */
18840     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED = 10;
18841 
18842     /**
18843      * Purchase premium capability failed because the telephony service is unavailable
18844      * or there was an error in the phone process.
18845      * Subsequent attempts will return the same error until request conditions are satisfied.
18846      */
18847     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED = 11;
18848 
18849     /**
18850      * Purchase premium capability failed because the network is not available.
18851      * Subsequent attempts will return the same error until network conditions change.
18852      */
18853     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE = 12;
18854 
18855     /**
18856      * Purchase premium capability failed because the entitlement check failed.
18857      * Subsequent attempts will be throttled for the amount of time specified by
18858      * {@link CarrierConfigManager
18859      * #KEY_PREMIUM_CAPABILITY_PURCHASE_CONDITION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18860      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18861      * Throttling will be reevaluated when the network is no longer congested.
18862      */
18863     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED = 13;
18864 
18865     /**
18866      * Purchase premium capability failed because the request was not made on the default data
18867      * subscription, indicated by {@link SubscriptionManager#getDefaultDataSubscriptionId()}.
18868      * Subsequent attempts will return the same error until the request is made on the default
18869      * data subscription.
18870      */
18871     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION = 14;
18872 
18873     /**
18874      * Purchase premium capability was successful and is waiting for the network to setup the
18875      * slicing configuration. If the setup is complete within the time specified by
18876      * {@link CarrierConfigManager#KEY_PREMIUM_CAPABILITY_NETWORK_SETUP_TIME_MILLIS_LONG},
18877      * subsequent requests will return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED}
18878      * until the purchase expires. If the setup is not complete within the time specified above,
18879      * applications can request the premium capability again.
18880      */
18881     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP = 15;
18882 
18883     /**
18884      * Purchase premium capability failed because the user disabled the feature.
18885      * Subsequent attempts will be throttled for the amount of time specified by
18886      * {@link CarrierConfigManager
18887      * #KEY_PREMIUM_CAPABILITY_NOTIFICATION_BACKOFF_HYSTERESIS_TIME_MILLIS_LONG}
18888      * and return {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED}.
18889      */
18890     @FlaggedApi(Flags.FLAG_SLICING_ADDITIONAL_ERROR_CODES)
18891     public static final int PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_DISABLED = 16;
18892 
18893     /**
18894      * Results of the purchase premium capability request.
18895      * @hide
18896      */
18897     @Retention(RetentionPolicy.SOURCE)
18898     @IntDef(prefix = { "PURCHASE_PREMIUM_CAPABILITY_RESULT_" }, value = {
18899             PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS,
18900             PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED,
18901             PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED,
18902             PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS,
18903             PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND,
18904             PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED,
18905             PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED,
18906             PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR,
18907             PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT,
18908             PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED,
18909             PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE,
18910             PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED,
18911             PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION,
18912             PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP,
18913             PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_DISABLED})
18914     public @interface PurchasePremiumCapabilityResult {}
18915 
18916     /**
18917      * Returns the purchase result as a String.
18918      *
18919      * @param result The purchase premium capability result.
18920      * @return The purchase result as a String.
18921      * @hide
18922      */
convertPurchaseResultToString( @urchasePremiumCapabilityResult int result)18923     public static String convertPurchaseResultToString(
18924             @PurchasePremiumCapabilityResult int result) {
18925         switch (result) {
18926             case PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS:
18927                 return "SUCCESS";
18928             case PURCHASE_PREMIUM_CAPABILITY_RESULT_THROTTLED:
18929                 return "THROTTLED";
18930             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED:
18931                 return "ALREADY_PURCHASED";
18932             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_IN_PROGRESS:
18933                 return "ALREADY_IN_PROGRESS";
18934             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_FOREGROUND:
18935                 return "NOT_FOREGROUND";
18936             case PURCHASE_PREMIUM_CAPABILITY_RESULT_USER_CANCELED:
18937                 return "USER_CANCELED";
18938             case PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_DISABLED:
18939                 return "CARRIER_DISABLED";
18940             case PURCHASE_PREMIUM_CAPABILITY_RESULT_CARRIER_ERROR:
18941                 return "CARRIER_ERROR";
18942             case PURCHASE_PREMIUM_CAPABILITY_RESULT_TIMEOUT:
18943                 return "TIMEOUT";
18944             case PURCHASE_PREMIUM_CAPABILITY_RESULT_FEATURE_NOT_SUPPORTED:
18945                 return "FEATURE_NOT_SUPPORTED";
18946             case PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED:
18947                 return "REQUEST_FAILED";
18948             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NETWORK_NOT_AVAILABLE:
18949                 return "NETWORK_NOT_AVAILABLE";
18950             case PURCHASE_PREMIUM_CAPABILITY_RESULT_ENTITLEMENT_CHECK_FAILED:
18951                 return "ENTITLEMENT_CHECK_FAILED";
18952             case PURCHASE_PREMIUM_CAPABILITY_RESULT_NOT_DEFAULT_DATA_SUBSCRIPTION:
18953                 return "NOT_DEFAULT_DATA_SUBSCRIPTION";
18954             case PURCHASE_PREMIUM_CAPABILITY_RESULT_PENDING_NETWORK_SETUP:
18955                 return "PENDING_NETWORK_SETUP";
18956             default:
18957                 return "UNKNOWN (" + result + ")";
18958         }
18959     }
18960 
18961     /**
18962      * Purchase the given premium capability from the carrier.
18963      * This requires user action to purchase the boost from the carrier.
18964      * If this returns {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_SUCCESS} or
18965      * {@link #PURCHASE_PREMIUM_CAPABILITY_RESULT_ALREADY_PURCHASED}, applications can request
18966      * the premium capability via {@link ConnectivityManager#requestNetwork}.
18967      *
18968      * @param capability The premium capability to purchase.
18969      * @param executor The callback executor for the response.
18970      * @param callback The result of the purchase request.
18971      * @throws SecurityException if the caller does not hold permissions
18972      *         READ_BASIC_PHONE_STATE or INTERNET.
18973      * @throws UnsupportedOperationException If the device does not have
18974      *          {@link PackageManager#FEATURE_TELEPHONY_DATA}.
18975      * @see #isPremiumCapabilityAvailableForPurchase(int) to check whether the capability is valid.
18976      */
18977     @RequiresPermission(allOf = {android.Manifest.permission.READ_BASIC_PHONE_STATE,
18978             android.Manifest.permission.INTERNET})
18979     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_DATA)
purchasePremiumCapability(@remiumCapability int capability, @NonNull @CallbackExecutor Executor executor, @NonNull @PurchasePremiumCapabilityResult Consumer<Integer> callback)18980     public void purchasePremiumCapability(@PremiumCapability int capability,
18981             @NonNull @CallbackExecutor Executor executor,
18982             @NonNull @PurchasePremiumCapabilityResult Consumer<Integer> callback) {
18983         Objects.requireNonNull(executor);
18984         Objects.requireNonNull(callback);
18985 
18986         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
18987             @Override
18988             public void accept(int result) {
18989                 executor.execute(() -> callback.accept(result));
18990             }
18991         };
18992 
18993         try {
18994             ITelephony telephony = getITelephony();
18995             if (telephony == null) {
18996                 callback.accept(PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED);
18997                 return;
18998             }
18999             telephony.purchasePremiumCapability(capability, internalCallback, getSubId());
19000         } catch (RemoteException ex) {
19001             callback.accept(PURCHASE_PREMIUM_CAPABILITY_RESULT_REQUEST_FAILED);
19002         }
19003     }
19004 
19005     /**
19006      * Get last known cell identity.
19007      *
19008      * If there is current registered network this value will be same as the registered cell
19009      * identity. If the device goes out of service the previous cell identity is cached and
19010      * will be returned. If the cache age of the Cell identity is more than 24 hours
19011      * it will be cleared and null will be returned.
19012      * @return last known cell identity {@CellIdentity}.
19013      * @hide
19014      */
19015     @SystemApi
19016     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_GET_LAST_KNOWN_CELL_IDENTITY)
19017     @RequiresPermission(allOf = {Manifest.permission.ACCESS_FINE_LOCATION,
19018             Manifest.permission.ACCESS_LAST_KNOWN_CELL_ID})
getLastKnownCellIdentity()19019     public @Nullable CellIdentity getLastKnownCellIdentity() {
19020         try {
19021             ITelephony telephony = getITelephony();
19022             if (telephony == null) {
19023                 throw new IllegalStateException("telephony service is null.");
19024             }
19025             return telephony.getLastKnownCellIdentity(getSubId(), getOpPackageName(),
19026                     getAttributionTag());
19027         } catch (RemoteException ex) {
19028             ex.rethrowAsRuntimeException();
19029         }
19030         return null;
19031     }
19032 
19033     /**
19034      * Callbacks to listen for when the set of packages with carrier privileges for a SIM changes.
19035      *
19036      * <p>Of note, when multiple callbacks are registered, they may be triggered one after another.
19037      * The ordering of them is not guaranteed and thus should not be depend on.
19038      *
19039      * @hide
19040      */
19041     @SystemApi
19042     public interface CarrierPrivilegesCallback {
19043         /**
19044          * Called when the set of packages with carrier privileges has changed.
19045          *
19046          * <p>Of note, this callback will <b>not</b> be fired if a carrier triggers a SIM profile
19047          * switch and the same set of packages remains privileged after the switch.
19048          *
19049          * <p>At registration, the callback will receive the current set of privileged packages.
19050          *
19051          * @param privilegedPackageNames The updated set of package names that have carrier
19052          *                               privileges
19053          * @param privilegedUids         The updated set of UIDs that have carrier privileges
19054          */
onCarrierPrivilegesChanged( @onNull Set<String> privilegedPackageNames, @NonNull Set<Integer> privilegedUids)19055         void onCarrierPrivilegesChanged(
19056                 @NonNull Set<String> privilegedPackageNames, @NonNull Set<Integer> privilegedUids);
19057 
19058         /**
19059          * Called when the {@link CarrierService} for the current user profile has changed.
19060          *
19061          * <p>This method does nothing by default. Clients that are interested in the carrier
19062          * service change should override this method to get package name and UID info.
19063          *
19064          * <p>At registration, the callback will receive the current carrier service info.
19065          *
19066          * <p>Of note, this callback will <b>not</b> be fired if a carrier triggers a SIM profile
19067          * switch and the same carrier service remains after switch.
19068          *
19069          * @param carrierServicePackageName package name of the {@link CarrierService}. May be
19070          *                                  {@code null} when no carrier service is detected.
19071          * @param carrierServiceUid         UID of the {@link CarrierService}. May be
19072          *                                  {@link android.os.Process#INVALID_UID} if no carrier
19073          *                                  service is detected.
19074          */
onCarrierServiceChanged( @ullable String carrierServicePackageName, int carrierServiceUid)19075         default void onCarrierServiceChanged(
19076                 @Nullable String carrierServicePackageName, int carrierServiceUid) {
19077             // do nothing by default
19078         }
19079     }
19080 
19081     /**
19082      * Sets a voice service state override from telecom based on the current {@link PhoneAccount}s
19083      * registered. See {@link PhoneAccount#CAPABILITY_VOICE_CALLING_AVAILABLE}.
19084      *
19085      * <p>Currently, this API is only called to indicate over-the-top voice calling capability of
19086      * the SIM call manager, which will get merged into {@link ServiceState#getState} and propagated
19087      * to interested callers via {@link #getServiceState} and {@link
19088      * TelephonyCallback.ServiceStateListener}.
19089      *
19090      * <p>If callers are truly interested in the actual device <-> tower connection status and not
19091      * an overall "device can make voice calls" boolean, they can use {@link
19092      * ServiceState#getNetworkRegistrationInfo} to check CS registration state.
19093      *
19094      * @hide
19095      */
19096     @TestApi
19097     @SystemApi
19098     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
19099     @RequiresPermission(Manifest.permission.BIND_TELECOM_CONNECTION_SERVICE)
setVoiceServiceStateOverride(boolean hasService)19100     public void setVoiceServiceStateOverride(boolean hasService) {
19101         try {
19102             ITelephony telephony = getITelephony();
19103             if (telephony == null) {
19104                 throw new IllegalStateException("Telephony service is null");
19105             }
19106             telephony.setVoiceServiceStateOverride(getSubId(), hasService, getOpPackageName());
19107         } catch (RemoteException ex) {
19108             ex.rethrowAsRuntimeException();
19109         }
19110     }
19111 
19112     /**
19113      * Registers a {@link CarrierPrivilegesCallback} on the given {@code logicalSlotIndex} to
19114      * receive callbacks when the set of packages with carrier privileges changes. The callback will
19115      * immediately be called with the latest state.
19116      *
19117      * @param logicalSlotIndex The SIM slot to listen on
19118      * @param executor The executor where {@code callback} will be invoked
19119      * @param callback The callback to register
19120      * @hide
19121      */
19122     @SystemApi
19123     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
registerCarrierPrivilegesCallback( int logicalSlotIndex, @NonNull @CallbackExecutor Executor executor, @NonNull CarrierPrivilegesCallback callback)19124     public void registerCarrierPrivilegesCallback(
19125             int logicalSlotIndex,
19126             @NonNull @CallbackExecutor Executor executor,
19127             @NonNull CarrierPrivilegesCallback callback) {
19128         if (mContext == null) {
19129             throw new IllegalStateException("Telephony service is null");
19130         } else if (executor == null || callback == null) {
19131             throw new IllegalArgumentException(
19132                     "CarrierPrivilegesCallback and executor must be non-null");
19133         }
19134         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
19135         if (mTelephonyRegistryMgr == null) {
19136             throw new IllegalStateException("Telephony registry service is null");
19137         }
19138         mTelephonyRegistryMgr.addCarrierPrivilegesCallback(logicalSlotIndex, executor, callback);
19139     }
19140 
19141     /**
19142      * Unregisters an existing {@link CarrierPrivilegesCallback}.
19143      *
19144      * @hide
19145      */
19146     @SystemApi
19147     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
unregisterCarrierPrivilegesCallback(@onNull CarrierPrivilegesCallback callback)19148     public void unregisterCarrierPrivilegesCallback(@NonNull CarrierPrivilegesCallback callback) {
19149         if (mContext == null) {
19150             throw new IllegalStateException("Telephony service is null");
19151         } else if (callback == null) {
19152             throw new IllegalArgumentException("CarrierPrivilegesCallback must be non-null");
19153         }
19154         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
19155         if (mTelephonyRegistryMgr == null) {
19156             throw new IllegalStateException("Telephony registry service is null");
19157         }
19158         mTelephonyRegistryMgr.removeCarrierPrivilegesCallback(callback);
19159     }
19160 
19161     /**
19162      * set removable eSIM as default eUICC.
19163      *
19164      * @hide
19165      */
19166     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
19167     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
setRemovableEsimAsDefaultEuicc(boolean isDefault)19168     public void setRemovableEsimAsDefaultEuicc(boolean isDefault) {
19169         try {
19170             ITelephony telephony = getITelephony();
19171             if (telephony != null) {
19172                 telephony.setRemovableEsimAsDefaultEuicc(isDefault, getOpPackageName());
19173             }
19174         } catch (RemoteException e) {
19175             Log.e(TAG, "Error in setRemovableEsimAsDefault: " + e);
19176         }
19177     }
19178 
19179     /**
19180      * Returns whether the removable eSIM is default eUICC or not.
19181      *
19182      * @hide
19183      */
19184     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19185     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_EUICC)
isRemovableEsimDefaultEuicc()19186     public boolean isRemovableEsimDefaultEuicc() {
19187         try {
19188             ITelephony telephony = getITelephony();
19189             if (telephony != null) {
19190                 return telephony.isRemovableEsimDefaultEuicc(getOpPackageName());
19191             }
19192         } catch (RemoteException e) {
19193             Log.e(TAG, "Error in isRemovableEsimDefaultEuicc: " + e);
19194         }
19195         return false;
19196     }
19197 
19198     /**
19199      * Returns a constant indicating the state of sim for the slot index.
19200      *
19201      * @param slotIndex Logical SIM slot index.
19202      *
19203      * @see TelephonyManager.SimState
19204      *
19205      * @hide
19206      */
19207     @SimState
getSimStateForSlotIndex(int slotIndex)19208     public static int getSimStateForSlotIndex(int slotIndex) {
19209         try {
19210             ITelephony telephony = getITelephony();
19211             if (telephony != null) {
19212                 return telephony.getSimStateForSlotIndex(slotIndex);
19213             }
19214         } catch (RemoteException e) {
19215             Log.e(TAG, "Error in getSimStateForSlotIndex: " + e);
19216         }
19217         return TelephonyManager.SIM_STATE_UNKNOWN;
19218     }
19219 
19220     /**
19221      * Captures parameters for collection of emergency
19222      * call diagnostic data
19223      * @hide
19224      */
19225     @SystemApi
19226     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
19227     public static final class EmergencyCallDiagnosticData {
19228         public static final class Builder {
19229             private boolean mCollectTelecomDumpsys;
19230             private boolean mCollectTelephonyDumpsys;
19231 
19232             // If this is set to a value other than -1L, then the logcat collection is enabled.
19233             // Logcat lines with this time or greater are collected how much is collected is
19234             // dependent on internal implementation. Time represented as milliseconds since boot.
19235             private long mLogcatStartTimeMillis = sUnsetLogcatStartTime;
19236 
19237             /**
19238              * Allows enabling of telecom dumpsys collection.
19239              * @param collectTelecomDumpsys Determines whether telecom dumpsys should be collected.
19240              * @return Builder instance corresponding to the configured call diagnostic params.
19241              */
setTelecomDumpsysCollectionEnabled( boolean collectTelecomDumpsys)19242             public @NonNull Builder setTelecomDumpsysCollectionEnabled(
19243                     boolean collectTelecomDumpsys) {
19244                 mCollectTelecomDumpsys = collectTelecomDumpsys;
19245                 return this;
19246             }
19247 
19248             /**
19249              * Allows enabling of telephony dumpsys collection.
19250              * @param collectTelephonyDumpsys Determines if telephony dumpsys should be collected.
19251              * @return Builder instance corresponding to the configured call diagnostic params.
19252              */
setTelephonyDumpsysCollectionEnabled( boolean collectTelephonyDumpsys)19253             public @NonNull Builder setTelephonyDumpsysCollectionEnabled(
19254                     boolean collectTelephonyDumpsys) {
19255                 mCollectTelephonyDumpsys = collectTelephonyDumpsys;
19256                 return this;
19257             }
19258 
19259             /**
19260              * Allows enabling of logcat (system,radio) collection.
19261              * @param startTimeMillis Enables logcat collection as of the indicated timestamp.
19262              * @return Builder instance corresponding to the configured call diagnostic params.
19263              */
setLogcatCollectionStartTimeMillis( @urrentTimeMillisLong long startTimeMillis)19264             public @NonNull Builder setLogcatCollectionStartTimeMillis(
19265                     @CurrentTimeMillisLong long startTimeMillis) {
19266                 mLogcatStartTimeMillis = startTimeMillis;
19267                 return this;
19268             }
19269 
19270             /**
19271              * Build the EmergencyCallDiagnosticData from the provided Builder config.
19272              * @return {@link EmergencyCallDiagnosticData} instance from provided builder.
19273              */
build()19274             public @NonNull EmergencyCallDiagnosticData build() {
19275                 return new EmergencyCallDiagnosticData(mCollectTelecomDumpsys,
19276                         mCollectTelephonyDumpsys, mLogcatStartTimeMillis);
19277             }
19278         }
19279 
19280         private boolean mCollectTelecomDumpsys;
19281         private boolean mCollectTelephonyDumpsys;
19282         private boolean mCollectLogcat;
19283         private long mLogcatStartTimeMillis;
19284 
19285         private static long sUnsetLogcatStartTime = -1L;
19286 
EmergencyCallDiagnosticData(boolean collectTelecomDumpsys, boolean collectTelephonyDumpsys, long logcatStartTimeMillis)19287         private EmergencyCallDiagnosticData(boolean collectTelecomDumpsys,
19288                 boolean collectTelephonyDumpsys, long logcatStartTimeMillis) {
19289             mCollectTelecomDumpsys = collectTelecomDumpsys;
19290             mCollectTelephonyDumpsys = collectTelephonyDumpsys;
19291             mLogcatStartTimeMillis = logcatStartTimeMillis;
19292             mCollectLogcat = logcatStartTimeMillis != sUnsetLogcatStartTime;
19293         }
19294 
isTelecomDumpsysCollectionEnabled()19295         public boolean isTelecomDumpsysCollectionEnabled() {
19296             return mCollectTelecomDumpsys;
19297         }
19298 
isTelephonyDumpsysCollectionEnabled()19299         public boolean isTelephonyDumpsysCollectionEnabled() {
19300             return mCollectTelephonyDumpsys;
19301         }
19302 
isLogcatCollectionEnabled()19303         public boolean isLogcatCollectionEnabled() {
19304             return mCollectLogcat;
19305         }
19306 
getLogcatCollectionStartTimeMillis()19307         public long getLogcatCollectionStartTimeMillis()
19308         {
19309             return mLogcatStartTimeMillis;
19310         }
19311 
19312         @Override
toString()19313         public String toString() {
19314             return "EmergencyCallDiagnosticData{"
19315                     + "mCollectTelecomDumpsys=" + mCollectTelecomDumpsys
19316                     + ", mCollectTelephonyDumpsys=" + mCollectTelephonyDumpsys
19317                     + ", mCollectLogcat=" + mCollectLogcat
19318                     + ", mLogcatStartTimeMillis=" + mLogcatStartTimeMillis
19319                     + '}';
19320         }
19321     }
19322 
19323     /**
19324      * Request telephony to persist state for debugging emergency call failures.
19325      *
19326      * @param dropboxTag Tag to use when persisting data to dropbox service.
19327      * @param data Parameters controlling what is collected in the diagnostics.
19328      *
19329      * @hide
19330      */
19331     @SystemApi
19332     @FlaggedApi(com.android.server.telecom.flags.Flags.FLAG_TELECOM_RESOLVE_HIDDEN_DEPENDENCIES)
19333     @RequiresPermission(android.Manifest.permission.READ_DROPBOX_DATA)
persistEmergencyCallDiagnosticData(@onNull String dropboxTag, @NonNull EmergencyCallDiagnosticData data)19334     public void persistEmergencyCallDiagnosticData(@NonNull String dropboxTag,
19335             @NonNull EmergencyCallDiagnosticData data) {
19336         try {
19337             ITelephony telephony = ITelephony.Stub.asInterface(
19338                     TelephonyFrameworkInitializer
19339                             .getTelephonyServiceManager()
19340                             .getTelephonyServiceRegisterer()
19341                             .get());
19342             if (telephony != null) {
19343                 telephony.persistEmergencyCallDiagnosticData(dropboxTag,
19344                         data.isLogcatCollectionEnabled(),
19345                         data.getLogcatCollectionStartTimeMillis(),
19346                         data.isTelecomDumpsysCollectionEnabled(),
19347                         data.isTelephonyDumpsysCollectionEnabled());
19348             }
19349         } catch (RemoteException e) {
19350             Log.e(TAG, "Error while persistEmergencyCallDiagnosticData: " + e);
19351         }
19352     }
19353 
19354     /**
19355      * Set the UE's ability to accept/reject null ciphered and null integrity-protected connections.
19356      *
19357      * The modem is required to ignore this in case of an emergency call.
19358      *
19359      * <p>Requires permission: android.Manifest.MODIFY_PHONE_STATE</p>
19360      *
19361      * @param enabled if null ciphered and null integrity protected connections are permitted
19362      * @throws IllegalStateException if the Telephony process is not currently available
19363      * @throws SecurityException if the caller does not have the required privileges
19364      * @throws UnsupportedOperationException if the modem does not support disabling null ciphers.
19365      * @hide
19366      */
19367     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNullCipherAndIntegrityEnabled(boolean enabled)19368     public void setNullCipherAndIntegrityEnabled(boolean enabled) {
19369         try {
19370             ITelephony telephony = getITelephony();
19371             if (telephony != null) {
19372                 telephony.setNullCipherAndIntegrityEnabled(enabled);
19373             } else {
19374                 throw new IllegalStateException("telephony service is null.");
19375             }
19376         } catch (RemoteException ex) {
19377             Rlog.e(TAG, "setNullCipherAndIntegrityEnabled RemoteException", ex);
19378             ex.rethrowFromSystemServer();
19379         }
19380     }
19381 
19382     /**
19383      * Get the value of the global preference for null cipher and integriy enablement.
19384      * Note: This does not return the state of the modem, only the persisted global preference.
19385      *
19386      * <p>Requires permission: android.Manifest.READ_PHONE_STATE</p>
19387      *
19388      * @throws IllegalStateException if the Telephony process is not currently available
19389      * @throws SecurityException if the caller does not have the required privileges
19390      * @throws UnsupportedOperationException if the modem does not support disabling null ciphers.
19391      * @hide
19392      */
19393     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
isNullCipherAndIntegrityPreferenceEnabled()19394     public boolean isNullCipherAndIntegrityPreferenceEnabled() {
19395         try {
19396             ITelephony telephony = getITelephony();
19397             if (telephony != null) {
19398                 return telephony.isNullCipherAndIntegrityPreferenceEnabled();
19399             } else {
19400                 throw new IllegalStateException("telephony service is null.");
19401             }
19402         } catch (RemoteException ex) {
19403             Rlog.e(TAG, "isNullCipherAndIntegrityPreferenceEnabled RemoteException", ex);
19404             ex.rethrowFromSystemServer();
19405         }
19406         return true;
19407     }
19408 
19409     /**
19410      * Enable or disable notifications sent for cellular identifier disclosure events.
19411      *
19412      * Disclosure events are defined as instances where a device has sent a cellular identifier
19413      * on the Non-access stratum (NAS) before a security context is established. As a result the
19414      * identifier is sent in the clear, which has privacy implications for the user.
19415      *
19416      * @param enable if notifications about disclosure events should be enabled
19417      * @throws IllegalStateException if the Telephony process is not currently available
19418      * @throws SecurityException if the caller does not have the required privileges
19419      * @throws UnsupportedOperationException if the modem does not support this feature.
19420      *
19421      * @hide
19422      */
19423     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
19424     @SystemApi
setEnableCellularIdentifierDisclosureNotifications(boolean enable)19425     public void setEnableCellularIdentifierDisclosureNotifications(boolean enable) {
19426         try {
19427             ITelephony telephony = getITelephony();
19428             if (telephony != null) {
19429                 telephony.setEnableCellularIdentifierDisclosureNotifications(enable);
19430             } else {
19431                 throw new IllegalStateException("telephony service is null.");
19432             }
19433         } catch (RemoteException ex) {
19434             Rlog.e(TAG, "setEnableCellularIdentifierDisclosureNotifications RemoteException", ex);
19435             ex.rethrowFromSystemServer();
19436         }
19437     }
19438 
19439     /**
19440      * Get whether or not cellular identifier disclosure notifications are enabled.
19441      *
19442      * @throws IllegalStateException if the Telephony process is not currently available
19443      * @throws SecurityException if the caller does not have the required privileges
19444      * @throws UnsupportedOperationException if the modem does not support this feature.
19445      *
19446      * @hide
19447      */
19448     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19449     @SystemApi
isCellularIdentifierDisclosureNotificationsEnabled()19450     public boolean isCellularIdentifierDisclosureNotificationsEnabled() {
19451         try {
19452             ITelephony telephony = getITelephony();
19453             if (telephony != null) {
19454                 return telephony.isCellularIdentifierDisclosureNotificationsEnabled();
19455             } else {
19456                 throw new IllegalStateException("telephony service is null.");
19457             }
19458         } catch (RemoteException ex) {
19459             Rlog.e(TAG, "isCellularIdentifierDisclosureNotificationsEnabled RemoteException", ex);
19460             ex.rethrowFromSystemServer();
19461         }
19462         return false;
19463     }
19464 
19465     /**
19466      * Enables or disables notifications sent when cellular null cipher or integrity algorithms
19467      * are in use by the cellular modem.
19468      *
19469      * @throws IllegalStateException if the Telephony process is not currently available
19470      * @throws SecurityException if the caller does not have the required privileges
19471      * @throws UnsupportedOperationException if the modem does not support reporting on ciphering
19472      * and integrity algorithms in use
19473      * @hide
19474      */
19475     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
19476     @SystemApi
setNullCipherNotificationsEnabled(boolean enable)19477     public void setNullCipherNotificationsEnabled(boolean enable) {
19478         try {
19479             ITelephony telephony = getITelephony();
19480             if (telephony != null) {
19481                 telephony.setNullCipherNotificationsEnabled(enable);
19482             } else {
19483                 throw new IllegalStateException("telephony service is null.");
19484             }
19485         } catch (RemoteException ex) {
19486             Rlog.e(TAG, "setEnableNullCipherNotifications RemoteException", ex);
19487             ex.rethrowFromSystemServer();
19488         }
19489     }
19490 
19491     /**
19492      * Get whether notifications are enabled for null cipher or integrity algorithms in use by the
19493      * cellular modem.
19494      *
19495      * @throws IllegalStateException if the Telephony process is not currently available
19496      * @throws SecurityException if the caller does not have the required privileges
19497      * @throws UnsupportedOperationException if the modem does not support reporting on ciphering
19498      * and integrity algorithms in use
19499      * @hide
19500      */
19501     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19502     @SystemApi
isNullCipherNotificationsEnabled()19503     public boolean isNullCipherNotificationsEnabled() {
19504         try {
19505             ITelephony telephony = getITelephony();
19506             if (telephony != null) {
19507                 return telephony.isNullCipherNotificationsEnabled();
19508             } else {
19509                 throw new IllegalStateException("telephony service is null.");
19510             }
19511         } catch (RemoteException ex) {
19512             Rlog.e(TAG, "isNullCipherNotificationsEnabled RemoteException", ex);
19513             ex.rethrowFromSystemServer();
19514         }
19515         return false;
19516     }
19517 
19518 
19519     /**
19520      * Get current cell broadcast message identifier ranges.
19521      *
19522      * @throws SecurityException if the caller does not have the required permission
19523      * @throws UnsupportedOperationException If the device does not have
19524      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
19525      *
19526      * @hide
19527      */
19528     @SystemApi
19529     @RequiresPermission(android.Manifest.permission.MODIFY_CELL_BROADCASTS)
19530     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
19531     @NonNull
getCellBroadcastIdRanges()19532     public List<CellBroadcastIdRange> getCellBroadcastIdRanges() {
19533         try {
19534             ITelephony telephony = getITelephony();
19535             if (telephony != null) {
19536                 return telephony.getCellBroadcastIdRanges(getSubId());
19537             } else {
19538                 throw new IllegalStateException("telephony service is null.");
19539             }
19540         } catch (RemoteException ex) {
19541             ex.rethrowFromSystemServer();
19542         }
19543         return new ArrayList<>();
19544     }
19545 
19546     /** @hide */
19547     @Retention(RetentionPolicy.SOURCE)
19548     @IntDef(prefix = {"CELL_BROADCAST_RESULT_"}, value = {
19549             CELL_BROADCAST_RESULT_UNKNOWN,
19550             CELL_BROADCAST_RESULT_SUCCESS,
19551             CELL_BROADCAST_RESULT_UNSUPPORTED,
19552             CELL_BROADCAST_RESULT_FAIL_CONFIG,
19553             CELL_BROADCAST_RESULT_FAIL_ACTIVATION})
19554     public @interface CellBroadcastResult {}
19555 
19556     /**
19557      * The result of the cell broadcast request is unknown
19558      * @hide
19559      */
19560     @SystemApi
19561     public static final int CELL_BROADCAST_RESULT_UNKNOWN = -1;
19562 
19563     /**
19564      * The cell broadcast request is successful.
19565      * @hide
19566      */
19567     @SystemApi
19568     public static final int CELL_BROADCAST_RESULT_SUCCESS = 0;
19569 
19570     /**
19571      * The cell broadcast request is not supported.
19572      * @hide
19573      */
19574     @SystemApi
19575     public static final int CELL_BROADCAST_RESULT_UNSUPPORTED = 1;
19576 
19577     /**
19578      * The cell broadcast request is failed due to the error to set config
19579      * @hide
19580      */
19581     @SystemApi
19582     public static final int CELL_BROADCAST_RESULT_FAIL_CONFIG = 2;
19583 
19584     /**
19585      * The cell broadcast request is failed due to the error to set activation
19586      * @hide
19587      */
19588     @SystemApi
19589     public static final int CELL_BROADCAST_RESULT_FAIL_ACTIVATION = 3;
19590 
19591     /**
19592      * Callback mode type
19593      * @hide
19594      */
19595     @Retention(RetentionPolicy.SOURCE)
19596     @IntDef(prefix = {"EMERGENCY_CALLBACK_MODE_"}, value = {
19597             EMERGENCY_CALLBACK_MODE_CALL,
19598             EMERGENCY_CALLBACK_MODE_SMS})
19599     public @interface EmergencyCallbackModeType {}
19600 
19601     /**
19602      * The emergency callback mode is due to emergency call.
19603      * @hide
19604      */
19605     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19606     @SystemApi
19607     public static final int EMERGENCY_CALLBACK_MODE_CALL = 1;
19608 
19609     /**
19610      * The emergency callback mode is due to emergency SMS.
19611      * @hide
19612      */
19613     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19614     @SystemApi
19615     public static final int EMERGENCY_CALLBACK_MODE_SMS = 2;
19616 
19617     /**
19618      * The reason for changing callback mode.
19619      * @hide
19620      */
19621     @Retention(RetentionPolicy.SOURCE)
19622     @IntDef(prefix = {"STOP_REASON_"},
19623             value = {
19624                     STOP_REASON_UNKNOWN,
19625                     STOP_REASON_OUTGOING_NORMAL_CALL_INITIATED,
19626                     STOP_REASON_NORMAL_SMS_SENT,
19627                     STOP_REASON_OUTGOING_EMERGENCY_CALL_INITIATED,
19628                     STOP_REASON_EMERGENCY_SMS_SENT,
19629                     STOP_REASON_TIMER_EXPIRED,
19630                     STOP_REASON_USER_ACTION,
19631             })
19632     public @interface EmergencyCallbackModeStopReason {}
19633 
19634     /**
19635      * Indicates that emergency callback mode has been stopped for an unknown reason.
19636      * @hide
19637      */
19638     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19639     @SystemApi
19640     public static final int STOP_REASON_UNKNOWN = 0;
19641 
19642     /**
19643      * Indicates that emergency callback mode has been stopped because a new non-emergency call was
19644      * initiated.
19645      * @hide
19646      */
19647     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19648     @SystemApi
19649     public static final int STOP_REASON_OUTGOING_NORMAL_CALL_INITIATED = 1;
19650 
19651     /**
19652      * Indicates that emergency callback mode has been stopped because a new non-emergency SMS was
19653      * sent.
19654      * @hide
19655      */
19656     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19657     @SystemApi
19658     public static final int STOP_REASON_NORMAL_SMS_SENT = 2;
19659 
19660     /**
19661      * Indicates that emergency callback mode has been stopped because a new outgoing emergency
19662      * call was initiated.
19663      * @hide
19664      */
19665     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19666     @SystemApi
19667     public static final int STOP_REASON_OUTGOING_EMERGENCY_CALL_INITIATED = 3;
19668 
19669     /**
19670      * Indicates that emergency callback mode has been stopped because a new emergency SMS was sent.
19671      * @hide
19672      */
19673     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19674     @SystemApi
19675     public static final int STOP_REASON_EMERGENCY_SMS_SENT = 4;
19676 
19677     /**
19678      * Indicates that emergency callback mode has been stopped due to the emergency callback mode
19679      * timer expiry.
19680      * @hide
19681      */
19682     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19683     @SystemApi
19684     public static final int STOP_REASON_TIMER_EXPIRED = 5;
19685 
19686     /**
19687      * Indicates that emergency callback mode has been stopped due to user ending the emergency
19688      * mode by clicking the notification.
19689      * @hide
19690      */
19691     @FlaggedApi(Flags.FLAG_EMERGENCY_CALLBACK_MODE_NOTIFICATION)
19692     @SystemApi
19693     public static final int STOP_REASON_USER_ACTION = 6;
19694 
19695     /**
19696      * Set reception of cell broadcast messages with the list of the given ranges
19697      *
19698      * <p>The ranges set previously will be overridden by the new one. Empty list
19699      * can be used to clear the ranges.
19700      *
19701      * @param ranges the list of {@link CellBroadcastIdRange} to be set.
19702      * @param executor The {@link Executor} that will be used to call the callback.
19703      * @param callback A callback called on the supplied {@link Executor} to notify
19704      * the result when the operation completes.
19705      * @throws SecurityException if the caller does not have the required permission
19706      * @throws IllegalArgumentException when the ranges are invalid.
19707      * @throws UnsupportedOperationException If the device does not have
19708      *          {@link PackageManager#FEATURE_TELEPHONY_MESSAGING}.
19709      * @hide
19710      */
19711     @SystemApi
19712     @RequiresPermission(android.Manifest.permission.MODIFY_CELL_BROADCASTS)
19713     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)
setCellBroadcastIdRanges(@onNull List<CellBroadcastIdRange> ranges, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Integer> callback)19714     public void setCellBroadcastIdRanges(@NonNull List<CellBroadcastIdRange> ranges,
19715             @NonNull @CallbackExecutor Executor executor,
19716             @NonNull Consumer<Integer> callback) {
19717         IIntegerConsumer consumer = callback == null ? null : new IIntegerConsumer.Stub() {
19718             @Override
19719             public void accept(int result) {
19720                 final long identity = Binder.clearCallingIdentity();
19721                 try {
19722                     executor.execute(() -> callback.accept(result));
19723                 } finally {
19724                     Binder.restoreCallingIdentity(identity);
19725                 }
19726             }
19727         };
19728 
19729         try {
19730             ITelephony telephony = getITelephony();
19731             if (telephony != null) {
19732                 telephony.setCellBroadcastIdRanges(getSubId(), ranges, consumer);
19733             } else {
19734                 throw new IllegalStateException("telephony service is null.");
19735             }
19736         } catch (RemoteException ex) {
19737             ex.rethrowFromSystemServer();
19738         }
19739     }
19740 
19741     /**
19742      * Returns whether the domain selection service is supported.
19743      *
19744      * @return {@code true} if the domain selection service is supported.
19745      * @hide
19746      */
19747     @SystemApi
19748     @FlaggedApi(Flags.FLAG_USE_OEM_DOMAIN_SELECTION_SERVICE)
19749     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19750     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isDomainSelectionSupported()19751     public boolean isDomainSelectionSupported() {
19752         try {
19753             ITelephony telephony = getITelephony();
19754             if (telephony != null) {
19755                 return telephony.isDomainSelectionSupported();
19756             }
19757         } catch (RemoteException ex) {
19758             Rlog.w(TAG, "RemoteException", ex);
19759         }
19760         return false;
19761     }
19762 
19763     /**
19764      * Returns whether the AOSP domain selection service is supported.
19765      *
19766      * @return {@code true} if the AOSP domain selection service is supported.
19767      * @hide
19768      */
19769     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19770     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_CALLING)
isAospDomainSelectionService()19771     public boolean isAospDomainSelectionService() {
19772         try {
19773             ITelephony telephony = getITelephony();
19774             if (telephony != null) {
19775                 return telephony.isAospDomainSelectionService();
19776             }
19777         } catch (RemoteException ex) {
19778             Rlog.w(TAG, "RemoteException", ex);
19779         }
19780         return false;
19781     }
19782 
19783     /**
19784      * Returns the primary IMEI (International Mobile Equipment Identity) of the device as
19785      * mentioned in GSMA TS.37. {@link #getImei(int)} returns the IMEI that belongs to the selected
19786      * slotID whereas this API {@link #getPrimaryImei()} returns primary IMEI of the device.
19787      * A single SIM device with only one IMEI will be set by default as primary IMEI.
19788      * A multi-SIM device with multiple IMEIs will have one of the IMEIs set as primary as
19789      * mentioned in GSMA TS37_2.2_REQ_8.
19790      *
19791      * <p>Requires one of the following permissions
19792      * <ul>
19793      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
19794      *     is a privileged permission that can only be granted to apps preloaded on the device.
19795      *     <li>If the calling app is the device owner of a fully-managed device, a profile
19796      *     owner of an organization-owned device, or their delegates (see {@link
19797      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
19798      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
19799      *     active subscription.
19800      *     <li>If the calling app is the default SMS role holder (see {@link
19801      *     RoleManager#isRoleHeld(String)}).
19802      *     <li>If the calling app has been granted the
19803      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
19804      * </ul>
19805      *
19806      * @return Primary IMEI of type string
19807      * @throws SecurityException if the caller does not have the required permission/privileges
19808      */
19809     @NonNull
getPrimaryImei()19810     public String getPrimaryImei() {
19811         try {
19812             ITelephony telephony = getITelephony();
19813             if (telephony == null) {
19814                 Rlog.e(TAG, "getPrimaryImei(): IPhoneSubInfo instance is NULL");
19815                 throw new IllegalStateException("Telephony service not available.");
19816             }
19817             return telephony.getPrimaryImei(getOpPackageName(), getAttributionTag());
19818         } catch (RemoteException ex) {
19819             Rlog.e(TAG, "getPrimaryImei() RemoteException : " + ex);
19820             throw ex.rethrowAsRuntimeException();
19821         }
19822     }
19823 
19824     /**
19825      * Convert SIM state into string.
19826      *
19827      * @param state SIM state.
19828      * @return SIM state in string format.
19829      *
19830      * @hide
19831      */
19832     @NonNull
simStateToString(@imState int state)19833     public static String simStateToString(@SimState int state) {
19834         switch (state) {
19835             case TelephonyManager.SIM_STATE_UNKNOWN:
19836                 return "UNKNOWN";
19837             case TelephonyManager.SIM_STATE_ABSENT:
19838                 return "ABSENT";
19839             case TelephonyManager.SIM_STATE_PIN_REQUIRED:
19840                 return "PIN_REQUIRED";
19841             case TelephonyManager.SIM_STATE_PUK_REQUIRED:
19842                 return "PUK_REQUIRED";
19843             case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
19844                 return "NETWORK_LOCKED";
19845             case TelephonyManager.SIM_STATE_READY:
19846                 return "READY";
19847             case TelephonyManager.SIM_STATE_NOT_READY:
19848                 return "NOT_READY";
19849             case TelephonyManager.SIM_STATE_PERM_DISABLED:
19850                 return "PERM_DISABLED";
19851             case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
19852                 return "CARD_IO_ERROR";
19853             case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
19854                 return "CARD_RESTRICTED";
19855             case TelephonyManager.SIM_STATE_LOADED:
19856                 return "LOADED";
19857             case TelephonyManager.SIM_STATE_PRESENT:
19858                 return "PRESENT";
19859             default:
19860                 return "UNKNOWN(" + state + ")";
19861         }
19862     }
19863 
19864     /**
19865      * This API can be used by only CTS to override the Euicc UI component.
19866      *
19867      * @param componentName ui component to be launched for testing. {@code null} to reset.
19868      *
19869      * @hide
19870      */
19871     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setTestEuiccUiComponent(@ullable ComponentName componentName)19872     public void setTestEuiccUiComponent(@Nullable ComponentName componentName) {
19873         try {
19874             ITelephony telephony = getITelephony();
19875             if (telephony == null) {
19876                 Rlog.e(TAG, "setTestEuiccUiComponent(): ITelephony instance is NULL");
19877                 throw new IllegalStateException("Telephony service not available.");
19878             }
19879             telephony.setTestEuiccUiComponent(componentName);
19880         } catch (RemoteException ex) {
19881             Rlog.e(TAG, "setTestEuiccUiComponent() RemoteException : " + ex);
19882             throw ex.rethrowAsRuntimeException();
19883         }
19884     }
19885 
19886     /**
19887      * This API can be used by only CTS to retrieve the Euicc UI component.
19888      *
19889      * @return The Euicc UI component for testing. {@code null} if not available.
19890      * @hide
19891      */
19892     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
19893     @Nullable
getTestEuiccUiComponent()19894     public ComponentName getTestEuiccUiComponent() {
19895         try {
19896             ITelephony telephony = getITelephony();
19897             if (telephony == null) {
19898                 Rlog.e(TAG, "getTestEuiccUiComponent(): ITelephony instance is NULL");
19899                 throw new IllegalStateException("Telephony service not available.");
19900             }
19901             return telephony.getTestEuiccUiComponent();
19902         } catch (RemoteException ex) {
19903             Rlog.e(TAG, "getTestEuiccUiComponent() RemoteException : " + ex);
19904             throw ex.rethrowAsRuntimeException();
19905         }
19906     }
19907 
19908     /**
19909      * Returns carrier id maps to the passing CarrierIdentifier.
19910      * To recognize a carrier (including MVNO) as a first-class identity,
19911      * Android assigns each carrier with a canonical integer a.k.a. carrier id.
19912      * The carrier ID is an Android platform-wide identifier for a carrier.
19913      * AOSP maintains carrier ID assignments in
19914      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/main/assets/latest_carrier_id/carrier_list.textpb">here</a>
19915      *
19916      * @param carrierIdentifier {@link CarrierIdentifier}
19917      *
19918      * @return Carrier id. Return {@link #UNKNOWN_CARRIER_ID} if the carrier cannot be identified.
19919      * @throws UnsupportedOperationException If the device does not have
19920      *          {@link PackageManager#FEATURE_TELEPHONY_SUBSCRIPTION}.
19921      *
19922      * @hide
19923      */
19924     @FlaggedApi(Flags.FLAG_CARRIER_ID_FROM_CARRIER_IDENTIFIER)
19925     @SystemApi
19926     @WorkerThread
19927     @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION)
19928     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromCarrierIdentifier(@onNull CarrierIdentifier carrierIdentifier)19929     public int getCarrierIdFromCarrierIdentifier(@NonNull CarrierIdentifier carrierIdentifier) {
19930         try {
19931             ITelephony service = getITelephony();
19932             if (service != null) {
19933                 return service.getCarrierIdFromIdentifier(carrierIdentifier);
19934             }
19935         } catch (RemoteException ex) {
19936             // This could happen if binder process crashes.
19937         }
19938         return UNKNOWN_CARRIER_ID;
19939     }
19940 }
19941