• 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.BytesLong;
27 import android.annotation.CallbackExecutor;
28 import android.annotation.IntDef;
29 import android.annotation.LongDef;
30 import android.annotation.NonNull;
31 import android.annotation.Nullable;
32 import android.annotation.RequiresFeature;
33 import android.annotation.RequiresPermission;
34 import android.annotation.SdkConstant;
35 import android.annotation.SdkConstant.SdkConstantType;
36 import android.annotation.StringDef;
37 import android.annotation.SuppressAutoDoc;
38 import android.annotation.SuppressLint;
39 import android.annotation.SystemApi;
40 import android.annotation.SystemService;
41 import android.annotation.TestApi;
42 import android.annotation.WorkerThread;
43 import android.app.PendingIntent;
44 import android.app.role.RoleManager;
45 import android.compat.Compatibility;
46 import android.compat.annotation.ChangeId;
47 import android.compat.annotation.EnabledAfter;
48 import android.compat.annotation.UnsupportedAppUsage;
49 import android.content.ComponentName;
50 import android.content.Context;
51 import android.content.Intent;
52 import android.database.Cursor;
53 import android.net.ConnectivityManager;
54 import android.net.Uri;
55 import android.os.AsyncTask;
56 import android.os.Binder;
57 import android.os.Build;
58 import android.os.Bundle;
59 import android.os.Handler;
60 import android.os.IBinder;
61 import android.os.Looper;
62 import android.os.OutcomeReceiver;
63 import android.os.ParcelFileDescriptor;
64 import android.os.ParcelUuid;
65 import android.os.Parcelable;
66 import android.os.PersistableBundle;
67 import android.os.RemoteException;
68 import android.os.ResultReceiver;
69 import android.os.SystemProperties;
70 import android.os.WorkSource;
71 import android.provider.Settings.SettingNotFoundException;
72 import android.service.carrier.CarrierIdentifier;
73 import android.sysprop.TelephonyProperties;
74 import android.telecom.CallScreeningService;
75 import android.telecom.InCallService;
76 import android.telecom.PhoneAccount;
77 import android.telecom.PhoneAccountHandle;
78 import android.telecom.TelecomManager;
79 import android.telephony.Annotation.ApnType;
80 import android.telephony.Annotation.CallState;
81 import android.telephony.Annotation.CarrierPrivilegeStatus;
82 import android.telephony.Annotation.NetworkType;
83 import android.telephony.Annotation.RadioPowerState;
84 import android.telephony.Annotation.SimActivationState;
85 import android.telephony.Annotation.ThermalMitigationResult;
86 import android.telephony.Annotation.UiccAppType;
87 import android.telephony.Annotation.UiccAppTypeExt;
88 import android.telephony.CallForwardingInfo.CallForwardingReason;
89 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
90 import android.telephony.data.ApnSetting;
91 import android.telephony.data.ApnSetting.MvnoType;
92 import android.telephony.data.NetworkSlicingConfig;
93 import android.telephony.emergency.EmergencyNumber;
94 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
95 import android.telephony.gba.UaSecurityProtocolIdentifier;
96 import android.telephony.ims.ImsMmTelManager;
97 import android.telephony.ims.aidl.IImsConfig;
98 import android.telephony.ims.aidl.IImsRegistration;
99 import android.telephony.ims.feature.MmTelFeature;
100 import android.telephony.ims.stub.ImsRegistrationImplBase;
101 import android.text.TextUtils;
102 import android.util.Log;
103 import android.util.Pair;
104 
105 import com.android.internal.annotations.GuardedBy;
106 import com.android.internal.annotations.VisibleForTesting;
107 import com.android.internal.os.BackgroundThread;
108 import com.android.internal.telephony.CellNetworkScanResult;
109 import com.android.internal.telephony.IBooleanConsumer;
110 import com.android.internal.telephony.ICallForwardingInfoCallback;
111 import com.android.internal.telephony.IIntegerConsumer;
112 import com.android.internal.telephony.INumberVerificationCallback;
113 import com.android.internal.telephony.IOns;
114 import com.android.internal.telephony.IPhoneSubInfo;
115 import com.android.internal.telephony.ISetOpportunisticDataCallback;
116 import com.android.internal.telephony.ISms;
117 import com.android.internal.telephony.ISub;
118 import com.android.internal.telephony.ITelephony;
119 import com.android.internal.telephony.IUpdateAvailableNetworksCallback;
120 import com.android.internal.telephony.OperatorInfo;
121 import com.android.internal.telephony.PhoneConstants;
122 import com.android.internal.telephony.RILConstants;
123 import com.android.internal.telephony.SmsApplication;
124 import com.android.telephony.Rlog;
125 
126 import java.io.IOException;
127 import java.io.InputStream;
128 import java.io.OutputStream;
129 import java.lang.annotation.Retention;
130 import java.lang.annotation.RetentionPolicy;
131 import java.nio.file.Files;
132 import java.nio.file.Path;
133 import java.util.ArrayList;
134 import java.util.Collections;
135 import java.util.HashMap;
136 import java.util.List;
137 import java.util.Locale;
138 import java.util.Map;
139 import java.util.Objects;
140 import java.util.UUID;
141 import java.util.concurrent.Executor;
142 import java.util.concurrent.RejectedExecutionException;
143 import java.util.function.Consumer;
144 import java.util.stream.Collectors;
145 import java.util.stream.IntStream;
146 
147 /**
148  * Provides access to information about the telephony services on
149  * the device. Applications can use the methods in this class to
150  * determine telephony services and states, as well as to access some
151  * types of subscriber information. Applications can also register
152  * a listener to receive notification of telephony state changes.
153  * <p>
154  * The returned TelephonyManager will use the default subscription for all calls.
155  * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
156  * <code>
157  *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
158  * </code>
159  * <p>
160  * Note that access to some telephony information is
161  * permission-protected. Your application cannot access the protected
162  * information unless it has the appropriate permissions declared in
163  * its manifest file. Where permissions apply, they are noted in the
164  * the methods through which you access the protected information.
165  *
166  * <p>TelephonyManager is intended for use on devices that implement
167  * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
168  * that do not implement this feature, the behavior is not reliable.
169  */
170 @SystemService(Context.TELEPHONY_SERVICE)
171 public class TelephonyManager {
172     private static final String TAG = "TelephonyManager";
173 
174     private TelephonyRegistryManager mTelephonyRegistryMgr;
175     /**
176      * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
177      * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
178      */
179     @ChangeId
180     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
181     private static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
182 
183     /**
184      * The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
185      * into the ResultReceiver Bundle.
186      * @hide
187      */
188     public static final String MODEM_ACTIVITY_RESULT_KEY = "controller_activity";
189 
190     /** @hide */
191     public static final String EXCEPTION_RESULT_KEY = "exception";
192 
193     /**
194      * The process name of the Phone app as well as many other apps that use this process name, such
195      * as settings and vendor components.
196      * @hide
197      */
198     public static final String PHONE_PROCESS_NAME = "com.android.phone";
199 
200     /**
201      * The allowed states of Wi-Fi calling.
202      *
203      * @hide
204      */
205     public interface WifiCallingChoices {
206         /** Always use Wi-Fi calling */
207         static final int ALWAYS_USE = 0;
208         /** Ask the user whether to use Wi-Fi on every call */
209         static final int ASK_EVERY_TIME = 1;
210         /** Never use Wi-Fi calling */
211         static final int NEVER_USE = 2;
212     }
213 
214     /** @hide */
215     @Retention(RetentionPolicy.SOURCE)
216     @IntDef(prefix = {"NETWORK_SELECTION_MODE_"},
217             value = {
218                     NETWORK_SELECTION_MODE_UNKNOWN,
219                     NETWORK_SELECTION_MODE_AUTO,
220                     NETWORK_SELECTION_MODE_MANUAL})
221     public @interface NetworkSelectionMode {}
222 
223     public static final int NETWORK_SELECTION_MODE_UNKNOWN = 0;
224     public static final int NETWORK_SELECTION_MODE_AUTO = 1;
225     public static final int NETWORK_SELECTION_MODE_MANUAL = 2;
226 
227     /** The otaspMode passed to PhoneStateListener#onOtaspChanged */
228     /** @hide */
229     static public final int OTASP_UNINITIALIZED = 0;
230     /** @hide */
231     static public final int OTASP_UNKNOWN = 1;
232     /** @hide */
233     static public final int OTASP_NEEDED = 2;
234     /** @hide */
235     static public final int OTASP_NOT_NEEDED = 3;
236     /* OtaUtil has conflict enum 4: OtaUtils.OTASP_FAILURE_SPC_RETRIES */
237     /** @hide */
238     static public final int OTASP_SIM_UNPROVISIONED = 5;
239 
240     /**
241      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
242      * available for use in ePDG links.
243      *
244      * @hide
245      */
246     @SystemApi
247     static public final int KEY_TYPE_EPDG = 1;
248 
249     /**
250      * Used in carrier Wi-Fi for IMSI + IMPI encryption, this indicates a public key that's
251      * available for use in WLAN links.
252      *
253      * @hide
254      */
255     @SystemApi
256     static public final int KEY_TYPE_WLAN = 2;
257 
258     /** @hide */
259     @Retention(RetentionPolicy.SOURCE)
260     @IntDef(prefix = {"KEY_TYPE_"}, value = {KEY_TYPE_EPDG, KEY_TYPE_WLAN})
261     public @interface KeyType {}
262 
263     /**
264      * No Single Radio Voice Call Continuity (SRVCC) handover is active.
265      * See TS 23.216 for more information.
266      * @hide
267      */
268     @SystemApi
269     public static final int SRVCC_STATE_HANDOVER_NONE  = -1;
270 
271     /**
272      * Single Radio Voice Call Continuity (SRVCC) handover has been started on the network.
273      * See TS 23.216 for more information.
274      * @hide
275      */
276     @SystemApi
277     public static final int SRVCC_STATE_HANDOVER_STARTED  = 0;
278 
279     /**
280      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has successfully completed.
281      * See TS 23.216 for more information.
282      * @hide
283      */
284     @SystemApi
285     public static final int SRVCC_STATE_HANDOVER_COMPLETED = 1;
286 
287     /**
288      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has failed.
289      * See TS 23.216 for more information.
290      * @hide
291      */
292     @SystemApi
293     public static final int SRVCC_STATE_HANDOVER_FAILED   = 2;
294 
295     /**
296      * Ongoing Single Radio Voice Call Continuity (SRVCC) handover has been canceled.
297      * See TS 23.216 for more information.
298      * @hide
299      */
300     @SystemApi
301     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
302 
303     /**
304      * A UICC card identifier used if the device does not support the operation.
305      * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
306      * eUICC, or the eUICC cannot be read.
307      */
308     public static final int UNSUPPORTED_CARD_ID = -1;
309 
310     /**
311      * A UICC card identifier used before the UICC card is loaded. See
312      * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
313      * <p>
314      * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
315      */
316     public static final int UNINITIALIZED_CARD_ID = -2;
317 
318     private final Context mContext;
319     private final int mSubId;
320     @UnsupportedAppUsage
321     private SubscriptionManager mSubscriptionManager;
322     private TelephonyScanManager mTelephonyScanManager;
323 
324     /** Cached service handles, cleared by resetServiceHandles() at death */
325     private static final Object sCacheLock = new Object();
326 
327     /** @hide */
328     private static boolean sServiceHandleCacheEnabled = true;
329 
330     @GuardedBy("sCacheLock")
331     private static ITelephony sITelephony;
332     @GuardedBy("sCacheLock")
333     private static IPhoneSubInfo sIPhoneSubInfo;
334     @GuardedBy("sCacheLock")
335     private static ISub sISub;
336     @GuardedBy("sCacheLock")
337     private static ISms sISms;
338     @GuardedBy("sCacheLock")
339     private static final DeathRecipient sServiceDeath = new DeathRecipient();
340 
341     /** Enum indicating multisim variants
342      *  DSDS - Dual SIM Dual Standby
343      *  DSDA - Dual SIM Dual Active
344      *  TSTS - Triple SIM Triple Standby
345      **/
346     /** @hide */
347     @UnsupportedAppUsage(implicitMember =
348             "values()[Landroid/telephony/TelephonyManager$MultiSimVariants;")
349     public enum MultiSimVariants {
350         @UnsupportedAppUsage
351         DSDS,
352         @UnsupportedAppUsage
353         DSDA,
354         @UnsupportedAppUsage
355         TSTS,
356         @UnsupportedAppUsage
357         UNKNOWN
358     };
359 
360     /** @hide */
361     @UnsupportedAppUsage
TelephonyManager(Context context)362     public TelephonyManager(Context context) {
363       this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
364     }
365 
366     /** @hide */
367     @UnsupportedAppUsage
TelephonyManager(Context context, int subId)368     public TelephonyManager(Context context, int subId) {
369         mSubId = subId;
370         Context appContext = context.getApplicationContext();
371         if (appContext != null) {
372             if (Objects.equals(context.getAttributionTag(), appContext.getAttributionTag())) {
373                 mContext = appContext;
374             } else {
375                 mContext = appContext.createAttributionContext(context.getAttributionTag());
376             }
377         } else {
378             mContext = context;
379         }
380         mSubscriptionManager = SubscriptionManager.from(mContext);
381     }
382 
383     /** @hide */
384     @UnsupportedAppUsage
TelephonyManager()385     private TelephonyManager() {
386         mContext = null;
387         mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
388     }
389 
390     private static TelephonyManager sInstance = new TelephonyManager();
391 
392     /** @hide
393     /* @deprecated - use getSystemService as described above */
394     @Deprecated
395     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDefault()396     public static TelephonyManager getDefault() {
397         return sInstance;
398     }
399 
getOpPackageName()400     private String getOpPackageName() {
401         // For legacy reasons the TelephonyManager has API for getting
402         // a static instance with no context set preventing us from
403         // getting the op package name. As a workaround we do a best
404         // effort and get the context from the current activity thread.
405         if (mContext != null) {
406             return mContext.getOpPackageName();
407         } else {
408             ITelephony telephony = getITelephony();
409             if (telephony == null) return null;
410             try {
411                 return telephony.getCurrentPackageName();
412             } catch (RemoteException ex) {
413                 return null;
414             } catch (NullPointerException ex) {
415                 return null;
416             }
417         }
418     }
419 
getAttributionTag()420     private String getAttributionTag() {
421         // For legacy reasons the TelephonyManager has API for getting
422         // a static instance with no context set preventing us from
423         // getting the attribution tag.
424         if (mContext != null) {
425             return mContext.getAttributionTag();
426         }
427         return null;
428     }
429 
430     /**
431      * Post a runnable to the BackgroundThread.
432      *
433      * Used to invoke user callbacks without calling into the caller's executor from the caller's
434      * calling thread context, for example to provide asynchronous error information that is
435      * generated locally (not over a binder thread).
436      *
437      * <p>This is not necessary unless you are invoking caller's code asynchronously from within
438      * the caller's thread context.
439      *
440      * @param r a runnable.
441      */
runOnBackgroundThread(@onNull Runnable r)442     private static void runOnBackgroundThread(@NonNull Runnable r) {
443         try {
444             BackgroundThread.getExecutor().execute(r);
445         } catch (RejectedExecutionException e) {
446             throw new IllegalStateException(
447                     "Failed to post a callback from the caller's thread context.", e);
448         }
449     }
450 
451     /**
452      * Returns the multi SIM variant
453      * Returns DSDS for Dual SIM Dual Standby
454      * Returns DSDA for Dual SIM Dual Active
455      * Returns TSTS for Triple SIM Triple Standby
456      * Returns UNKNOWN for others
457      */
458     /** {@hide} */
459     @UnsupportedAppUsage
getMultiSimConfiguration()460     public MultiSimVariants getMultiSimConfiguration() {
461         String mSimConfig =
462                 TelephonyProperties.multi_sim_config().orElse("");
463         if (mSimConfig.equals("dsds")) {
464             return MultiSimVariants.DSDS;
465         } else if (mSimConfig.equals("dsda")) {
466             return MultiSimVariants.DSDA;
467         } else if (mSimConfig.equals("tsts")) {
468             return MultiSimVariants.TSTS;
469         } else {
470             return MultiSimVariants.UNKNOWN;
471         }
472     }
473 
474     /**
475      * Returns the number of phones available.
476      * Returns 0 if none of voice, sms, data is not supported
477      * Returns 1 for Single standby mode (Single SIM functionality).
478      * Returns 2 for Dual standby mode (Dual SIM functionality).
479      * Returns 3 for Tri standby mode (Tri SIM functionality).
480      * @deprecated Use {@link #getActiveModemCount} instead.
481      */
482     @Deprecated
getPhoneCount()483     public int getPhoneCount() {
484         return getActiveModemCount();
485     }
486 
487     /**
488      * Returns the number of logical modems currently configured to be activated.
489      *
490      * Returns 0 if none of voice, sms, data is not supported
491      * Returns 1 for Single standby mode (Single SIM functionality).
492      * Returns 2 for Dual standby mode (Dual SIM functionality).
493      * Returns 3 for Tri standby mode (Tri SIM functionality).
494      */
getActiveModemCount()495     public int getActiveModemCount() {
496         int modemCount = 1;
497         switch (getMultiSimConfiguration()) {
498             case UNKNOWN:
499                 modemCount = 1;
500                 // check for voice and data support, 0 if not supported
501                 if (!isVoiceCapable() && !isSmsCapable() && !isDataCapable()) {
502                     modemCount = 0;
503                 }
504                 break;
505             case DSDS:
506             case DSDA:
507                 modemCount = 2;
508                 break;
509             case TSTS:
510                 modemCount = 3;
511                 break;
512         }
513         return modemCount;
514     }
515 
516     /**
517      * Return how many logical modem can be potentially active simultaneously, in terms of hardware
518      * capability.
519      * It might return different value from {@link #getActiveModemCount}. For example, for a
520      * dual-SIM capable device operating in single SIM mode (only one logical modem is turned on),
521      * {@link #getActiveModemCount} returns 1 while this API returns 2.
522      */
getSupportedModemCount()523     public int getSupportedModemCount() {
524         return TelephonyProperties.max_active_modems().orElse(getActiveModemCount());
525     }
526 
527     /**
528      * Gets the maximum number of SIMs that can be active, based on the device's multisim
529      * configuration.
530      * @return 1 for single-SIM, DSDS, and TSTS devices. 2 for DSDA devices.
531      * @hide
532      */
533     @SystemApi
getMaxNumberOfSimultaneouslyActiveSims()534     public int getMaxNumberOfSimultaneouslyActiveSims() {
535         switch (getMultiSimConfiguration()) {
536             case UNKNOWN:
537             case DSDS:
538             case TSTS:
539                 return 1;
540             case DSDA:
541                 return 2;
542         }
543         return 1;
544     }
545 
546     /** {@hide} */
547     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
from(Context context)548     public static TelephonyManager from(Context context) {
549         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
550     }
551 
552     /**
553      * Create a new TelephonyManager object pinned to the given subscription ID.
554      *
555      * @return a TelephonyManager that uses the given subId for all calls.
556      */
createForSubscriptionId(int subId)557     public TelephonyManager createForSubscriptionId(int subId) {
558       // Don't reuse any TelephonyManager objects.
559       return new TelephonyManager(mContext, subId);
560     }
561 
562     /**
563      * Create a new TelephonyManager object pinned to the subscription ID associated with the given
564      * phone account.
565      *
566      * @return a TelephonyManager that uses the given phone account for all calls, or {@code null}
567      * if the phone account does not correspond to a valid subscription ID.
568      */
569     @Nullable
createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle)570     public TelephonyManager createForPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
571         int subId = getSubscriptionId(phoneAccountHandle);
572         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
573             return null;
574         }
575         return new TelephonyManager(mContext, subId);
576     }
577 
578     /** {@hide} */
579     @UnsupportedAppUsage
isMultiSimEnabled()580     public boolean isMultiSimEnabled() {
581         return getPhoneCount() > 1;
582     }
583 
584     private static final int MAXIMUM_CALL_COMPOSER_PICTURE_SIZE = 80000;
585 
586     /**
587      * Indicates the maximum size of the call composure picture.
588      *
589      * Pictures sent via
590      * {@link #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)}
591      * or {@link #uploadCallComposerPicture(Path, String, Executor, OutcomeReceiver)} must not
592      * exceed this size, or an error will be returned via the callback in those methods.
593      *
594      * @return Maximum file size in bytes.
595      */
getMaximumCallComposerPictureSize()596     public static @BytesLong long getMaximumCallComposerPictureSize() {
597         return MAXIMUM_CALL_COMPOSER_PICTURE_SIZE;
598     }
599 
600     //
601     // Broadcast Intent actions
602     //
603 
604     /**
605      * Broadcast intent action indicating that the call state
606      * on the device has changed.
607      *
608      * <p>
609      * The {@link #EXTRA_STATE} extra indicates the new call state.
610      * If a receiving app has {@link android.Manifest.permission#READ_CALL_LOG} permission, a second
611      * extra {@link #EXTRA_INCOMING_NUMBER} provides the phone number for incoming and outgoing
612      * calls as a String.
613      * <p>
614      * If the receiving app has
615      * {@link android.Manifest.permission#READ_CALL_LOG} and
616      * {@link android.Manifest.permission#READ_PHONE_STATE} permission, it will receive the
617      * broadcast twice; one with the {@link #EXTRA_INCOMING_NUMBER} populated with the phone number,
618      * and another with it blank.  Due to the nature of broadcasts, you cannot assume the order
619      * in which these broadcasts will arrive, however you are guaranteed to receive two in this
620      * case.  Apps which are interested in the {@link #EXTRA_INCOMING_NUMBER} can ignore the
621      * broadcasts where {@link #EXTRA_INCOMING_NUMBER} is not present in the extras (e.g. where
622      * {@link Intent#hasExtra(String)} returns {@code false}).
623      * <p class="note">
624      * This was a {@link android.content.Context#sendStickyBroadcast sticky}
625      * broadcast in version 1.0, but it is no longer sticky.
626      * Instead, use {@link #getCallState} to synchronously query the current call state.
627      *
628      * @see #EXTRA_STATE
629      * @see #EXTRA_INCOMING_NUMBER
630      * @see #getCallState
631      */
632     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
633     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
634     public static final String ACTION_PHONE_STATE_CHANGED =
635             "android.intent.action.PHONE_STATE";
636 
637     /**
638      * The Phone app sends this intent when a user opts to respond-via-message during an incoming
639      * call. By default, the device's default SMS app consumes this message and sends a text message
640      * to the caller. A third party app can also provide this functionality by consuming this Intent
641      * with a {@link android.app.Service} and sending the message using its own messaging system.
642      * <p>The intent contains a URI (available from {@link android.content.Intent#getData})
643      * describing the recipient, using either the {@code sms:}, {@code smsto:}, {@code mms:},
644      * or {@code mmsto:} URI schema. Each of these URI schema carry the recipient information the
645      * same way: the path part of the URI contains the recipient's phone number or a comma-separated
646      * set of phone numbers if there are multiple recipients. For example, {@code
647      * smsto:2065551234}.</p>
648      *
649      * <p>The intent may also contain extras for the message text (in {@link
650      * android.content.Intent#EXTRA_TEXT}) and a message subject
651      * (in {@link android.content.Intent#EXTRA_SUBJECT}).</p>
652      *
653      * <p class="note"><strong>Note:</strong>
654      * The intent-filter that consumes this Intent needs to be in a {@link android.app.Service}
655      * that requires the
656      * permission {@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}.</p>
657      * <p>For example, the service that receives this intent can be declared in the manifest file
658      * with an intent filter like this:</p>
659      * <pre>
660      * &lt;!-- Service that delivers SMS messages received from the phone "quick response" -->
661      * &lt;service android:name=".HeadlessSmsSendService"
662      *          android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
663      *          android:exported="true" >
664      *   &lt;intent-filter>
665      *     &lt;action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
666      *     &lt;category android:name="android.intent.category.DEFAULT" />
667      *     &lt;data android:scheme="sms" />
668      *     &lt;data android:scheme="smsto" />
669      *     &lt;data android:scheme="mms" />
670      *     &lt;data android:scheme="mmsto" />
671      *   &lt;/intent-filter>
672      * &lt;/service></pre>
673      * <p>
674      * Output: nothing.
675      */
676     @SdkConstant(SdkConstantType.SERVICE_ACTION)
677     public static final String ACTION_RESPOND_VIA_MESSAGE =
678             "android.intent.action.RESPOND_VIA_MESSAGE";
679 
680     /**
681      * The emergency dialer may choose to present activities with intent filters for this
682      * action as emergency assistance buttons that launch the activity when clicked.
683      *
684      * @hide
685      */
686     @SystemApi
687     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
688     public static final String ACTION_EMERGENCY_ASSISTANCE =
689             "android.telephony.action.EMERGENCY_ASSISTANCE";
690 
691     /**
692      * A boolean meta-data value indicating whether the voicemail settings should be hidden in the
693      * call settings page launched by
694      * {@link android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS}.
695      * Dialer implementations (see {@link android.telecom.TelecomManager#getDefaultDialerPackage()})
696      * which would also like to manage voicemail settings should set this meta-data to {@code true}
697      * in the manifest registration of their application.
698      *
699      * @see android.telecom.TelecomManager#ACTION_SHOW_CALL_SETTINGS
700      * @see #ACTION_CONFIGURE_VOICEMAIL
701      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
702      */
703     public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU =
704             "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
705 
706     /**
707      * Open the voicemail settings activity to make changes to voicemail configuration.
708      *
709      * <p>
710      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} to
711      * configure voicemail.
712      * The {@link #EXTRA_HIDE_PUBLIC_SETTINGS} hides settings the dialer will modify through public
713      * API if set.
714      *
715      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
716      * @see #EXTRA_HIDE_PUBLIC_SETTINGS
717      */
718     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
719     public static final String ACTION_CONFIGURE_VOICEMAIL =
720             "android.telephony.action.CONFIGURE_VOICEMAIL";
721 
722     /**
723      * The boolean value indicating whether the voicemail settings activity launched by {@link
724      * #ACTION_CONFIGURE_VOICEMAIL} should hide settings accessible through public API. This is
725      * used by dialer implementations which provides their own voicemail settings UI, but still
726      * needs to expose device specific voicemail settings to the user.
727      *
728      * @see #ACTION_CONFIGURE_VOICEMAIL
729      * @see #METADATA_HIDE_VOICEMAIL_SETTINGS_MENU
730      */
731     public static final String EXTRA_HIDE_PUBLIC_SETTINGS =
732             "android.telephony.extra.HIDE_PUBLIC_SETTINGS";
733 
734     /**
735      * @hide
736      */
737     public static final boolean EMERGENCY_ASSISTANCE_ENABLED = true;
738 
739     /**
740      * The lookup key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
741      * for a String containing the new call state.
742      *
743      * <p class="note">
744      * Retrieve with
745      * {@link android.content.Intent#getStringExtra(String)}.
746      *
747      * @see #EXTRA_STATE_IDLE
748      * @see #EXTRA_STATE_RINGING
749      * @see #EXTRA_STATE_OFFHOOK
750      */
751     public static final String EXTRA_STATE = PhoneConstants.STATE_KEY;
752 
753     /**
754      * Value used with {@link #EXTRA_STATE} corresponding to
755      * {@link #CALL_STATE_IDLE}.
756      */
757     public static final String EXTRA_STATE_IDLE = PhoneConstants.State.IDLE.toString();
758 
759     /**
760      * Value used with {@link #EXTRA_STATE} corresponding to
761      * {@link #CALL_STATE_RINGING}.
762      */
763     public static final String EXTRA_STATE_RINGING = PhoneConstants.State.RINGING.toString();
764 
765     /**
766      * Value used with {@link #EXTRA_STATE} corresponding to
767      * {@link #CALL_STATE_OFFHOOK}.
768      */
769     public static final String EXTRA_STATE_OFFHOOK = PhoneConstants.State.OFFHOOK.toString();
770 
771     /**
772      * Extra key used with the {@link #ACTION_PHONE_STATE_CHANGED} broadcast
773      * for a String containing the incoming or outgoing phone number.
774      * <p>
775      * This extra is only populated for receivers of the {@link #ACTION_PHONE_STATE_CHANGED}
776      * broadcast which have been granted the {@link android.Manifest.permission#READ_CALL_LOG} and
777      * {@link android.Manifest.permission#READ_PHONE_STATE} permissions.
778      * <p>
779      * For incoming calls, the phone number is only guaranteed to be populated when the
780      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_RINGING}.
781      * If the incoming caller is from an unknown number, the extra will be populated with an empty
782      * string.
783      * For outgoing calls, the phone number is only guaranteed to be populated when the
784      * {@link #EXTRA_STATE} changes from {@link #EXTRA_STATE_IDLE} to {@link #EXTRA_STATE_OFFHOOK}.
785      * <p class="note">
786      * Retrieve with
787      * {@link android.content.Intent#getStringExtra(String)}.
788      * <p>
789      *
790      * @deprecated Companion apps for wearable devices should use the {@link InCallService} API
791      * to retrieve the phone number for calls instead.  Apps performing call screening should use
792      * the {@link CallScreeningService} API instead.
793      */
794     @Deprecated
795     public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
796 
797     /**
798      * Broadcast intent action indicating that call disconnect cause has changed.
799      *
800      * <p>
801      * The {@link #EXTRA_DISCONNECT_CAUSE} extra indicates the disconnect cause.
802      * The {@link #EXTRA_PRECISE_DISCONNECT_CAUSE} extra indicates the precise disconnect cause.
803      *
804      * <p class="note">
805      * Requires the READ_PRECISE_PHONE_STATE permission.
806      *
807      * @see #EXTRA_DISCONNECT_CAUSE
808      * @see #EXTRA_PRECISE_DISCONNECT_CAUSE
809      *
810      * @hide
811      */
812     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
813     public static final String ACTION_CALL_DISCONNECT_CAUSE_CHANGED =
814             "android.intent.action.CALL_DISCONNECT_CAUSE";
815 
816     /**
817      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
818      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
819      * containing the disconnect cause.
820      *
821      * @see DisconnectCause
822      *
823      * <p class="note">
824      * Retrieve with
825      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
826      *
827      * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
828      * @hide
829      */
830     @Deprecated
831     public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
832 
833     /**
834      * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
835      * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
836      * containing the disconnect cause provided by the RIL.
837      *
838      * @see PreciseDisconnectCause
839      *
840      * <p class="note">
841      * Retrieve with
842      * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
843      *
844      * @hide
845      */
846     public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
847 
848     /**
849      * Broadcast intent action for letting the default dialer to know to show voicemail
850      * notification.
851      *
852      * <p>
853      * The {@link #EXTRA_PHONE_ACCOUNT_HANDLE} extra indicates which {@link PhoneAccountHandle} the
854      * voicemail is received on.
855      * The {@link #EXTRA_NOTIFICATION_COUNT} extra indicates the total numbers of unheard
856      * voicemails.
857      * The {@link #EXTRA_VOICEMAIL_NUMBER} extra indicates the voicemail number if available.
858      * The {@link #EXTRA_CALL_VOICEMAIL_INTENT} extra is a {@link android.app.PendingIntent} that
859      * will call the voicemail number when sent. This extra will be empty if the voicemail number
860      * is not set, and {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} will be set instead.
861      * The {@link #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT} extra is a
862      * {@link android.app.PendingIntent} that will launch the voicemail settings. This extra is only
863      * available when the voicemail number is not set.
864      * The {@link #EXTRA_IS_REFRESH} extra indicates whether the notification is a refresh or a new
865      * notification.
866      *
867      * @see #EXTRA_PHONE_ACCOUNT_HANDLE
868      * @see #EXTRA_NOTIFICATION_COUNT
869      * @see #EXTRA_VOICEMAIL_NUMBER
870      * @see #EXTRA_CALL_VOICEMAIL_INTENT
871      * @see #EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT
872      * @see #EXTRA_IS_REFRESH
873      */
874     public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
875             "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
876 
877     /**
878      * The extra used with an {@link #ACTION_CONFIGURE_VOICEMAIL} and
879      * {@link #ACTION_SHOW_VOICEMAIL_NOTIFICATION} {@code Intent} to specify the
880      * {@link PhoneAccountHandle} the configuration or notification is for.
881      * <p class="note">
882      * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
883      */
884     public static final String EXTRA_PHONE_ACCOUNT_HANDLE =
885             "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
886 
887     /**
888      * The number of voice messages associated with the notification.
889      */
890     public static final String EXTRA_NOTIFICATION_COUNT =
891             "android.telephony.extra.NOTIFICATION_COUNT";
892 
893     /**
894      * The voicemail number.
895      */
896     public static final String EXTRA_VOICEMAIL_NUMBER =
897             "android.telephony.extra.VOICEMAIL_NUMBER";
898 
899     /**
900      * The intent to call voicemail.
901      */
902     public static final String EXTRA_CALL_VOICEMAIL_INTENT =
903             "android.telephony.extra.CALL_VOICEMAIL_INTENT";
904 
905     /**
906      * The intent to launch voicemail settings.
907      */
908     public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
909             "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
910 
911     /**
912      * Boolean value representing whether the {@link
913      * TelephonyManager#ACTION_SHOW_VOICEMAIL_NOTIFICATION} is new or a refresh of an existing
914      * notification. Notification refresh happens after reboot or connectivity changes. The user has
915      * already been notified for the voicemail so it should not alert the user, and should not be
916      * shown again if the user has dismissed it.
917      */
918     public static final String EXTRA_IS_REFRESH = "android.telephony.extra.IS_REFRESH";
919 
920     /**
921      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
922      * successfully handed over from WIFI to LTE.
923      * <p>
924      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
925      * The {@link Bundle} parameter is expected to be null when this connection event is used.
926      * @hide
927      */
928     public static final String EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE =
929             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE";
930 
931     /**
932      * {@link android.telecom.Connection} event used to indicate that an IMS call has be
933      * successfully handed over from LTE to WIFI.
934      * <p>
935      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
936      * The {@link Bundle} parameter is expected to be null when this connection event is used.
937      * @hide
938      */
939     public static final String EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI =
940             "android.telephony.event.EVENT_HANDOVER_VIDEO_FROM_LTE_TO_WIFI";
941 
942     /**
943      * {@link android.telecom.Connection} event used to indicate that an IMS call failed to be
944      * handed over from LTE to WIFI.
945      * <p>
946      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
947      * The {@link Bundle} parameter is expected to be null when this connection event is used.
948      * @hide
949      */
950     public static final String EVENT_HANDOVER_TO_WIFI_FAILED =
951             "android.telephony.event.EVENT_HANDOVER_TO_WIFI_FAILED";
952 
953     /**
954      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
955      * audio because the data limit was reached.
956      * <p>
957      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
958      * The {@link Bundle} parameter is expected to be null when this connection event is used.
959      * @hide
960      */
961     public static final String EVENT_DOWNGRADE_DATA_LIMIT_REACHED =
962             "android.telephony.event.EVENT_DOWNGRADE_DATA_LIMIT_REACHED";
963 
964     /**
965      * {@link android.telecom.Connection} event used to indicate that a video call was downgraded to
966      * audio because the data was disabled.
967      * <p>
968      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
969      * The {@link Bundle} parameter is expected to be null when this connection event is used.
970      * @hide
971      */
972     public static final String EVENT_DOWNGRADE_DATA_DISABLED =
973             "android.telephony.event.EVENT_DOWNGRADE_DATA_DISABLED";
974 
975     /**
976      * {@link android.telecom.Connection} event used to indicate that the InCall UI should notify
977      * the user when an international call is placed while on WFC only.
978      * <p>
979      * Used when the carrier config value
980      * {@link CarrierConfigManager#KEY_NOTIFY_INTERNATIONAL_CALL_ON_WFC_BOOL} is true, the device
981      * is on WFC (VoLTE not available) and an international number is dialed.
982      * <p>
983      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
984      * The {@link Bundle} parameter is expected to be null when this connection event is used.
985      * @hide
986      */
987     public static final String EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC =
988             "android.telephony.event.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC";
989 
990     /**
991      * {@link android.telecom.Connection} event used to indicate that an outgoing call has been
992      * forwarded to another number.
993      * <p>
994      * Sent in response to an IMS supplementary service notification indicating the call has been
995      * forwarded.
996      * <p>
997      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
998      * The {@link Bundle} parameter is expected to be null when this connection event is used.
999      * @hide
1000      */
1001     public static final String EVENT_CALL_FORWARDED =
1002             "android.telephony.event.EVENT_CALL_FORWARDED";
1003 
1004     /**
1005      * {@link android.telecom.Connection} event used to indicate that a supplementary service
1006      * notification has been received.
1007      * <p>
1008      * Sent via {@link android.telecom.Connection#sendConnectionEvent(String, Bundle)}.
1009      * The {@link Bundle} parameter is expected to include the following extras:
1010      * <ul>
1011      *     <li>{@link #EXTRA_NOTIFICATION_TYPE} - the notification type.</li>
1012      *     <li>{@link #EXTRA_NOTIFICATION_CODE} - the notification code.</li>
1013      *     <li>{@link #EXTRA_NOTIFICATION_MESSAGE} - human-readable message associated with the
1014      *     supplementary service notification.</li>
1015      * </ul>
1016      * @hide
1017      */
1018     public static final String EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION =
1019             "android.telephony.event.EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION";
1020 
1021     /**
1022      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1023      * the type of supplementary service notification which occurred.
1024      * Will be either
1025      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_1}
1026      * or
1027      * {@link com.android.internal.telephony.gsm.SuppServiceNotification#NOTIFICATION_TYPE_CODE_2}
1028      * <p>
1029      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1030      * @hide
1031      */
1032     public static final String EXTRA_NOTIFICATION_TYPE =
1033             "android.telephony.extra.NOTIFICATION_TYPE";
1034 
1035     /**
1036      * Integer extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} which indicates
1037      * the supplementary service notification which occurred.
1038      * <p>
1039      * Depending on the {@link #EXTRA_NOTIFICATION_TYPE}, the code will be one of the {@code CODE_*}
1040      * codes defined in {@link com.android.internal.telephony.gsm.SuppServiceNotification}.
1041      * <p>
1042      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1043      * @hide
1044      */
1045     public static final String EXTRA_NOTIFICATION_CODE =
1046             "android.telephony.extra.NOTIFICATION_CODE";
1047 
1048     /**
1049      * {@link CharSequence} extra key used with {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION}
1050      * which contains a human-readable message which can be displayed to the user for the
1051      * supplementary service notification.
1052      * <p>
1053      * Set in the extras for the {@link #EVENT_SUPPLEMENTARY_SERVICE_NOTIFICATION} connection event.
1054      * @hide
1055      */
1056     public static final String EXTRA_NOTIFICATION_MESSAGE =
1057             "android.telephony.extra.NOTIFICATION_MESSAGE";
1058 
1059     /* Visual voicemail protocols */
1060 
1061     /**
1062      * The OMTP protocol.
1063      */
1064     public static final String VVM_TYPE_OMTP = "vvm_type_omtp";
1065 
1066     /**
1067      * A flavor of OMTP protocol with a different mobile originated (MO) format
1068      */
1069     public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
1070 
1071     /**
1072      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating whether visual
1073      * voicemail was enabled or disabled by the user. If the user never explicitly changed this
1074      * setting, this key will not exist.
1075      *
1076      * @see #getVisualVoicemailSettings()
1077      * @hide
1078      */
1079     @SystemApi
1080     public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL =
1081             "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
1082 
1083     /**
1084      * Key in bundle returned by {@link #getVisualVoicemailPackageName()}, indicating the voicemail
1085      * access PIN scrambled during the auto provisioning process. The user is expected to reset
1086      * their PIN if this value is not {@code null}.
1087      *
1088      * @see #getVisualVoicemailSettings()
1089      * @hide
1090      */
1091     @SystemApi
1092     public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING =
1093             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
1094 
1095     /**
1096      * Broadcast action to be received by Broadcast receivers.
1097      *
1098      * Indicates multi-SIM configuration is changed. For example, it changed
1099      * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
1100      *
1101      * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
1102      * or that all steps during multi-SIM change are done. To know those information you still need
1103      * to listen to SIM_STATE changes or active subscription changes.
1104      *
1105      * See extra of {@link #EXTRA_ACTIVE_SIM_SUPPORTED_COUNT} for updated value.
1106      */
1107     public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
1108             "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
1109 
1110 
1111     /**
1112      * The number of active SIM supported by current multi-SIM config. It's not related to how many
1113      * SIM/subscriptions are currently active.
1114      *
1115      * Same value will be returned by {@link #getActiveModemCount()}.
1116      *
1117      * For single SIM mode, it's 1.
1118      * For DSDS or DSDA mode, it's 2.
1119      * For triple-SIM mode, it's 3.
1120      *
1121      * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
1122      *
1123      * type: integer
1124      */
1125     public static final String EXTRA_ACTIVE_SIM_SUPPORTED_COUNT =
1126             "android.telephony.extra.ACTIVE_SIM_SUPPORTED_COUNT";
1127 
1128     /**
1129      * @hide
1130      */
1131     public static final String USSD_RESPONSE = "USSD_RESPONSE";
1132 
1133     /**
1134      * USSD return code success.
1135      * @hide
1136      */
1137     public static final int USSD_RETURN_SUCCESS = 100;
1138 
1139     /**
1140      * Failed code returned when the mobile network has failed to complete a USSD request.
1141      * <p>
1142      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1143      * TelephonyManager, String, int)}.
1144      */
1145     public static final int USSD_RETURN_FAILURE = -1;
1146 
1147     /**
1148      * Failure code returned when a USSD request has failed to execute because the Telephony
1149      * service is unavailable.
1150      * <p>
1151      * Returned via {@link TelephonyManager.UssdResponseCallback#onReceiveUssdResponseFailed(
1152      * TelephonyManager, String, int)}.
1153      */
1154     public static final int USSD_ERROR_SERVICE_UNAVAIL = -2;
1155 
1156     /**
1157      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which leaves the roaming
1158      * mode set to the radio default or to the user's preference if they've indicated one.
1159      */
1160     public static final int CDMA_ROAMING_MODE_RADIO_DEFAULT = -1;
1161     /**
1162      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which only permits
1163      * connections on home networks.
1164      */
1165     public static final int CDMA_ROAMING_MODE_HOME = 0;
1166     /**
1167      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1168      * affiliated networks.
1169      */
1170     public static final int CDMA_ROAMING_MODE_AFFILIATED = 1;
1171     /**
1172      * Value for {@link CarrierConfigManager#KEY_CDMA_ROAMING_MODE_INT} which permits roaming on
1173      * any network.
1174      */
1175     public static final int CDMA_ROAMING_MODE_ANY = 2;
1176 
1177     /** @hide */
1178     @IntDef(prefix = { "CDMA_ROAMING_MODE_" }, value = {
1179             CDMA_ROAMING_MODE_RADIO_DEFAULT,
1180             CDMA_ROAMING_MODE_HOME,
1181             CDMA_ROAMING_MODE_AFFILIATED,
1182             CDMA_ROAMING_MODE_ANY
1183     })
1184     @Retention(RetentionPolicy.SOURCE)
1185     public @interface CdmaRoamingMode{}
1186 
1187     /**
1188      * An unknown carrier id. It could either be subscription unavailable or the subscription
1189      * carrier cannot be recognized. Unrecognized carriers here means
1190      * {@link #getSimOperator() MCC+MNC} cannot be identified.
1191      */
1192     public static final int UNKNOWN_CARRIER_ID = -1;
1193 
1194     /**
1195      * An unknown carrier id list version.
1196      * @hide
1197      */
1198     @TestApi
1199     public static final int UNKNOWN_CARRIER_ID_LIST_VERSION = -1;
1200 
1201     /**
1202      * Broadcast Action: The subscription carrier identity has changed.
1203      * This intent could be sent on the following events:
1204      * <ul>
1205      *   <li>Subscription absent. Carrier identity could change from a valid id to
1206      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID}.</li>
1207      *   <li>Subscription loaded. Carrier identity could change from
1208      *   {@link TelephonyManager#UNKNOWN_CARRIER_ID} to a valid id.</li>
1209      *   <li>The subscription carrier is recognized after a remote update.</li>
1210      * </ul>
1211      * The intent will have the following extra values:
1212      * <ul>
1213      *   <li>{@link #EXTRA_CARRIER_ID} The up-to-date carrier id of the current subscription id.
1214      *   </li>
1215      *   <li>{@link #EXTRA_CARRIER_NAME} The up-to-date carrier name of the current subscription.
1216      *   </li>
1217      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1218      *   identity.
1219      *   </li>
1220      * </ul>
1221      * <p class="note">This is a protected intent that can only be sent by the system.
1222      */
1223     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1224     public static final String ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED =
1225             "android.telephony.action.SUBSCRIPTION_CARRIER_IDENTITY_CHANGED";
1226 
1227     /**
1228      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which indicates
1229      * the updated carrier id returned by {@link TelephonyManager#getSimCarrierId()}.
1230      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1231      * the carrier cannot be identified.
1232      */
1233     public static final String EXTRA_CARRIER_ID = "android.telephony.extra.CARRIER_ID";
1234 
1235     /**
1236      * An string extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} which
1237      * indicates the updated carrier name of the current subscription.
1238      * @see TelephonyManager#getSimCarrierIdName()
1239      * <p>Carrier name is a user-facing name of the carrier id {@link #EXTRA_CARRIER_ID},
1240      * usually the brand name of the subsidiary (e.g. T-Mobile).
1241      */
1242     public static final String EXTRA_CARRIER_NAME = "android.telephony.extra.CARRIER_NAME";
1243 
1244     /**
1245      * Broadcast Action: The subscription specific carrier identity has changed.
1246      *
1247      * A specific carrier ID returns the fine-grained carrier ID of the current subscription.
1248      * It can represent the fact that a carrier may be in effect an aggregation of other carriers
1249      * (ie in an MVNO type scenario) where each of these specific carriers which are used to make
1250      * up the actual carrier service may have different carrier configurations.
1251      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
1252      * different carrier configuration for different service offering such as a prepaid plan.
1253      *
1254      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
1255      * about the carrier itself should use the regular carrier ID returned by
1256      * {@link #getSimCarrierId()}.
1257      *
1258      * <p>Similar like {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED}, this intent will be
1259      * sent on the event of {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} while its also
1260      * possible to be sent without {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} when
1261      * specific carrier ID changes while carrier ID remains the same.
1262      * e.g, the same subscription switches to different IMSI could potentially change its
1263      * specific carrier ID while carrier id remains the same.
1264      * @see #getSimSpecificCarrierId()
1265      * @see #getSimCarrierId()
1266      *
1267      * The intent will have the following extra values:
1268      * <ul>
1269      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_ID} The up-to-date specific carrier id of the
1270      *   current subscription.
1271      *   </li>
1272      *   <li>{@link #EXTRA_SPECIFIC_CARRIER_NAME} The up-to-date name of the specific carrier id.
1273      *   </li>
1274      *   <li>{@link #EXTRA_SUBSCRIPTION_ID} The subscription id associated with the changed carrier
1275      *   identity.
1276      *   </li>
1277      * </ul>
1278      * <p class="note">This is a protected intent that can only be sent by the system.
1279      */
1280     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1281     public static final String ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED =
1282             "android.telephony.action.SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED";
1283 
1284     /**
1285      * An int extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED} which
1286      * indicates the updated specific carrier id returned by
1287      * {@link TelephonyManager#getSimSpecificCarrierId()}. Note, its possible specific carrier id
1288      * changes while {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} remains the same
1289      * e.g, when subscription switch to different IMSIs.
1290      * <p>Will be {@link TelephonyManager#UNKNOWN_CARRIER_ID} if the subscription is unavailable or
1291      * the carrier cannot be identified.
1292      */
1293     public static final String EXTRA_SPECIFIC_CARRIER_ID =
1294             "android.telephony.extra.SPECIFIC_CARRIER_ID";
1295 
1296     /**
1297      * An string extra used with {@link #ACTION_SUBSCRIPTION_SPECIFIC_CARRIER_IDENTITY_CHANGED}
1298      * which indicates the updated specific carrier name returned by
1299      * {@link TelephonyManager#getSimSpecificCarrierIdName()}.
1300      * <p>it's a user-facing name of the specific carrier id {@link #EXTRA_SPECIFIC_CARRIER_ID}
1301      * e.g, Tracfone-AT&T
1302      */
1303     public static final String EXTRA_SPECIFIC_CARRIER_NAME =
1304             "android.telephony.extra.SPECIFIC_CARRIER_NAME";
1305 
1306     /**
1307      * An int extra used with {@link #ACTION_SUBSCRIPTION_CARRIER_IDENTITY_CHANGED} to indicate the
1308      * subscription which has changed; or in general whenever a subscription ID needs specified.
1309      */
1310     public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
1311 
1312     /**
1313      * Broadcast Action: The Service Provider string(s) have been updated. Activities or
1314      * services that use these strings should update their display.
1315      *
1316      * <p>The intent will have the following extra values:
1317      * <dl>
1318      *   <dt>{@link #EXTRA_SHOW_PLMN}</dt>
1319      *   <dd>Boolean that indicates whether the PLMN should be shown.</dd>
1320      *   <dt>{@link #EXTRA_PLMN}</dt>
1321      *   <dd>The operator name of the registered network, as a string.</dd>
1322      *   <dt>{@link #EXTRA_SHOW_SPN}</dt>
1323      *   <dd>Boolean that indicates whether the SPN should be shown.</dd>
1324      *   <dt>{@link #EXTRA_SPN}</dt>
1325      *   <dd>The service provider name, as a string.</dd>
1326      *   <dt>{@link #EXTRA_DATA_SPN}</dt>
1327      *   <dd>The service provider name for data service, as a string.</dd>
1328      * </dl>
1329      *
1330      * Note that {@link #EXTRA_SHOW_PLMN} may indicate that {@link #EXTRA_PLMN} should be displayed,
1331      * even though the value for {@link #EXTRA_PLMN} is null. This can happen, for example, if the
1332      * phone has not registered to a network yet. In this case the receiver may substitute an
1333      * appropriate placeholder string (eg, "No service").
1334      *
1335      * It is recommended to display {@link #EXTRA_PLMN} before / above {@link #EXTRA_SPN} if
1336      * both are displayed.
1337      *
1338      * <p>Note: this is a protected intent that can only be sent by the system.
1339      * @hide
1340      */
1341     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1342     public static final String ACTION_SERVICE_PROVIDERS_UPDATED =
1343             "android.telephony.action.SERVICE_PROVIDERS_UPDATED";
1344 
1345     /**
1346      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1347      * whether the PLMN should be shown.
1348      * @hide
1349      */
1350     public static final String EXTRA_SHOW_PLMN = "android.telephony.extra.SHOW_PLMN";
1351 
1352     /**
1353      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1354      * the operator name of the registered network.
1355      * @hide
1356      */
1357     public static final String EXTRA_PLMN = "android.telephony.extra.PLMN";
1358 
1359     /**
1360      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1361      * whether the PLMN should be shown.
1362      * @hide
1363      */
1364     public static final String EXTRA_SHOW_SPN = "android.telephony.extra.SHOW_SPN";
1365 
1366     /**
1367      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1368      * the service provider name.
1369      * @hide
1370      */
1371     public static final String EXTRA_SPN = "android.telephony.extra.SPN";
1372 
1373     /**
1374      * String intent extra to be used with {@link ACTION_SERVICE_PROVIDERS_UPDATED} to indicate
1375      * the service provider name for data service.
1376      * @hide
1377      */
1378     public static final String EXTRA_DATA_SPN = "android.telephony.extra.DATA_SPN";
1379 
1380     /**
1381      * Broadcast intent action indicating that when data stall recovery is attempted by Telephony,
1382      * intended for report every data stall recovery step attempted.
1383      *
1384      * <p>
1385      * The {@link #EXTRA_RECOVERY_ACTION} extra indicates the action associated with the data
1386      * stall recovery.
1387      * The phone id where the data stall recovery is attempted.
1388      *
1389      * <p class="note">
1390      * Requires the READ_PHONE_STATE permission.
1391      *
1392      * <p class="note">
1393      * This is a protected intent that can only be sent by the system.
1394      *
1395      * @see #EXTRA_RECOVERY_ACTION
1396      *
1397      * @hide
1398      */
1399     // TODO(b/78370030) : Restrict this to system applications only
1400     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1401     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1402     public static final String ACTION_DATA_STALL_DETECTED =
1403             "android.intent.action.DATA_STALL_DETECTED";
1404 
1405     /**
1406      * A service action that identifies
1407      * a {@link android.service.carrier.CarrierMessagingClientService} subclass in the
1408      * AndroidManifest.xml.
1409      *
1410      * <p>See {@link android.service.carrier.CarrierMessagingClientService} for the details.
1411      */
1412     @SdkConstant(SdkConstantType.SERVICE_ACTION)
1413     public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE =
1414             "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
1415 
1416     /**
1417      * An int extra used with {@link #ACTION_DATA_STALL_DETECTED} to indicate the
1418      * action associated with the data stall recovery.
1419      *
1420      * @see #ACTION_DATA_STALL_DETECTED
1421      *
1422      * @hide
1423      */
1424     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
1425 
1426     private static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000;
1427 
1428     /**
1429      * Intent sent when an error occurs that debug tools should log and possibly take further
1430      * action such as capturing vendor-specific logs.
1431      *
1432      * A privileged application that reads these events should take appropriate vendor-specific
1433      * action to record the event and collect further information to assist in analysis, debugging,
1434      * and resolution of any associated issue.
1435      *
1436      * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
1437      * should generally be sent at a low rate. Instead, this mechanism should be used for the
1438      * framework to notify a debugging application that an event (such as a bug) has occured
1439      * within the framework if that event should trigger the collection and preservation of other
1440      * more detailed device state for debugging.
1441      *
1442      * <p>At most one application can receive these events and should register a receiver in
1443      * in the application manifest. For performance reasons, if no application to receive these
1444      * events is detected at boot, then these events will not be sent.
1445      *
1446      * <p>Each event will include an {@link EXTRA_ANOMALY_ID} that will uniquely identify the
1447      * event that has occurred. Each event will be sent to the diagnostic monitor only once per
1448      * boot cycle (as another optimization).
1449      *
1450      * @see #EXTRA_ANOMALY_ID
1451      * @see #EXTRA_ANOMALY_DESCRIPTION
1452      * @hide
1453      */
1454     @SystemApi
1455     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
1456     public static final String ACTION_ANOMALY_REPORTED =
1457             "android.telephony.action.ANOMALY_REPORTED";
1458 
1459     /**
1460      * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
1461      *
1462      * This field must be included in all {@link ACTION_ANOMALY_REPORTED} events.
1463      *
1464      * @see #ACTION_ANOMALY_REPORTED
1465      * @hide
1466      */
1467     @SystemApi
1468     public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
1469 
1470     /**
1471      * A freeform string description of the Anomaly.
1472      *
1473      * This field is optional for all {@link ACTION_ANOMALY_REPORTED}s, as a guideline should not
1474      * exceed 80 characters, and should be as short as possible to convey the essence of the event.
1475      *
1476      * @see #ACTION_ANOMALY_REPORTED
1477      * @hide
1478      */
1479     @SystemApi
1480     public static final String EXTRA_ANOMALY_DESCRIPTION =
1481             "android.telephony.extra.ANOMALY_DESCRIPTION";
1482 
1483     /**
1484      * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
1485      *
1486      * @hide
1487      */
1488     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1489     public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
1490             "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
1491 
1492     /**
1493      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1494      * to indicate what type of SIM selection is needed.
1495      *
1496      * @hide
1497      */
1498     public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
1499             "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
1500 
1501     /** @hide */
1502     @IntDef({
1503             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE,
1504             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA,
1505             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE,
1506             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS,
1507             EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL
1508     })
1509     @Retention(RetentionPolicy.SOURCE)
1510     public @interface DefaultSubscriptionSelectType{}
1511 
1512     /**
1513      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1514      * to indicate there's no need to re-select any default subscription.
1515      * @hide
1516      */
1517     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
1518 
1519     /**
1520      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1521      * to indicate there's a need to select default data subscription.
1522      * @hide
1523      */
1524     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
1525 
1526     /**
1527      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1528      * to indicate there's a need to select default voice call subscription.
1529      * @hide
1530      */
1531     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
1532 
1533     /**
1534      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1535      * to indicate there's a need to select default sms subscription.
1536      * @hide
1537      */
1538     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
1539 
1540     /**
1541      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1542      * to indicate user to decide whether current SIM should be preferred for all
1543      * data / voice / sms. {@link #EXTRA_SUBSCRIPTION_ID} will specified to indicate
1544      * which subscription should be the default subscription.
1545      * @hide
1546      */
1547     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_ALL = 4;
1548 
1549     /**
1550      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1551      * to indicate that default subscription for data/sms/voice is now determined, that
1552      * it should dismiss any dialog or pop-ups that is asking user to select default sub.
1553      * This is used when, for example, opportunistic subscription is configured. At that
1554      * time the primary becomes default sub there's no need to ask user to select anymore.
1555      * @hide
1556      */
1557     public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS = 5;
1558 
1559     /**
1560      * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1561      * to indicate if the SIM combination in DSDS has limitation or compatible issue.
1562      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios.
1563      *
1564      * @hide
1565      */
1566     public static final String EXTRA_SIM_COMBINATION_WARNING_TYPE =
1567             "android.telephony.extra.SIM_COMBINATION_WARNING_TYPE";
1568 
1569     /** @hide */
1570     @IntDef({
1571             EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE,
1572             EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA
1573     })
1574     @Retention(RetentionPolicy.SOURCE)
1575     public @interface SimCombinationWarningType{}
1576 
1577     /**
1578      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1579      * to indicate there's no SIM combination warning.
1580      * @hide
1581      */
1582     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_NONE = 0;
1583 
1584     /**
1585      * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
1586      * to indicate two active SIMs are both CDMA hence there might be functional limitation.
1587      * @hide
1588      */
1589     public static final int EXTRA_SIM_COMBINATION_WARNING_TYPE_DUAL_CDMA = 1;
1590 
1591     /**
1592      * String intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
1593      * to indicate what's the name of SIM combination it has limitation or compatible issue.
1594      * e.g. two CDMA SIMs may disrupt each other's voice call in certain scenarios, and the
1595      * name will be "operator1 & operator2".
1596      *
1597      * @hide
1598      */
1599     public static final String EXTRA_SIM_COMBINATION_NAMES =
1600             "android.telephony.extra.SIM_COMBINATION_NAMES";
1601 
1602     /**
1603      * <p>Broadcast Action: The emergency callback mode is changed.
1604      * <ul>
1605      *   <li><em>EXTRA_PHONE_IN_ECM_STATE</em> - A boolean value,true=phone in ECM,
1606      *   false=ECM off</li>
1607      * </ul>
1608      * <p class="note">
1609      * You can <em>not</em> receive this through components declared
1610      * in manifests, only by explicitly registering for it with
1611      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1612      * android.content.IntentFilter) Context.registerReceiver()}.
1613      *
1614      * <p class="note">This is a protected intent that can only be sent by the system.
1615      *
1616      * @see #EXTRA_PHONE_IN_ECM_STATE
1617      *
1618      * @hide
1619      */
1620     @SystemApi
1621     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1622     @SuppressLint("ActionValue")
1623     public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
1624             "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
1625 
1626 
1627     /**
1628      * Extra included in {@link #ACTION_EMERGENCY_CALLBACK_MODE_CHANGED}.
1629      * Indicates whether the phone is in an emergency phone state.
1630      *
1631      * @hide
1632      */
1633     @SystemApi
1634     public static final String EXTRA_PHONE_IN_ECM_STATE =
1635             "android.telephony.extra.PHONE_IN_ECM_STATE";
1636 
1637     /**
1638      * Broadcast action sent when a data connection is redirected with validation failure.
1639      *
1640      * This action is intended for sim/account status checks and only sent to the carrier apps
1641      * specified in the carrier config for the subscription ID that's attached to this intent.
1642      *
1643      * The intent will have the following extra values:
1644      * <ul>
1645      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1646      *   <li>{@link #EXTRA_REDIRECTION_URL}</li><dd>A string indicating the redirection url</dd>
1647      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1648      *          <dd>The subscription ID on which the validation failure happened.</dd>
1649      * </ul>
1650      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1651      */
1652     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1653     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
1654             "android.telephony.action.CARRIER_SIGNAL_REDIRECTED";
1655 
1656     /**
1657      * Broadcast action sent when a data connection setup fails.
1658      *
1659      * This action is intended for sim/account status checks and only sent to the carrier apps
1660      * specified in the carrier config for the subscription ID that's attached to this intent.
1661      *
1662      * The intent will have the following extra values:
1663      * <ul>
1664      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1665      *   <li>{@link #EXTRA_DATA_FAIL_CAUSE}</li><dd>A integer indicating the data fail cause.</dd>
1666      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1667      *          <dd>The subscription ID on which the data setup failure happened.</dd>
1668      * </ul>
1669      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1670      */
1671     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1672     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
1673             "android.telephony.action.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
1674 
1675     /**
1676      * Broadcast action sent when a PCO value becomes available from the modem.
1677      *
1678      * This action is intended for sim/account status checks and only sent to the carrier apps
1679      * specified in the carrier config for the subscription ID that's attached to this intent.
1680      *
1681      * The intent will have the following extra values:</p>
1682      * <ul>
1683      *   <li>{@link #EXTRA_APN_TYPE}</li><dd>An integer indicating the apn type.</dd>
1684      *   <li>{@link #EXTRA_APN_PROTOCOL}</li><dd>An integer indicating the protocol of the apn
1685      *      connection</dd>
1686      *   <li>{@link #EXTRA_PCO_ID}</li><dd>An integer indicating the PCO id for the data.</dd>
1687      *   <li>{@link #EXTRA_PCO_VALUE}</li><dd>A byte array of PCO data read from modem.</dd>
1688      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1689      *          <dd>The subscription ID for which the PCO info was received.</dd>
1690      * </ul>
1691      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1692      */
1693     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1694     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
1695             "android.telephony.action.CARRIER_SIGNAL_PCO_VALUE";
1696 
1697     /**
1698      * Broadcast action sent when the availability of the system default network changes.
1699      *
1700      * @see ConnectivityManager#registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)
1701      *
1702      * This action is intended for carrier apps to set/reset carrier actions. It is only sent to the
1703      * carrier apps specified in the carrier config for the subscription ID attached to this intent.
1704      *
1705      * The intent will have the following extra values:</p>
1706      * <ul>
1707      *   <li>{@link #EXTRA_DEFAULT_NETWORK_AVAILABLE}</li>
1708      *   <dd>{@code true} if the default network is now available, {@code false} otherwise.</dd>
1709      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1710      *          <dd>The subscription ID on which the default network availability changed.</dd>
1711      * </ul>
1712      * <p class="note">This is a protected intent that can only be sent by the system. </p>
1713      */
1714     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1715     public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE =
1716             "android.telephony.action.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
1717 
1718     /**
1719      * Broadcast action sent when carrier apps should reset their internal state.
1720      *
1721      * Sent when certain events such as turning on/off mobile data, removing the SIM, etc. require
1722      * carrier apps to reset their state.
1723      *
1724      * This action is intended to signal carrier apps to perform cleanup operations. It is only sent
1725      * to the carrier apps specified in the carrier config for the subscription ID attached to
1726      * this intent.
1727      *
1728      * The intent will have the following extra values:</p>
1729      * <ul>
1730      *   <li>{@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX}</li>
1731      *          <dd>The subscription ID for which state should be reset.</dd>
1732      * </ul>
1733      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1734      */
1735     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1736     public static final String ACTION_CARRIER_SIGNAL_RESET =
1737             "android.telephony.action.CARRIER_SIGNAL_RESET";
1738 
1739     /**
1740      * String extra containing the redirection URL sent with
1741      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}.
1742      */
1743     public static final String EXTRA_REDIRECTION_URL = "android.telephony.extra.REDIRECTION_URL";
1744 
1745     /**
1746      * An integer extra containing the data fail cause.
1747      *
1748      * Sent with {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED}. See {@link DataFailCause}
1749      * for a list of possible values.
1750      */
1751     public static final String EXTRA_DATA_FAIL_CAUSE = "android.telephony.extra.DATA_FAIL_CAUSE";
1752 
1753     /**
1754      * An integer extra containing the APN type.
1755      *
1756      * Sent with the  {@link #ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED},
1757      * {@link #ACTION_CARRIER_SIGNAL_REDIRECTED}, and {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE}
1758      * broadcasts.
1759      * See the {@code TYPE_} constants in {@link ApnSetting} for a list of possible values.
1760      */
1761     public static final String EXTRA_APN_TYPE = "android.telephony.extra.APN_TYPE";
1762 
1763     /**
1764      * An integer extra containing the protocol of the apn connection.
1765      *
1766      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
1767      * See the {@code PROTOCOL_*} constants in {@link ApnSetting} for a list of possible values.
1768      */
1769     public static final String EXTRA_APN_PROTOCOL = "android.telephony.extra.APN_PROTOCOL";
1770 
1771     /**
1772      * An integer extra indicating the ID for the PCO data.
1773      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
1774      */
1775     public static final String EXTRA_PCO_ID = "android.telephony.extra.PCO_ID";
1776 
1777     /**
1778      * A byte array extra containing PCO data read from the modem.
1779      * Sent with the {@link #ACTION_CARRIER_SIGNAL_PCO_VALUE} broadcast.
1780      */
1781     public static final String EXTRA_PCO_VALUE = "android.telephony.extra.PCO_VALUE";
1782 
1783     /**
1784      * A boolean extra indicating the availability of the default network.
1785      * Sent with the {@link #ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE} broadcast.
1786      */
1787     public static final String EXTRA_DEFAULT_NETWORK_AVAILABLE =
1788             "android.telephony.extra.DEFAULT_NETWORK_AVAILABLE";
1789 
1790     /**
1791      * <p>Broadcast Action: The emergency call state is changed.
1792      * <ul>
1793      *   <li><em>EXTRA_PHONE_IN_EMERGENCY_CALL</em> - A boolean value, true if phone in emergency
1794      *   call, false otherwise</li>
1795      * </ul>
1796      * <p class="note">
1797      * You can <em>not</em> receive this through components declared
1798      * in manifests, only by explicitly registering for it with
1799      * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
1800      * android.content.IntentFilter) Context.registerReceiver()}.
1801      *
1802      * <p class="note">This is a protected intent that can only be sent by the system.
1803      *
1804      * @see #EXTRA_PHONE_IN_EMERGENCY_CALL
1805      *
1806      * @hide
1807      */
1808     @SystemApi
1809     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1810     @SuppressLint("ActionValue")
1811     public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
1812             "android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
1813 
1814 
1815     /**
1816      * Extra included in {@link #ACTION_EMERGENCY_CALL_STATE_CHANGED}.
1817      * It indicates whether the phone is making an emergency call.
1818      *
1819      * @hide
1820      */
1821     @SystemApi
1822     public static final String EXTRA_PHONE_IN_EMERGENCY_CALL =
1823             "android.telephony.extra.PHONE_IN_EMERGENCY_CALL";
1824 
1825     /**
1826      * <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
1827      * <p class="note">.
1828      * This is to pop up a notice to show user that the phone is in emergency callback mode
1829      * and data calls and outgoing sms are blocked.
1830      *
1831      * <p class="note">This is a protected intent that can only be sent by the system.
1832      *
1833      * @hide
1834      */
1835     @SystemApi
1836     public static final String ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS =
1837             "android.telephony.action.SHOW_NOTICE_ECM_BLOCK_OTHERS";
1838 
1839     /**
1840      * Broadcast Action: The default data subscription has changed in a multi-SIM device.
1841      * This has the following extra values:</p>
1842      * <ul>
1843      *   <li><em>subscription</em> - A int, the current data default subscription.</li>
1844      * </ul>
1845      *
1846      * @hide
1847      */
1848     @SystemApi
1849     @SuppressLint("ActionValue")
1850     public static final String ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED =
1851             "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED";
1852 
1853     /**
1854      * Broadcast Action: The default voice subscription has changed in a mult-SIm device.
1855      * This has the following extra values:</p>
1856      * <ul>
1857      *   <li><em>subscription</em> - A int, the current voice default subscription.</li>
1858      * </ul>
1859      *
1860      * @hide
1861      */
1862     @SystemApi
1863     @SuppressLint("ActionValue")
1864     public static final String ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED =
1865             "android.intent.action.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED";
1866 
1867     /**
1868      * Broadcast Action: This triggers a client initiated OMA-DM session to the OMA server.
1869      * <p class="note">
1870      * Open Mobile Alliance (OMA) Device Management (DM).
1871      *
1872      * This intent is used by the system components to trigger OMA-DM
1873      *
1874      * @hide
1875      */
1876     @SystemApi
1877     @SuppressLint("ActionValue")
1878     public static final String ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE =
1879             "com.android.omadm.service.CONFIGURATION_UPDATE";
1880 
1881     //
1882     //
1883     // Device Info
1884     //
1885     //
1886 
1887     /**
1888      * Returns the software version number for the device, for example,
1889      * the IMEI/SV for GSM phones. Return null if the software version is
1890      * not available.
1891      * <p>
1892      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}.
1893      */
1894     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1895     @Nullable
getDeviceSoftwareVersion()1896     public String getDeviceSoftwareVersion() {
1897         return getDeviceSoftwareVersion(getSlotIndex());
1898     }
1899 
1900     /**
1901      * Returns the software version number for the device, for example,
1902      * the IMEI/SV for GSM phones. Return null if the software version is
1903      * not available.
1904      * <p>
1905      * Requires Permission: READ_PHONE_STATE.
1906      *
1907      * @param slotIndex of which deviceID is returned
1908      *
1909      * @hide
1910      */
1911     @SystemApi
1912     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
1913     @Nullable
getDeviceSoftwareVersion(int slotIndex)1914     public String getDeviceSoftwareVersion(int slotIndex) {
1915         ITelephony telephony = getITelephony();
1916         if (telephony == null) return null;
1917 
1918         try {
1919             return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
1920                     getAttributionTag());
1921         } catch (RemoteException ex) {
1922             return null;
1923         } catch (NullPointerException ex) {
1924             return null;
1925         }
1926     }
1927 
1928     /**
1929      * Returns the unique device ID, for example, the IMEI for GSM and the MEID
1930      * or ESN for CDMA phones. Return null if device ID is not available.
1931      *
1932      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
1933      * restrictions, and apps are recommended to use resettable identifiers (see <a
1934      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
1935      * method can be invoked if one of the following requirements is met:
1936      * <ul>
1937      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
1938      *     is a privileged permission that can only be granted to apps preloaded on the device.
1939      *     <li>If the calling app is the device owner of a fully-managed device, a profile
1940      *     owner of an organization-owned device, or their delegates (see {@link
1941      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
1942      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
1943      *     active subscription.
1944      *     <li>If the calling app is the default SMS role holder (see {@link
1945      *     RoleManager#isRoleHeld(String)}).
1946      * </ul>
1947      *
1948      * <p>If the calling app does not meet one of these requirements then this method will behave
1949      * as follows:
1950      *
1951      * <ul>
1952      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
1953      *     READ_PHONE_STATE permission then null is returned.</li>
1954      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
1955      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
1956      *     higher, then a SecurityException is thrown.</li>
1957      * </ul>
1958      *
1959      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
1960      * MEID for CDMA.
1961      */
1962     @Deprecated
1963     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
1964     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId()1965     public String getDeviceId() {
1966         try {
1967             ITelephony telephony = getITelephony();
1968             if (telephony == null)
1969                 return null;
1970             return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
1971                     mContext.getAttributionTag());
1972         } catch (RemoteException ex) {
1973             return null;
1974         } catch (NullPointerException ex) {
1975             return null;
1976         }
1977     }
1978 
1979     /**
1980      * Returns the unique device ID of a subscription, for example, the IMEI for
1981      * GSM and the MEID for CDMA phones. Return null if device ID is not available.
1982      *
1983      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
1984      * restrictions, and apps are recommended to use resettable identifiers (see <a
1985      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
1986      * method can be invoked if one of the following requirements is met:
1987      * <ul>
1988      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
1989      *     is a privileged permission that can only be granted to apps preloaded on the device.
1990      *     <li>If the calling app is the device owner of a fully-managed device, a profile
1991      *     owner of an organization-owned device, or their delegates (see {@link
1992      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
1993      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
1994      *     active subscription.
1995      *     <li>If the calling app is the default SMS role holder (see {@link
1996      *     RoleManager#isRoleHeld(String)}).
1997      * </ul>
1998      *
1999      * <p>If the calling app does not meet one of these requirements then this method will behave
2000      * as follows:
2001      *
2002      * <ul>
2003      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2004      *     READ_PHONE_STATE permission then null is returned.</li>
2005      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2006      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2007      *     higher, then a SecurityException is thrown.</li>
2008      * </ul>
2009      *
2010      * @param slotIndex of which deviceID is returned
2011      *
2012      * @deprecated Use {@link #getImei} which returns IMEI for GSM or {@link #getMeid} which returns
2013      * MEID for CDMA.
2014      */
2015     @Deprecated
2016     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2017     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDeviceId(int slotIndex)2018     public String getDeviceId(int slotIndex) {
2019         // FIXME this assumes phoneId == slotIndex
2020         try {
2021             IPhoneSubInfo info = getSubscriberInfoService();
2022             if (info == null)
2023                 return null;
2024             return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
2025                     mContext.getAttributionTag());
2026         } catch (RemoteException ex) {
2027             return null;
2028         } catch (NullPointerException ex) {
2029             return null;
2030         }
2031     }
2032 
2033     /**
2034      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2035      * available.
2036      *
2037      * See {@link #getImei(int)} for details on the required permissions and behavior
2038      * when the caller does not hold sufficient permissions.
2039      */
2040     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2041     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei()2042     public String getImei() {
2043         return getImei(getSlotIndex());
2044     }
2045 
2046     /**
2047      * Returns the IMEI (International Mobile Equipment Identity). Return null if IMEI is not
2048      * available.
2049      *
2050      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2051      * restrictions, and apps are recommended to use resettable identifiers (see <a
2052      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2053      * method can be invoked if one of the following requirements is met:
2054      * <ul>
2055      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2056      *     is a privileged permission that can only be granted to apps preloaded on the device.
2057      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2058      *     owner of an organization-owned device, or their delegates (see {@link
2059      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2060      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2061      *     active subscription.
2062      *     <li>If the calling app is the default SMS role holder (see {@link
2063      *     RoleManager#isRoleHeld(String)}).
2064      *     <li>If the calling app has been granted the
2065      *      {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
2066      * </ul>
2067      *
2068      * <p>If the calling app does not meet one of these requirements then this method will behave
2069      * as follows:
2070      *
2071      * <ul>
2072      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2073      *     READ_PHONE_STATE permission then null is returned.</li>
2074      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2075      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2076      *     higher, then a SecurityException is thrown.</li>
2077      * </ul>
2078      *
2079      * @param slotIndex of which IMEI is returned
2080      */
2081     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2082     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getImei(int slotIndex)2083     public String getImei(int slotIndex) {
2084         ITelephony telephony = getITelephony();
2085         if (telephony == null) return null;
2086 
2087         try {
2088             return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
2089         } catch (RemoteException ex) {
2090             return null;
2091         } catch (NullPointerException ex) {
2092             return null;
2093         }
2094     }
2095 
2096     /**
2097      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2098      * available.
2099      */
2100     @Nullable
getTypeAllocationCode()2101     public String getTypeAllocationCode() {
2102         return getTypeAllocationCode(getSlotIndex());
2103     }
2104 
2105     /**
2106      * Returns the Type Allocation Code from the IMEI. Return null if Type Allocation Code is not
2107      * available.
2108      *
2109      * @param slotIndex of which Type Allocation Code is returned
2110      */
2111     @Nullable
getTypeAllocationCode(int slotIndex)2112     public String getTypeAllocationCode(int slotIndex) {
2113         ITelephony telephony = getITelephony();
2114         if (telephony == null) return null;
2115 
2116         try {
2117             return telephony.getTypeAllocationCodeForSlot(slotIndex);
2118         } catch (RemoteException ex) {
2119             return null;
2120         } catch (NullPointerException ex) {
2121             return null;
2122         }
2123     }
2124 
2125     /**
2126      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2127      *
2128      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2129      * restrictions, and apps are recommended to use resettable identifiers (see <a
2130      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2131      * method can be invoked if one of the following requirements is met:
2132      * <ul>
2133      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2134      *     is a privileged permission that can only be granted to apps preloaded on the device.
2135      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2136      *     owner of an organization-owned device, or their delegates (see {@link
2137      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2138      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2139      *     active subscription.
2140      *     <li>If the calling app is the default SMS role holder (see {@link
2141      *     RoleManager#isRoleHeld(String)}).
2142      * </ul>
2143      *
2144      * <p>If the calling app does not meet one of these requirements then this method will behave
2145      * as follows:
2146      *
2147      * <ul>
2148      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2149      *     READ_PHONE_STATE permission then null is returned.</li>
2150      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2151      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2152      *     higher, then a SecurityException is thrown.</li>
2153      * </ul>
2154      */
2155     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2156     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid()2157     public String getMeid() {
2158         return getMeid(getSlotIndex());
2159     }
2160 
2161     /**
2162      * Returns the MEID (Mobile Equipment Identifier). Return null if MEID is not available.
2163      *
2164      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2165      * restrictions, and apps are recommended to use resettable identifiers (see <a
2166      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2167      * method can be invoked if one of the following requirements is met:
2168      * <ul>
2169      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2170      *     is a privileged permission that can only be granted to apps preloaded on the device.
2171      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2172      *     owner of an organization-owned device, or their delegates (see {@link
2173      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2174      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}) on any
2175      *     active subscription.
2176      *     <li>If the calling app is the default SMS role holder (see {@link
2177      *     RoleManager#isRoleHeld(String)}).
2178      * </ul>
2179      *
2180      * <p>If the calling app does not meet one of these requirements then this method will behave
2181      * as follows:
2182      *
2183      * <ul>
2184      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2185      *     READ_PHONE_STATE permission then null is returned.</li>
2186      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2187      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2188      *     higher, then a SecurityException is thrown.</li>
2189      * </ul>
2190      *
2191      * @param slotIndex of which MEID is returned
2192      */
2193     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2194     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMeid(int slotIndex)2195     public String getMeid(int slotIndex) {
2196         ITelephony telephony = getITelephony();
2197         if (telephony == null) return null;
2198 
2199         try {
2200             String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
2201                     getAttributionTag());
2202             if (TextUtils.isEmpty(meid)) {
2203                 Log.d(TAG, "getMeid: return null because MEID is not available");
2204                 return null;
2205             }
2206             return meid;
2207         } catch (RemoteException ex) {
2208             return null;
2209         } catch (NullPointerException ex) {
2210             return null;
2211         }
2212     }
2213 
2214     /**
2215      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2216      * available.
2217      */
2218     @Nullable
getManufacturerCode()2219     public String getManufacturerCode() {
2220         return getManufacturerCode(getSlotIndex());
2221     }
2222 
2223     /**
2224      * Returns the Manufacturer Code from the MEID. Return null if Manufacturer Code is not
2225      * available.
2226      *
2227      * @param slotIndex of which Type Allocation Code is returned
2228      */
2229     @Nullable
getManufacturerCode(int slotIndex)2230     public String getManufacturerCode(int slotIndex) {
2231         ITelephony telephony = getITelephony();
2232         if (telephony == null) return null;
2233 
2234         try {
2235             return telephony.getManufacturerCodeForSlot(slotIndex);
2236         } catch (RemoteException ex) {
2237             return null;
2238         } catch (NullPointerException ex) {
2239             return null;
2240         }
2241     }
2242 
2243     /**
2244      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
2245      *
2246      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2247      * restrictions, and apps are recommended to use resettable identifiers (see <a
2248      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2249      * method can be invoked if one of the following requirements is met:
2250      * <ul>
2251      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2252      *     is a privileged permission that can only be granted to apps preloaded on the device.
2253      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2254      *     owner of an organization-owned device, or their delegates (see {@link
2255      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2256      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2257      *     <li>If the calling app is the default SMS role holder (see {@link
2258      *     RoleManager#isRoleHeld(String)}).
2259      * </ul>
2260      *
2261      * <p>If the calling app does not meet one of these requirements then this method will behave
2262      * as follows:
2263      *
2264      * <ul>
2265      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2266      *     READ_PHONE_STATE permission then null is returned.</li>
2267      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2268      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2269      *     higher, then a SecurityException is thrown.</li>
2270      * </ul>
2271      */
2272     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
2273     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNai()2274     public String getNai() {
2275         return getNaiBySubscriberId(getSubId());
2276     }
2277 
2278     /**
2279      * Returns the NAI. Return null if NAI is not available.
2280      *
2281      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
2282      * restrictions, and apps are recommended to use resettable identifiers (see <a
2283      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
2284      * method can be invoked if one of the following requirements is met:
2285      * <ul>
2286      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
2287      *     is a privileged permission that can only be granted to apps preloaded on the device.
2288      *     <li>If the calling app is the device owner of a fully-managed device, a profile
2289      *     owner of an organization-owned device, or their delegates (see {@link
2290      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
2291      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2292      *     <li>If the calling app is the default SMS role holder (see {@link
2293      *     RoleManager#isRoleHeld(String)}).
2294      * </ul>
2295      *
2296      * <p>If the calling app does not meet one of these requirements then this method will behave
2297      * as follows:
2298      *
2299      * <ul>
2300      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
2301      *     READ_PHONE_STATE permission then null is returned.</li>
2302      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
2303      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
2304      *     higher, then a SecurityException is thrown.</li>
2305      * </ul>
2306      *
2307      *  @param slotIndex of which Nai is returned
2308      */
2309     /** {@hide}*/
2310     @UnsupportedAppUsage
getNai(int slotIndex)2311     public String getNai(int slotIndex) {
2312         int[] subId = SubscriptionManager.getSubId(slotIndex);
2313         if (subId == null) {
2314             return null;
2315         }
2316         return getNaiBySubscriberId(subId[0]);
2317     }
2318 
getNaiBySubscriberId(int subId)2319     private String getNaiBySubscriberId(int subId) {
2320         try {
2321             IPhoneSubInfo info = getSubscriberInfoService();
2322             if (info == null)
2323                 return null;
2324             String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
2325                     mContext.getAttributionTag());
2326             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2327                 Rlog.v(TAG, "Nai = " + nai);
2328             }
2329             return nai;
2330         } catch (RemoteException ex) {
2331             return null;
2332         } catch (NullPointerException ex) {
2333             return null;
2334         }
2335     }
2336 
2337     /**
2338      * Returns the current location of the device.
2339      *<p>
2340      * If there is only one radio in the device and that radio has an LTE connection,
2341      * this method will return null. The implementation must not to try add LTE
2342      * identifiers into the existing cdma/gsm classes.
2343      *<p>
2344      * @return Current location of the device or null if not available.
2345      *
2346      * @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
2347      */
2348     @Deprecated
2349     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getCellLocation()2350     public CellLocation getCellLocation() {
2351         try {
2352             ITelephony telephony = getITelephony();
2353             if (telephony == null) {
2354                 Rlog.d(TAG, "getCellLocation returning null because telephony is null");
2355                 return null;
2356             }
2357 
2358             CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
2359                     mContext.getAttributionTag());
2360             CellLocation cl = cellIdentity.asCellLocation();
2361             if (cl == null || cl.isEmpty()) {
2362                 Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
2363                         + " phone type doesn't match CellLocation type");
2364                 return null;
2365             }
2366 
2367             return cl;
2368         } catch (RemoteException ex) {
2369             Rlog.d(TAG, "getCellLocation returning null due to RemoteException " + ex);
2370             return null;
2371         }
2372     }
2373 
2374     /**
2375      * Returns the neighboring cell information of the device.
2376      *
2377      * @return List of NeighboringCellInfo or null if info unavailable.
2378      *
2379      * @removed
2380      * @deprecated Use {@link #getAllCellInfo} which returns a superset of the information
2381      *             from NeighboringCellInfo, including LTE cell information.
2382      */
2383     @Deprecated
2384     @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
getNeighboringCellInfo()2385     public List<NeighboringCellInfo> getNeighboringCellInfo() {
2386         try {
2387             ITelephony telephony = getITelephony();
2388             if (telephony == null)
2389                 return null;
2390             return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
2391                     mContext.getAttributionTag());
2392         } catch (RemoteException ex) {
2393             return null;
2394         } catch (NullPointerException ex) {
2395             return null;
2396         }
2397     }
2398 
2399     /** No phone radio. */
2400     public static final int PHONE_TYPE_NONE = PhoneConstants.PHONE_TYPE_NONE;
2401     /** Phone radio is GSM. */
2402     public static final int PHONE_TYPE_GSM = PhoneConstants.PHONE_TYPE_GSM;
2403     /** Phone radio is CDMA. */
2404     public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
2405     /** Phone is via SIP. */
2406     public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
2407 
2408     /**
2409      * Phone is via IMS.
2410      *
2411      * @hide
2412      */
2413     public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
2414 
2415     /**
2416      * Phone is via Third Party.
2417      *
2418      * @hide
2419      */
2420     public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
2421 
2422     /**
2423      * Returns the current phone type.
2424      * TODO: This is a last minute change and hence hidden.
2425      *
2426      * @see #PHONE_TYPE_NONE
2427      * @see #PHONE_TYPE_GSM
2428      * @see #PHONE_TYPE_CDMA
2429      * @see #PHONE_TYPE_SIP
2430      *
2431      * {@hide}
2432      */
2433     @SystemApi
getCurrentPhoneType()2434     public int getCurrentPhoneType() {
2435         return getCurrentPhoneType(getSubId());
2436     }
2437 
2438     /**
2439      * Returns a constant indicating the device phone type for a subscription.
2440      *
2441      * @see #PHONE_TYPE_NONE
2442      * @see #PHONE_TYPE_GSM
2443      * @see #PHONE_TYPE_CDMA
2444      *
2445      * @param subId for which phone type is returned
2446      * @hide
2447      */
2448     @SystemApi
getCurrentPhoneType(int subId)2449     public int getCurrentPhoneType(int subId) {
2450         int phoneId;
2451         if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
2452             // if we don't have any sims, we don't have subscriptions, but we
2453             // still may want to know what type of phone we've got.
2454             phoneId = 0;
2455         } else {
2456             phoneId = SubscriptionManager.getPhoneId(subId);
2457         }
2458 
2459         return getCurrentPhoneTypeForSlot(phoneId);
2460     }
2461 
2462     /**
2463      * See getCurrentPhoneType.
2464      *
2465      * @hide
2466      */
getCurrentPhoneTypeForSlot(int slotIndex)2467     public int getCurrentPhoneTypeForSlot(int slotIndex) {
2468         try{
2469             ITelephony telephony = getITelephony();
2470             if (telephony != null) {
2471                 return telephony.getActivePhoneTypeForSlot(slotIndex);
2472             } else {
2473                 // This can happen when the ITelephony interface is not up yet.
2474                 return getPhoneTypeFromProperty(slotIndex);
2475             }
2476         } catch (RemoteException ex) {
2477             // This shouldn't happen in the normal case, as a backup we
2478             // read from the system property.
2479             return getPhoneTypeFromProperty(slotIndex);
2480         } catch (NullPointerException ex) {
2481             // This shouldn't happen in the normal case, as a backup we
2482             // read from the system property.
2483             return getPhoneTypeFromProperty(slotIndex);
2484         }
2485     }
2486 
2487     /**
2488      * Returns a constant indicating the device phone type.  This
2489      * indicates the type of radio used to transmit voice calls.
2490      *
2491      * @see #PHONE_TYPE_NONE
2492      * @see #PHONE_TYPE_GSM
2493      * @see #PHONE_TYPE_CDMA
2494      * @see #PHONE_TYPE_SIP
2495      */
getPhoneType()2496     public int getPhoneType() {
2497         if (!isVoiceCapable()) {
2498             return PHONE_TYPE_NONE;
2499         }
2500         return getCurrentPhoneType();
2501     }
2502 
getPhoneTypeFromProperty()2503     private int getPhoneTypeFromProperty() {
2504         return getPhoneTypeFromProperty(getPhoneId());
2505     }
2506 
2507     /** {@hide} */
2508     @UnsupportedAppUsage
getPhoneTypeFromProperty(int phoneId)2509     private int getPhoneTypeFromProperty(int phoneId) {
2510         Integer type = getTelephonyProperty(
2511                 phoneId, TelephonyProperties.current_active_phone(), null);
2512         if (type != null) return type;
2513         return getPhoneTypeFromNetworkType(phoneId);
2514     }
2515 
getPhoneTypeFromNetworkType()2516     private int getPhoneTypeFromNetworkType() {
2517         return getPhoneTypeFromNetworkType(getPhoneId());
2518     }
2519 
2520     /** {@hide} */
getPhoneTypeFromNetworkType(int phoneId)2521     private int getPhoneTypeFromNetworkType(int phoneId) {
2522         // When the system property CURRENT_ACTIVE_PHONE, has not been set,
2523         // use the system property for default network type.
2524         // This is a fail safe, and can only happen at first boot.
2525         Integer mode = getTelephonyProperty(phoneId, TelephonyProperties.default_network(), null);
2526         if (mode != null) {
2527             return TelephonyManager.getPhoneType(mode);
2528         }
2529         return TelephonyManager.PHONE_TYPE_NONE;
2530     }
2531 
2532     /**
2533      * This function returns the type of the phone, depending
2534      * on the network mode.
2535      *
2536      * @param networkMode
2537      * @return Phone Type
2538      *
2539      * @hide
2540      */
2541     @UnsupportedAppUsage
getPhoneType(int networkMode)2542     public static int getPhoneType(int networkMode) {
2543         switch(networkMode) {
2544         case RILConstants.NETWORK_MODE_CDMA:
2545         case RILConstants.NETWORK_MODE_CDMA_NO_EVDO:
2546         case RILConstants.NETWORK_MODE_EVDO_NO_CDMA:
2547             return PhoneConstants.PHONE_TYPE_CDMA;
2548 
2549         case RILConstants.NETWORK_MODE_WCDMA_PREF:
2550         case RILConstants.NETWORK_MODE_GSM_ONLY:
2551         case RILConstants.NETWORK_MODE_WCDMA_ONLY:
2552         case RILConstants.NETWORK_MODE_GSM_UMTS:
2553         case RILConstants.NETWORK_MODE_LTE_GSM_WCDMA:
2554         case RILConstants.NETWORK_MODE_LTE_WCDMA:
2555         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
2556         case RILConstants.NETWORK_MODE_TDSCDMA_ONLY:
2557         case RILConstants.NETWORK_MODE_TDSCDMA_WCDMA:
2558         case RILConstants.NETWORK_MODE_LTE_TDSCDMA:
2559         case RILConstants.NETWORK_MODE_TDSCDMA_GSM:
2560         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM:
2561         case RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA:
2562         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA:
2563         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA:
2564         case RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2565             return PhoneConstants.PHONE_TYPE_GSM;
2566 
2567         // Use CDMA Phone for the global mode including CDMA
2568         case RILConstants.NETWORK_MODE_GLOBAL:
2569         case RILConstants.NETWORK_MODE_LTE_CDMA_EVDO:
2570         case RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
2571             return PhoneConstants.PHONE_TYPE_CDMA;
2572 
2573         case RILConstants.NETWORK_MODE_LTE_ONLY:
2574             if (TelephonyProperties.lte_on_cdma_device().orElse(
2575                     PhoneConstants.LTE_ON_CDMA_FALSE) == PhoneConstants.LTE_ON_CDMA_TRUE) {
2576                 return PhoneConstants.PHONE_TYPE_CDMA;
2577             } else {
2578                 return PhoneConstants.PHONE_TYPE_GSM;
2579             }
2580         default:
2581             return PhoneConstants.PHONE_TYPE_GSM;
2582         }
2583     }
2584 
2585     /**
2586      * @return The max value for the timeout passed in {@link #requestNumberVerification}.
2587      * @hide
2588      */
2589     @SystemApi
getMaxNumberVerificationTimeoutMillis()2590     public static long getMaxNumberVerificationTimeoutMillis() {
2591         return MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS;
2592     }
2593 
2594     //
2595     //
2596     // Current Network
2597     //
2598     //
2599 
2600     /**
2601      * Returns the alphabetic name of current registered operator.
2602      * <p>
2603      * Availability: Only when user is registered to a network. Result may be
2604      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2605      * on a CDMA network).
2606      */
getNetworkOperatorName()2607     public String getNetworkOperatorName() {
2608         return getNetworkOperatorName(getSubId());
2609     }
2610 
2611     /**
2612      * Returns the alphabetic name of current registered operator
2613      * for a particular subscription.
2614      * <p>
2615      * Availability: Only when user is registered to a network. Result may be
2616      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2617      * on a CDMA network).
2618      * @param subId
2619      * @hide
2620      */
2621     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperatorName(int subId)2622     public String getNetworkOperatorName(int subId) {
2623         int phoneId = SubscriptionManager.getPhoneId(subId);
2624         return getTelephonyProperty(phoneId, TelephonyProperties.operator_alpha(), "");
2625     }
2626 
2627     /**
2628      * Returns the numeric name (MCC+MNC) of current registered operator.
2629      * <p>
2630      * Availability: Only when user is registered to a network. Result may be
2631      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2632      * on a CDMA network).
2633      */
getNetworkOperator()2634     public String getNetworkOperator() {
2635         return getNetworkOperatorForPhone(getPhoneId());
2636     }
2637 
2638     /**
2639      * Returns the numeric name (MCC+MNC) of current registered operator
2640      * for a particular subscription.
2641      * <p>
2642      * Availability: Only when user is registered to a network. Result may be
2643      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2644      * on a CDMA network).
2645      *
2646      * @param subId
2647      * @hide
2648      */
2649     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkOperator(int subId)2650     public String getNetworkOperator(int subId) {
2651         int phoneId = SubscriptionManager.getPhoneId(subId);
2652         return getNetworkOperatorForPhone(phoneId);
2653      }
2654 
2655     /**
2656      * Returns the numeric name (MCC+MNC) of current registered operator
2657      * for a particular subscription.
2658      * <p>
2659      * Availability: Only when user is registered to a network. Result may be
2660      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
2661      * on a CDMA network).
2662      *
2663      * @param phoneId
2664      * @hide
2665      **/
2666     @UnsupportedAppUsage
getNetworkOperatorForPhone(int phoneId)2667     public String getNetworkOperatorForPhone(int phoneId) {
2668         return getTelephonyProperty(phoneId, TelephonyProperties.operator_numeric(), "");
2669     }
2670 
2671 
2672     /**
2673      * Returns the network specifier of the subscription ID pinned to the TelephonyManager. The
2674      * network specifier is used by {@link
2675      * android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to create a {@link
2676      * android.net.NetworkRequest} that connects through the subscription.
2677      *
2678      * @see android.net.NetworkRequest.Builder#setNetworkSpecifier(String)
2679      * @see #createForSubscriptionId(int)
2680      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2681      */
getNetworkSpecifier()2682     public String getNetworkSpecifier() {
2683         return String.valueOf(getSubId());
2684     }
2685 
2686     /**
2687      * Returns the carrier config of the subscription ID pinned to the TelephonyManager. If an
2688      * invalid subscription ID is pinned to the TelephonyManager, the returned config will contain
2689      * default values.
2690      *
2691      * <p>This method may take several seconds to complete, so it should only be called from a
2692      * worker thread.
2693      *
2694      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2695      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2696      *
2697      * @see CarrierConfigManager#getConfigForSubId(int)
2698      * @see #createForSubscriptionId(int)
2699      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
2700      */
2701     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2702     @WorkerThread
2703     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCarrierConfig()2704     public PersistableBundle getCarrierConfig() {
2705         CarrierConfigManager carrierConfigManager = mContext
2706                 .getSystemService(CarrierConfigManager.class);
2707         return carrierConfigManager.getConfigForSubId(getSubId());
2708     }
2709 
2710     /**
2711      * Returns true if the device is considered roaming on the current
2712      * network, for GSM purposes.
2713      * <p>
2714      * Availability: Only when user registered to a network.
2715      */
isNetworkRoaming()2716     public boolean isNetworkRoaming() {
2717         return isNetworkRoaming(getSubId());
2718     }
2719 
2720     /**
2721      * Returns true if the device is considered roaming on the current
2722      * network for a subscription.
2723      * <p>
2724      * Availability: Only when user registered to a network.
2725      *
2726      * @param subId
2727      * @hide
2728      */
2729     @UnsupportedAppUsage
isNetworkRoaming(int subId)2730     public boolean isNetworkRoaming(int subId) {
2731         int phoneId = SubscriptionManager.getPhoneId(subId);
2732         return getTelephonyProperty(phoneId, TelephonyProperties.operator_is_roaming(), false);
2733     }
2734 
2735     /**
2736      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2737      * the current registered operator or the cell nearby, if available.
2738      *
2739      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2740      * if on a CDMA network).
2741      * <p>
2742      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2743      * available.
2744      */
getNetworkCountryIso()2745     public String getNetworkCountryIso() {
2746         return getNetworkCountryIso(getSlotIndex());
2747     }
2748 
2749     /**
2750      * Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of
2751      * the current registered operator or the cell nearby, if available. This is same as
2752      * {@link #getNetworkCountryIso()} but allowing specifying the SIM slot index. This is used for
2753      * accessing network country info from the SIM slot that does not have SIM inserted.
2754      *
2755      * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
2756      * if on a CDMA network).
2757      * <p>
2758      *
2759      * @param slotIndex the SIM slot index to get network country ISO.
2760      *
2761      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string if not
2762      * available.
2763      *
2764      * @throws IllegalArgumentException when the slotIndex is invalid.
2765      *
2766      */
2767     @NonNull
getNetworkCountryIso(int slotIndex)2768     public String getNetworkCountryIso(int slotIndex) {
2769         try {
2770             if (slotIndex != SubscriptionManager.DEFAULT_SIM_SLOT_INDEX
2771                     && !SubscriptionManager.isValidSlotIndex(slotIndex)) {
2772                 throw new IllegalArgumentException("invalid slot index " + slotIndex);
2773             }
2774 
2775             ITelephony telephony = getITelephony();
2776             if (telephony == null) return "";
2777             return telephony.getNetworkCountryIsoForPhone(slotIndex);
2778         } catch (RemoteException ex) {
2779             return "";
2780         }
2781     }
2782 
2783     /**
2784      * @hide
2785      * @deprecated Use {@link #getNetworkCountryIso(int)} instead.
2786      */
2787     @Deprecated
2788     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
2789             publicAlternatives = "Use {@link #getNetworkCountryIso(int)} instead.")
getNetworkCountryIsoForPhone(int phoneId)2790     public String getNetworkCountryIsoForPhone(int phoneId) {
2791         return getNetworkCountryIso(phoneId);
2792     }
2793 
2794     /*
2795      * When adding a network type to the list below, make sure to add the correct icon to
2796      * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
2797      * Do not add negative types.
2798      */
2799     /** Network type is unknown */
2800     public static final int NETWORK_TYPE_UNKNOWN = TelephonyProtoEnums.NETWORK_TYPE_UNKNOWN; // = 0.
2801     /** Current network is GPRS */
2802     public static final int NETWORK_TYPE_GPRS = TelephonyProtoEnums.NETWORK_TYPE_GPRS; // = 1.
2803     /** Current network is EDGE */
2804     public static final int NETWORK_TYPE_EDGE = TelephonyProtoEnums.NETWORK_TYPE_EDGE; // = 2.
2805     /** Current network is UMTS */
2806     public static final int NETWORK_TYPE_UMTS = TelephonyProtoEnums.NETWORK_TYPE_UMTS; // = 3.
2807     /** Current network is CDMA: Either IS95A or IS95B*/
2808     public static final int NETWORK_TYPE_CDMA = TelephonyProtoEnums.NETWORK_TYPE_CDMA; // = 4.
2809     /** Current network is EVDO revision 0*/
2810     public static final int NETWORK_TYPE_EVDO_0 = TelephonyProtoEnums.NETWORK_TYPE_EVDO_0; // = 5.
2811     /** Current network is EVDO revision A*/
2812     public static final int NETWORK_TYPE_EVDO_A = TelephonyProtoEnums.NETWORK_TYPE_EVDO_A; // = 6.
2813     /** Current network is 1xRTT*/
2814     public static final int NETWORK_TYPE_1xRTT = TelephonyProtoEnums.NETWORK_TYPE_1XRTT; // = 7.
2815     /** Current network is HSDPA */
2816     public static final int NETWORK_TYPE_HSDPA = TelephonyProtoEnums.NETWORK_TYPE_HSDPA; // = 8.
2817     /** Current network is HSUPA */
2818     public static final int NETWORK_TYPE_HSUPA = TelephonyProtoEnums.NETWORK_TYPE_HSUPA; // = 9.
2819     /** Current network is HSPA */
2820     public static final int NETWORK_TYPE_HSPA = TelephonyProtoEnums.NETWORK_TYPE_HSPA; // = 10.
2821     /** Current network is iDen */
2822     public static final int NETWORK_TYPE_IDEN = TelephonyProtoEnums.NETWORK_TYPE_IDEN; // = 11.
2823     /** Current network is EVDO revision B*/
2824     public static final int NETWORK_TYPE_EVDO_B = TelephonyProtoEnums.NETWORK_TYPE_EVDO_B; // = 12.
2825     /** Current network is LTE */
2826     public static final int NETWORK_TYPE_LTE = TelephonyProtoEnums.NETWORK_TYPE_LTE; // = 13.
2827     /** Current network is eHRPD */
2828     public static final int NETWORK_TYPE_EHRPD = TelephonyProtoEnums.NETWORK_TYPE_EHRPD; // = 14.
2829     /** Current network is HSPA+ */
2830     public static final int NETWORK_TYPE_HSPAP = TelephonyProtoEnums.NETWORK_TYPE_HSPAP; // = 15.
2831     /** Current network is GSM */
2832     public static final int NETWORK_TYPE_GSM = TelephonyProtoEnums.NETWORK_TYPE_GSM; // = 16.
2833     /** Current network is TD_SCDMA */
2834     public static final int NETWORK_TYPE_TD_SCDMA =
2835             TelephonyProtoEnums.NETWORK_TYPE_TD_SCDMA; // = 17.
2836     /** Current network is IWLAN */
2837     public static final int NETWORK_TYPE_IWLAN = TelephonyProtoEnums.NETWORK_TYPE_IWLAN; // = 18.
2838     /** Current network is LTE_CA {@hide} */
2839     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2840     public static final int NETWORK_TYPE_LTE_CA = TelephonyProtoEnums.NETWORK_TYPE_LTE_CA; // = 19.
2841     /**
2842      * Current network is NR (New Radio) 5G.
2843      * This will only be returned for 5G SA.
2844      * For 5G NSA, the network type will be {@link #NETWORK_TYPE_LTE}.
2845      */
2846     public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
2847 
2848     private static final @NetworkType int[] NETWORK_TYPES = {
2849             NETWORK_TYPE_GPRS,
2850             NETWORK_TYPE_EDGE,
2851             NETWORK_TYPE_UMTS,
2852             NETWORK_TYPE_CDMA,
2853             NETWORK_TYPE_EVDO_0,
2854             NETWORK_TYPE_EVDO_A,
2855             NETWORK_TYPE_1xRTT,
2856             NETWORK_TYPE_HSDPA,
2857             NETWORK_TYPE_HSUPA,
2858             NETWORK_TYPE_HSPA,
2859             NETWORK_TYPE_IDEN,
2860             NETWORK_TYPE_EVDO_B,
2861             NETWORK_TYPE_LTE,
2862             NETWORK_TYPE_EHRPD,
2863             NETWORK_TYPE_HSPAP,
2864             NETWORK_TYPE_GSM,
2865             NETWORK_TYPE_TD_SCDMA,
2866             NETWORK_TYPE_IWLAN,
2867             NETWORK_TYPE_LTE_CA,
2868             NETWORK_TYPE_NR
2869     };
2870 
2871     /**
2872      * Returns an array of all valid network types.
2873      *
2874      * @return An integer array containing all valid network types in no particular order.
2875      *
2876      * @hide
2877      */
2878     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getAllNetworkTypes()2879     public static @NonNull @NetworkType int[] getAllNetworkTypes() {
2880         return NETWORK_TYPES.clone();
2881     }
2882 
2883     /**
2884      * Return the current data network type.
2885      *
2886      * @deprecated use {@link #getDataNetworkType()}
2887      * @return the NETWORK_TYPE_xxxx for current data connection.
2888      */
2889     @Deprecated
2890     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNetworkType()2891     public @NetworkType int getNetworkType() {
2892         return getNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
2893     }
2894 
2895     /**
2896      * Returns a constant indicating the radio technology (network type)
2897      * currently in use on the device for a subscription.
2898      * @return the network type
2899      *
2900      * @param subId for which network type is returned
2901      *
2902      * @see #NETWORK_TYPE_UNKNOWN
2903      * @see #NETWORK_TYPE_GPRS
2904      * @see #NETWORK_TYPE_EDGE
2905      * @see #NETWORK_TYPE_UMTS
2906      * @see #NETWORK_TYPE_HSDPA
2907      * @see #NETWORK_TYPE_HSUPA
2908      * @see #NETWORK_TYPE_HSPA
2909      * @see #NETWORK_TYPE_CDMA
2910      * @see #NETWORK_TYPE_EVDO_0
2911      * @see #NETWORK_TYPE_EVDO_A
2912      * @see #NETWORK_TYPE_EVDO_B
2913      * @see #NETWORK_TYPE_1xRTT
2914      * @see #NETWORK_TYPE_IDEN
2915      * @see #NETWORK_TYPE_LTE
2916      * @see #NETWORK_TYPE_EHRPD
2917      * @see #NETWORK_TYPE_HSPAP
2918      * @see #NETWORK_TYPE_NR
2919      *
2920      * @hide
2921      */
2922     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2923     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getNetworkType(int subId)2924     public int getNetworkType(int subId) {
2925         try {
2926             ITelephony telephony = getITelephony();
2927             if (telephony != null) {
2928                 return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
2929                         getAttributionTag());
2930             } else {
2931                 // This can happen when the ITelephony interface is not up yet.
2932                 return NETWORK_TYPE_UNKNOWN;
2933             }
2934         } catch (RemoteException ex) {
2935             // This shouldn't happen in the normal case
2936             return NETWORK_TYPE_UNKNOWN;
2937         } catch (NullPointerException ex) {
2938             // This could happen before phone restarts due to crashing
2939             return NETWORK_TYPE_UNKNOWN;
2940         }
2941     }
2942 
2943     /**
2944      * Returns a constant indicating the radio technology (network type)
2945      * currently in use on the device for data transmission.
2946      *
2947      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
2948      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
2949      *
2950      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
2951      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
2952      *
2953      * @return the network type
2954      *
2955      * @see #NETWORK_TYPE_UNKNOWN
2956      * @see #NETWORK_TYPE_GPRS
2957      * @see #NETWORK_TYPE_EDGE
2958      * @see #NETWORK_TYPE_UMTS
2959      * @see #NETWORK_TYPE_HSDPA
2960      * @see #NETWORK_TYPE_HSUPA
2961      * @see #NETWORK_TYPE_HSPA
2962      * @see #NETWORK_TYPE_CDMA
2963      * @see #NETWORK_TYPE_EVDO_0
2964      * @see #NETWORK_TYPE_EVDO_A
2965      * @see #NETWORK_TYPE_EVDO_B
2966      * @see #NETWORK_TYPE_1xRTT
2967      * @see #NETWORK_TYPE_IDEN
2968      * @see #NETWORK_TYPE_LTE
2969      * @see #NETWORK_TYPE_EHRPD
2970      * @see #NETWORK_TYPE_HSPAP
2971      * @see #NETWORK_TYPE_NR
2972      */
2973     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
2974     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getDataNetworkType()2975     public @NetworkType int getDataNetworkType() {
2976         return getDataNetworkType(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
2977     }
2978 
2979     /**
2980      * Returns a constant indicating the radio technology (network type)
2981      * currently in use on the device for data transmission for a subscription
2982      * @return the network type
2983      *
2984      * @param subId for which network type is returned
2985      * @hide
2986      */
2987     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
2988     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getDataNetworkType(int subId)2989     public int getDataNetworkType(int subId) {
2990         try{
2991             ITelephony telephony = getITelephony();
2992             if (telephony != null) {
2993                 return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
2994                         getAttributionTag());
2995             } else {
2996                 // This can happen when the ITelephony interface is not up yet.
2997                 return NETWORK_TYPE_UNKNOWN;
2998             }
2999         } catch(RemoteException ex) {
3000             // This shouldn't happen in the normal case
3001             return NETWORK_TYPE_UNKNOWN;
3002         } catch (NullPointerException ex) {
3003             // This could happen before phone restarts due to crashing
3004             return NETWORK_TYPE_UNKNOWN;
3005         }
3006     }
3007 
3008     /**
3009      * Returns the NETWORK_TYPE_xxxx for voice
3010      *
3011      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
3012      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3013      */
3014     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
3015     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceNetworkType()3016     public @NetworkType int getVoiceNetworkType() {
3017         return getVoiceNetworkType(getSubId());
3018     }
3019 
3020     /**
3021      * Returns the NETWORK_TYPE_xxxx for voice for a subId
3022      * @hide
3023      */
3024     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
3025     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getVoiceNetworkType(int subId)3026     public int getVoiceNetworkType(int subId) {
3027         try{
3028             ITelephony telephony = getITelephony();
3029             if (telephony != null) {
3030                 return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
3031                         getAttributionTag());
3032             } else {
3033                 // This can happen when the ITelephony interface is not up yet.
3034                 return NETWORK_TYPE_UNKNOWN;
3035             }
3036         } catch(RemoteException ex) {
3037             // This shouldn't happen in the normal case
3038             return NETWORK_TYPE_UNKNOWN;
3039         } catch (NullPointerException ex) {
3040             // This could happen before phone restarts due to crashing
3041             return NETWORK_TYPE_UNKNOWN;
3042         }
3043     }
3044 
3045     /**
3046      * Returns a string representation of the radio technology (network type)
3047      * currently in use on the device.
3048      * @return the name of the radio technology
3049      *
3050      * @hide pending API council review
3051      */
3052     @UnsupportedAppUsage
getNetworkTypeName()3053     public String getNetworkTypeName() {
3054         return getNetworkTypeName(getNetworkType());
3055     }
3056 
3057     /**
3058      * Returns a string representation of the radio technology (network type)
3059      * currently in use on the device.
3060      * @param subId for which network type is returned
3061      * @return the name of the radio technology
3062      *
3063      */
3064     /** {@hide} */
3065     @UnsupportedAppUsage
getNetworkTypeName(@etworkType int type)3066     public static String getNetworkTypeName(@NetworkType int type) {
3067         switch (type) {
3068             case NETWORK_TYPE_GPRS:
3069                 return "GPRS";
3070             case NETWORK_TYPE_EDGE:
3071                 return "EDGE";
3072             case NETWORK_TYPE_UMTS:
3073                 return "UMTS";
3074             case NETWORK_TYPE_HSDPA:
3075                 return "HSDPA";
3076             case NETWORK_TYPE_HSUPA:
3077                 return "HSUPA";
3078             case NETWORK_TYPE_HSPA:
3079                 return "HSPA";
3080             case NETWORK_TYPE_CDMA:
3081                 return "CDMA";
3082             case NETWORK_TYPE_EVDO_0:
3083                 return "CDMA - EvDo rev. 0";
3084             case NETWORK_TYPE_EVDO_A:
3085                 return "CDMA - EvDo rev. A";
3086             case NETWORK_TYPE_EVDO_B:
3087                 return "CDMA - EvDo rev. B";
3088             case NETWORK_TYPE_1xRTT:
3089                 return "CDMA - 1xRTT";
3090             case NETWORK_TYPE_LTE:
3091                 return "LTE";
3092             case NETWORK_TYPE_EHRPD:
3093                 return "CDMA - eHRPD";
3094             case NETWORK_TYPE_IDEN:
3095                 return "iDEN";
3096             case NETWORK_TYPE_HSPAP:
3097                 return "HSPA+";
3098             case NETWORK_TYPE_GSM:
3099                 return "GSM";
3100             case NETWORK_TYPE_TD_SCDMA:
3101                 return "TD_SCDMA";
3102             case NETWORK_TYPE_IWLAN:
3103                 return "IWLAN";
3104             case NETWORK_TYPE_LTE_CA:
3105                 return "LTE_CA";
3106             case NETWORK_TYPE_NR:
3107                 return "NR";
3108             default:
3109                 return "UNKNOWN";
3110         }
3111     }
3112 
3113     /**
3114      * Returns the bitmask for a given technology (network type)
3115      * @param networkType for which bitmask is returned
3116      * @return the network type bitmask
3117      * {@hide}
3118      */
getBitMaskForNetworkType(@etworkType int networkType)3119     public static @NetworkTypeBitMask long getBitMaskForNetworkType(@NetworkType int networkType) {
3120         switch(networkType) {
3121             case NETWORK_TYPE_GSM:
3122                 return NETWORK_TYPE_BITMASK_GSM;
3123             case NETWORK_TYPE_GPRS:
3124                 return NETWORK_TYPE_BITMASK_GPRS;
3125             case NETWORK_TYPE_EDGE:
3126                 return NETWORK_TYPE_BITMASK_EDGE;
3127             case NETWORK_TYPE_CDMA:
3128                 return NETWORK_TYPE_BITMASK_CDMA;
3129             case NETWORK_TYPE_1xRTT:
3130                 return NETWORK_TYPE_BITMASK_1xRTT;
3131             case NETWORK_TYPE_EVDO_0:
3132                 return NETWORK_TYPE_BITMASK_EVDO_0;
3133             case NETWORK_TYPE_EVDO_A:
3134                 return NETWORK_TYPE_BITMASK_EVDO_A;
3135             case NETWORK_TYPE_EVDO_B:
3136                 return NETWORK_TYPE_BITMASK_EVDO_B;
3137             case NETWORK_TYPE_EHRPD:
3138                 return NETWORK_TYPE_BITMASK_EHRPD;
3139             case NETWORK_TYPE_HSUPA:
3140                 return NETWORK_TYPE_BITMASK_HSUPA;
3141             case NETWORK_TYPE_HSDPA:
3142                 return NETWORK_TYPE_BITMASK_HSDPA;
3143             case NETWORK_TYPE_HSPA:
3144                 return NETWORK_TYPE_BITMASK_HSPA;
3145             case NETWORK_TYPE_HSPAP:
3146                 return NETWORK_TYPE_BITMASK_HSPAP;
3147             case NETWORK_TYPE_UMTS:
3148                 return NETWORK_TYPE_BITMASK_UMTS;
3149             case NETWORK_TYPE_TD_SCDMA:
3150                 return NETWORK_TYPE_BITMASK_TD_SCDMA;
3151             case NETWORK_TYPE_LTE:
3152                 return NETWORK_TYPE_BITMASK_LTE;
3153             case NETWORK_TYPE_LTE_CA:
3154                 return NETWORK_TYPE_BITMASK_LTE_CA;
3155             case NETWORK_TYPE_NR:
3156                 return NETWORK_TYPE_BITMASK_NR;
3157             case NETWORK_TYPE_IWLAN:
3158                 return NETWORK_TYPE_BITMASK_IWLAN;
3159             case NETWORK_TYPE_IDEN:
3160                 return (1 << (NETWORK_TYPE_IDEN - 1));
3161             default:
3162                 return NETWORK_TYPE_BITMASK_UNKNOWN;
3163         }
3164     }
3165 
3166     //
3167     //
3168     // SIM Card
3169     //
3170     //
3171 
3172     /** @hide */
3173     @IntDef(prefix = {"SIM_STATE_"},
3174             value = {
3175                     SIM_STATE_UNKNOWN,
3176                     SIM_STATE_ABSENT,
3177                     SIM_STATE_PIN_REQUIRED,
3178                     SIM_STATE_PUK_REQUIRED,
3179                     SIM_STATE_NETWORK_LOCKED,
3180                     SIM_STATE_READY,
3181                     SIM_STATE_NOT_READY,
3182                     SIM_STATE_PERM_DISABLED,
3183                     SIM_STATE_CARD_IO_ERROR,
3184                     SIM_STATE_CARD_RESTRICTED,
3185                     SIM_STATE_LOADED,
3186                     SIM_STATE_PRESENT,
3187             })
3188     public @interface SimState {}
3189 
3190     /**
3191      * SIM card state: Unknown. Signifies that the SIM is in transition
3192      * between states. For example, when the user inputs the SIM pin
3193      * under PIN_REQUIRED state, a query for sim status returns
3194      * this state before turning to SIM_STATE_READY.
3195      *
3196      * These are the ordinal value of IccCardConstants.State.
3197      */
3198 
3199     public static final int SIM_STATE_UNKNOWN = TelephonyProtoEnums.SIM_STATE_UNKNOWN;  // 0
3200     /** SIM card state: no SIM card is available in the device */
3201     public static final int SIM_STATE_ABSENT = TelephonyProtoEnums.SIM_STATE_ABSENT;  // 1
3202     /** SIM card state: Locked: requires the user's SIM PIN to unlock */
3203     public static final int SIM_STATE_PIN_REQUIRED =
3204             TelephonyProtoEnums.SIM_STATE_PIN_REQUIRED;  // 2
3205     /** SIM card state: Locked: requires the user's SIM PUK to unlock */
3206     public static final int SIM_STATE_PUK_REQUIRED =
3207             TelephonyProtoEnums.SIM_STATE_PUK_REQUIRED;  // 3
3208     /** SIM card state: Locked: requires a network PIN to unlock */
3209     public static final int SIM_STATE_NETWORK_LOCKED =
3210             TelephonyProtoEnums.SIM_STATE_NETWORK_LOCKED;  // 4
3211     /** SIM card state: Ready */
3212     public static final int SIM_STATE_READY = TelephonyProtoEnums.SIM_STATE_READY;  // 5
3213     /** SIM card state: SIM Card is NOT READY */
3214     public static final int SIM_STATE_NOT_READY = TelephonyProtoEnums.SIM_STATE_NOT_READY;  // 6
3215     /** SIM card state: SIM Card Error, permanently disabled */
3216     public static final int SIM_STATE_PERM_DISABLED =
3217             TelephonyProtoEnums.SIM_STATE_PERM_DISABLED;  // 7
3218     /** SIM card state: SIM Card Error, present but faulty */
3219     public static final int SIM_STATE_CARD_IO_ERROR =
3220             TelephonyProtoEnums.SIM_STATE_CARD_IO_ERROR;  // 8
3221     /** SIM card state: SIM Card restricted, present but not usable due to
3222      * carrier restrictions.
3223      */
3224     public static final int SIM_STATE_CARD_RESTRICTED =
3225             TelephonyProtoEnums.SIM_STATE_CARD_RESTRICTED;  // 9
3226     /**
3227      * SIM card state: Loaded: SIM card applications have been loaded
3228      * @hide
3229      */
3230     @SystemApi
3231     public static final int SIM_STATE_LOADED = TelephonyProtoEnums.SIM_STATE_LOADED;  // 10
3232     /**
3233      * SIM card state: SIM Card is present
3234      * @hide
3235      */
3236     @SystemApi
3237     public static final int SIM_STATE_PRESENT = TelephonyProtoEnums.SIM_STATE_PRESENT;  // 11
3238 
3239     /**
3240      * Extra included in {@link #ACTION_SIM_CARD_STATE_CHANGED} and
3241      * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED} to indicate the card/application state.
3242      *
3243      * @hide
3244      */
3245     @SystemApi
3246     public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
3247 
3248     /**
3249      * Broadcast Action: The sim card state has changed.
3250      * The intent will have the following extra values:</p>
3251      * <dl>
3252      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3253      *   <dd>The sim card state. One of:
3254      *     <dl>
3255      *       <dt>{@link #SIM_STATE_ABSENT}</dt>
3256      *       <dd>SIM card not found</dd>
3257      *       <dt>{@link #SIM_STATE_CARD_IO_ERROR}</dt>
3258      *       <dd>SIM card IO error</dd>
3259      *       <dt>{@link #SIM_STATE_CARD_RESTRICTED}</dt>
3260      *       <dd>SIM card is restricted</dd>
3261      *       <dt>{@link #SIM_STATE_PRESENT}</dt>
3262      *       <dd>SIM card is present</dd>
3263      *     </dl>
3264      *   </dd>
3265      * </dl>
3266      *
3267      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3268      *
3269      * <p class="note">The current state can also be queried using {@link #getSimCardState()}.
3270      *
3271      * <p class="note">This is a protected intent that can only be sent by the system.
3272      * @hide
3273      */
3274     @SystemApi
3275     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3276     public static final String ACTION_SIM_CARD_STATE_CHANGED =
3277             "android.telephony.action.SIM_CARD_STATE_CHANGED";
3278 
3279     /**
3280      * Broadcast Action: The sim application state has changed.
3281      * The intent will have the following extra values:</p>
3282      * <dl>
3283      *   <dt>{@link #EXTRA_SIM_STATE}</dt>
3284      *   <dd>The sim application state. One of:
3285      *     <dl>
3286      *       <dt>{@link #SIM_STATE_NOT_READY}</dt>
3287      *       <dd>SIM card applications not ready</dd>
3288      *       <dt>{@link #SIM_STATE_PIN_REQUIRED}</dt>
3289      *       <dd>SIM card PIN locked</dd>
3290      *       <dt>{@link #SIM_STATE_PUK_REQUIRED}</dt>
3291      *       <dd>SIM card PUK locked</dd>
3292      *       <dt>{@link #SIM_STATE_NETWORK_LOCKED}</dt>
3293      *       <dd>SIM card network locked</dd>
3294      *       <dt>{@link #SIM_STATE_PERM_DISABLED}</dt>
3295      *       <dd>SIM card permanently disabled due to PUK failures</dd>
3296      *       <dt>{@link #SIM_STATE_LOADED}</dt>
3297      *       <dd>SIM card data loaded</dd>
3298      *     </dl>
3299      *   </dd>
3300      * </dl>
3301      *
3302      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3303      *
3304      * <p class="note">The current state can also be queried using
3305      * {@link #getSimApplicationState()}.
3306      *
3307      * <p class="note">This is a protected intent that can only be sent by the system.
3308      * @hide
3309      */
3310     @SystemApi
3311     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3312     public static final String ACTION_SIM_APPLICATION_STATE_CHANGED =
3313             "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
3314 
3315     /**
3316      * Broadcast Action: Status of the SIM slots on the device has changed.
3317      *
3318      * <p class="note">Requires the READ_PRIVILEGED_PHONE_STATE permission.
3319      *
3320      * <p class="note">The status can be queried using
3321      * {@link #getUiccSlotsInfo()}
3322      *
3323      * <p class="note">This is a protected intent that can only be sent by the system.
3324      * @hide
3325      */
3326     @SystemApi
3327     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3328     public static final String ACTION_SIM_SLOT_STATUS_CHANGED =
3329             "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
3330 
3331     /**
3332      * Broadcast Action: A debug code has been entered in the dialer.
3333      * <p>
3334      * This intent is broadcast by the system and OEM telephony apps may need to receive these
3335      * broadcasts. And it requires the sender to be default dialer or has carrier privileges
3336      * (see {@link #hasCarrierPrivileges}).
3337      * <p>
3338      * These "secret codes" are used to activate developer menus by dialing certain codes.
3339      * And they are of the form {@code *#*#<code>#*#*}. The intent will have the data
3340      * URI: {@code android_secret_code://<code>}. It is possible that a manifest
3341      * receiver would be woken up even if it is not currently running.
3342      * <p>
3343      * It is supposed to replace {@link android.provider.Telephony.Sms.Intents#SECRET_CODE_ACTION}
3344      * in the next Android version.
3345      * Before that both of these two actions will be broadcast.
3346      */
3347     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3348     public static final String ACTION_SECRET_CODE = "android.telephony.action.SECRET_CODE";
3349 
3350     /**
3351      * @return true if a ICC card is present
3352      */
hasIccCard()3353     public boolean hasIccCard() {
3354         return hasIccCard(getSlotIndex());
3355     }
3356 
3357     /**
3358      * @return true if a ICC card is present for a subscription
3359      *
3360      * @param slotIndex for which icc card presence is checked
3361      */
3362     /** {@hide} */
3363     // FIXME Input argument slotIndex should be of type int
3364     @UnsupportedAppUsage
hasIccCard(int slotIndex)3365     public boolean hasIccCard(int slotIndex) {
3366 
3367         try {
3368             ITelephony telephony = getITelephony();
3369             if (telephony == null)
3370                 return false;
3371             return telephony.hasIccCardUsingSlotIndex(slotIndex);
3372         } catch (RemoteException ex) {
3373             // Assume no ICC card if remote exception which shouldn't happen
3374             return false;
3375         } catch (NullPointerException ex) {
3376             // This could happen before phone restarts due to crashing
3377             return false;
3378         }
3379     }
3380 
3381     /**
3382      * Returns a constant indicating the state of the default SIM card.
3383      *
3384      * @see #SIM_STATE_UNKNOWN
3385      * @see #SIM_STATE_ABSENT
3386      * @see #SIM_STATE_PIN_REQUIRED
3387      * @see #SIM_STATE_PUK_REQUIRED
3388      * @see #SIM_STATE_NETWORK_LOCKED
3389      * @see #SIM_STATE_READY
3390      * @see #SIM_STATE_NOT_READY
3391      * @see #SIM_STATE_PERM_DISABLED
3392      * @see #SIM_STATE_CARD_IO_ERROR
3393      * @see #SIM_STATE_CARD_RESTRICTED
3394      */
getSimState()3395     public @SimState int getSimState() {
3396         int simState = getSimStateIncludingLoaded();
3397         if (simState == SIM_STATE_LOADED) {
3398             simState = SIM_STATE_READY;
3399         }
3400         return simState;
3401     }
3402 
getSimStateIncludingLoaded()3403     private @SimState int getSimStateIncludingLoaded() {
3404         int slotIndex = getSlotIndex();
3405         // slotIndex may be invalid due to sim being absent. In that case query all slots to get
3406         // sim state
3407         if (slotIndex < 0) {
3408             // query for all slots and return absent if all sim states are absent, otherwise
3409             // return unknown
3410             for (int i = 0; i < getPhoneCount(); i++) {
3411                 int simState = getSimState(i);
3412                 if (simState != SIM_STATE_ABSENT) {
3413                     Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", sim state for " +
3414                             "slotIndex=" + i + " is " + simState + ", return state as unknown");
3415                     return SIM_STATE_UNKNOWN;
3416                 }
3417             }
3418             Rlog.d(TAG, "getSimState: default sim:" + slotIndex + ", all SIMs absent, return " +
3419                     "state as absent");
3420             return SIM_STATE_ABSENT;
3421         }
3422         return SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3423     }
3424 
3425     /**
3426      * Returns a constant indicating the state of the default SIM card.
3427      *
3428      * @see #SIM_STATE_UNKNOWN
3429      * @see #SIM_STATE_ABSENT
3430      * @see #SIM_STATE_CARD_IO_ERROR
3431      * @see #SIM_STATE_CARD_RESTRICTED
3432      * @see #SIM_STATE_PRESENT
3433      *
3434      * @hide
3435      */
3436     @SystemApi
getSimCardState()3437     public @SimState int getSimCardState() {
3438         int simState = getSimState();
3439         return getSimCardStateFromSimState(simState);
3440     }
3441 
3442     /**
3443      * Returns a constant indicating the state of the device SIM card in a physical slot.
3444      *
3445      * @param physicalSlotIndex physical slot index
3446      *
3447      * @see #SIM_STATE_UNKNOWN
3448      * @see #SIM_STATE_ABSENT
3449      * @see #SIM_STATE_CARD_IO_ERROR
3450      * @see #SIM_STATE_CARD_RESTRICTED
3451      * @see #SIM_STATE_PRESENT
3452      *
3453      * @hide
3454      */
3455     @SystemApi
3456     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimCardState(int physicalSlotIndex)3457     public @SimState int getSimCardState(int physicalSlotIndex) {
3458         int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex));
3459         return getSimCardStateFromSimState(simState);
3460     }
3461 
3462     /**
3463      * Converts SIM state to SIM card state.
3464      * @param simState
3465      * @return SIM card state
3466      */
getSimCardStateFromSimState(int simState)3467     private @SimState int getSimCardStateFromSimState(int simState) {
3468         switch (simState) {
3469             case SIM_STATE_UNKNOWN:
3470             case SIM_STATE_ABSENT:
3471             case SIM_STATE_CARD_IO_ERROR:
3472             case SIM_STATE_CARD_RESTRICTED:
3473                 return simState;
3474             default:
3475                 return SIM_STATE_PRESENT;
3476         }
3477     }
3478 
3479     /**
3480      * Converts a physical slot index to logical slot index.
3481      * @param physicalSlotIndex physical slot index
3482      * @return logical slot index
3483      */
getLogicalSlotIndex(int physicalSlotIndex)3484     private int getLogicalSlotIndex(int physicalSlotIndex) {
3485         UiccSlotInfo[] slotInfos = getUiccSlotsInfo();
3486         if (slotInfos != null && physicalSlotIndex >= 0 && physicalSlotIndex < slotInfos.length) {
3487             return slotInfos[physicalSlotIndex].getLogicalSlotIdx();
3488         }
3489 
3490         return SubscriptionManager.INVALID_SIM_SLOT_INDEX;
3491     }
3492 
3493     /**
3494      * Returns a constant indicating the state of the card applications on the default SIM card.
3495      *
3496      * @see #SIM_STATE_UNKNOWN
3497      * @see #SIM_STATE_PIN_REQUIRED
3498      * @see #SIM_STATE_PUK_REQUIRED
3499      * @see #SIM_STATE_NETWORK_LOCKED
3500      * @see #SIM_STATE_NOT_READY
3501      * @see #SIM_STATE_PERM_DISABLED
3502      * @see #SIM_STATE_LOADED
3503      *
3504      * @hide
3505      */
3506     @SystemApi
getSimApplicationState()3507     public @SimState int getSimApplicationState() {
3508         int simState = getSimStateIncludingLoaded();
3509         return getSimApplicationStateFromSimState(simState);
3510     }
3511 
3512     /**
3513      * Returns a constant indicating the state of the card applications on the device SIM card in
3514      * a physical slot.
3515      *
3516      * @param physicalSlotIndex physical slot index
3517      *
3518      * @see #SIM_STATE_UNKNOWN
3519      * @see #SIM_STATE_PIN_REQUIRED
3520      * @see #SIM_STATE_PUK_REQUIRED
3521      * @see #SIM_STATE_NETWORK_LOCKED
3522      * @see #SIM_STATE_NOT_READY
3523      * @see #SIM_STATE_PERM_DISABLED
3524      * @see #SIM_STATE_LOADED
3525      *
3526      * @hide
3527      */
3528     @SystemApi
3529     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimApplicationState(int physicalSlotIndex)3530     public @SimState int getSimApplicationState(int physicalSlotIndex) {
3531         int simState =
3532                 SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex));
3533         return getSimApplicationStateFromSimState(simState);
3534     }
3535 
3536     /**
3537      * Converts SIM state to SIM application state.
3538      * @param simState
3539      * @return SIM application state
3540      */
getSimApplicationStateFromSimState(int simState)3541     private @SimState int getSimApplicationStateFromSimState(int simState) {
3542         switch (simState) {
3543             case SIM_STATE_UNKNOWN:
3544             case SIM_STATE_ABSENT:
3545             case SIM_STATE_CARD_IO_ERROR:
3546             case SIM_STATE_CARD_RESTRICTED:
3547                 return SIM_STATE_UNKNOWN;
3548             case SIM_STATE_READY:
3549                 // Ready is not a valid state anymore. The state that is broadcast goes from
3550                 // NOT_READY to either LOCKED or LOADED.
3551                 return SIM_STATE_NOT_READY;
3552             default:
3553                 return simState;
3554         }
3555     }
3556 
3557 
3558     /**
3559      * Returns true if the specified type of application (e.g. {@link #APPTYPE_CSIM} is present
3560      * on the UICC card.
3561      *
3562      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
3563      *
3564      * @param appType the uicc app type like {@link APPTYPE_CSIM}
3565      * @return true if the specified type of application in UICC CARD or false if no uicc or error.
3566      * @hide
3567      */
3568     @SystemApi
3569     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApplicationOnUicc(@iccAppType int appType)3570     public boolean isApplicationOnUicc(@UiccAppType int appType) {
3571         try {
3572             ITelephony service = getITelephony();
3573             if (service != null) {
3574                 return service.isApplicationOnUicc(getSubId(), appType);
3575             }
3576         } catch (RemoteException e) {
3577             Log.e(TAG, "Error calling ITelephony#isApplicationOnUicc", e);
3578         }
3579         return false;
3580     }
3581 
3582     /**
3583      * Returns a constant indicating the state of the device SIM card in a logical slot.
3584      *
3585      * @param slotIndex logical slot index
3586      *
3587      * @see #SIM_STATE_UNKNOWN
3588      * @see #SIM_STATE_ABSENT
3589      * @see #SIM_STATE_PIN_REQUIRED
3590      * @see #SIM_STATE_PUK_REQUIRED
3591      * @see #SIM_STATE_NETWORK_LOCKED
3592      * @see #SIM_STATE_READY
3593      * @see #SIM_STATE_NOT_READY
3594      * @see #SIM_STATE_PERM_DISABLED
3595      * @see #SIM_STATE_CARD_IO_ERROR
3596      * @see #SIM_STATE_CARD_RESTRICTED
3597      */
getSimState(int slotIndex)3598     public @SimState int getSimState(int slotIndex) {
3599         int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex);
3600         if (simState == SIM_STATE_LOADED) {
3601             simState = SIM_STATE_READY;
3602         }
3603         return simState;
3604     }
3605 
3606     /**
3607      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3608      * provider of the SIM. 5 or 6 decimal digits.
3609      * <p>
3610      * Availability: SIM state must be {@link #SIM_STATE_READY}
3611      *
3612      * @see #getSimState
3613      */
getSimOperator()3614     public String getSimOperator() {
3615         return getSimOperatorNumeric();
3616     }
3617 
3618     /**
3619      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3620      * provider of the SIM. 5 or 6 decimal digits.
3621      * <p>
3622      * Availability: SIM state must be {@link #SIM_STATE_READY}
3623      *
3624      * @see #getSimState
3625      *
3626      * @param subId for which SimOperator is returned
3627      * @hide
3628      */
3629     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperator(int subId)3630     public String getSimOperator(int subId) {
3631         return getSimOperatorNumeric(subId);
3632     }
3633 
3634     /**
3635      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3636      * provider of the SIM. 5 or 6 decimal digits.
3637      * <p>
3638      * Availability: SIM state must be {@link #SIM_STATE_READY}
3639      *
3640      * @see #getSimState
3641      * @hide
3642      */
3643     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric()3644     public String getSimOperatorNumeric() {
3645         int subId = mSubId;
3646         if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3647             subId = SubscriptionManager.getDefaultDataSubscriptionId();
3648             if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3649                 subId = SubscriptionManager.getDefaultSmsSubscriptionId();
3650                 if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3651                     subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
3652                     if (!SubscriptionManager.isUsableSubIdValue(subId)) {
3653                         subId = SubscriptionManager.getDefaultSubscriptionId();
3654                     }
3655                 }
3656             }
3657         }
3658         return getSimOperatorNumeric(subId);
3659     }
3660 
3661     /**
3662      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3663      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3664      * <p>
3665      * Availability: SIM state must be {@link #SIM_STATE_READY}
3666      *
3667      * @see #getSimState
3668      *
3669      * @param subId for which SimOperator is returned
3670      * @hide
3671      */
3672     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumeric(int subId)3673     public String getSimOperatorNumeric(int subId) {
3674         int phoneId = SubscriptionManager.getPhoneId(subId);
3675         return getSimOperatorNumericForPhone(phoneId);
3676     }
3677 
3678     /**
3679      * Returns the MCC+MNC (mobile country code + mobile network code) of the
3680      * provider of the SIM for a particular subscription. 5 or 6 decimal digits.
3681      * <p>
3682      *
3683      * @param phoneId for which SimOperator is returned
3684      * @hide
3685      */
3686     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorNumericForPhone(int phoneId)3687     public String getSimOperatorNumericForPhone(int phoneId) {
3688         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_numeric(), "");
3689     }
3690 
3691     /**
3692      * Returns the Service Provider Name (SPN).
3693      * <p>
3694      * Availability: SIM state must be {@link #SIM_STATE_READY}
3695      *
3696      * @see #getSimState
3697      */
getSimOperatorName()3698     public String getSimOperatorName() {
3699         return getSimOperatorNameForPhone(getPhoneId());
3700     }
3701 
3702     /**
3703      * Returns the Service Provider Name (SPN).
3704      * <p>
3705      * Availability: SIM state must be {@link #SIM_STATE_READY}
3706      *
3707      * @see #getSimState
3708      *
3709      * @param subId for which SimOperatorName is returned
3710      * @hide
3711      */
3712     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimOperatorName(int subId)3713     public String getSimOperatorName(int subId) {
3714         int phoneId = SubscriptionManager.getPhoneId(subId);
3715         return getSimOperatorNameForPhone(phoneId);
3716     }
3717 
3718     /**
3719      * Returns the Service Provider Name (SPN).
3720      *
3721      * @hide
3722      */
3723     @UnsupportedAppUsage
getSimOperatorNameForPhone(int phoneId)3724     public String getSimOperatorNameForPhone(int phoneId) {
3725         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_alpha(), "");
3726     }
3727 
3728     /**
3729      * Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
3730      * <p>
3731      * The ISO-3166-1 alpha-2 country code is provided in lowercase 2 character format.
3732      * @return the lowercase 2 character ISO-3166-1 alpha-2 country code, or empty string is not
3733      * available.
3734      */
getSimCountryIso()3735     public String getSimCountryIso() {
3736         return getSimCountryIsoForPhone(getPhoneId());
3737     }
3738 
3739     /**
3740      * Returns the ISO country code equivalent for the SIM provider's country code.
3741      *
3742      * @param subId for which SimCountryIso is returned
3743      * @hide
3744      */
3745     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSimCountryIso(int subId)3746     public static String getSimCountryIso(int subId) {
3747         int phoneId = SubscriptionManager.getPhoneId(subId);
3748         return getSimCountryIsoForPhone(phoneId);
3749     }
3750 
3751     /**
3752      * Returns the ISO country code equivalent for the SIM provider's country code.
3753      *
3754      * @hide
3755      */
3756     @UnsupportedAppUsage
getSimCountryIsoForPhone(int phoneId)3757     public static String getSimCountryIsoForPhone(int phoneId) {
3758         return getTelephonyProperty(phoneId, TelephonyProperties.icc_operator_iso_country(), "");
3759     }
3760 
3761     /**
3762      * Returns the serial number of the SIM, if applicable. Return null if it is
3763      * unavailable.
3764      *
3765      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
3766      * restrictions, and apps are recommended to use resettable identifiers (see <a
3767      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
3768      * method can be invoked if one of the following requirements is met:
3769      * <ul>
3770      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
3771      *     is a privileged permission that can only be granted to apps preloaded on the device.
3772      *     <li>If the calling app is the device owner of a fully-managed device, a profile
3773      *     owner of an organization-owned device, or their delegates (see {@link
3774      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
3775      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3776      *     <li>If the calling app is the default SMS role holder (see {@link
3777      *     RoleManager#isRoleHeld(String)}).
3778      * </ul>
3779      *
3780      * <p>If the calling app does not meet one of these requirements then this method will behave
3781      * as follows:
3782      *
3783      * <ul>
3784      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3785      *     READ_PHONE_STATE permission then null is returned.</li>
3786      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3787      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3788      *     higher, then a SecurityException is thrown.</li>
3789      * </ul>
3790      */
3791     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
3792     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimSerialNumber()3793     public String getSimSerialNumber() {
3794          return getSimSerialNumber(getSubId());
3795     }
3796 
3797     /**
3798      * Returns the serial number for the given subscription, if applicable. Return null if it is
3799      * unavailable.
3800      *
3801      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
3802      * restrictions, and apps are recommended to use resettable identifiers (see <a
3803      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
3804      * method can be invoked if one of the following requirements is met:
3805      * <ul>
3806      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
3807      *     is a privileged permission that can only be granted to apps preloaded on the device.
3808      *     <li>If the calling app is the device owner of a fully-managed device, a profile
3809      *     owner of an organization-owned device, or their delegates (see {@link
3810      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
3811      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3812      *     <li>If the calling app is the default SMS role holder (see {@link
3813      *     RoleManager#isRoleHeld(String)}).
3814      * </ul>
3815      *
3816      * <p>If the calling app does not meet one of these requirements then this method will behave
3817      * as follows:
3818      *
3819      * <ul>
3820      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
3821      *     READ_PHONE_STATE permission then null is returned.</li>
3822      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
3823      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
3824      *     higher, then a SecurityException is thrown.</li>
3825      * </ul>
3826      *
3827      * @param subId for which Sim Serial number is returned
3828      * @hide
3829      */
3830     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3831     @UnsupportedAppUsage
getSimSerialNumber(int subId)3832     public String getSimSerialNumber(int subId) {
3833         try {
3834             IPhoneSubInfo info = getSubscriberInfoService();
3835             if (info == null)
3836                 return null;
3837             return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
3838                     mContext.getAttributionTag());
3839         } catch (RemoteException ex) {
3840             return null;
3841         } catch (NullPointerException ex) {
3842             // This could happen before phone restarts due to crashing
3843             return null;
3844         }
3845     }
3846 
3847     /**
3848      * Return if the current radio can support both 3GPP and 3GPP2 radio technologies at the same
3849      * time. This is also known as global mode, which includes LTE, CDMA, EvDo and GSM/WCDMA.
3850      *
3851      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
3852      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
3853      *
3854      * @return {@code true} if 3GPP and 3GPP2 radio technologies can be supported at the same time
3855      *         {@code false} if not supported or unknown
3856      * @hide
3857      */
3858     @SystemApi
3859     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isLteCdmaEvdoGsmWcdmaEnabled()3860     public boolean isLteCdmaEvdoGsmWcdmaEnabled() {
3861         return getLteOnCdmaMode(getSubId()) == PhoneConstants.LTE_ON_CDMA_TRUE;
3862     }
3863 
3864     /**
3865      * Return if the current radio is LTE on CDMA for Subscription. This
3866      * is a tri-state return value as for a period of time
3867      * the mode may be unknown.
3868      *
3869      * @param subId for which radio is LTE on CDMA is returned
3870      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
3871      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
3872      * @hide
3873      */
3874     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3875     @UnsupportedAppUsage
getLteOnCdmaMode(int subId)3876     public int getLteOnCdmaMode(int subId) {
3877         try {
3878             ITelephony telephony = getITelephony();
3879             if (telephony == null)
3880                 return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3881             return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
3882                     getAttributionTag());
3883         } catch (RemoteException ex) {
3884             // Assume no ICC card if remote exception which shouldn't happen
3885             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3886         } catch (NullPointerException ex) {
3887             // This could happen before phone restarts due to crashing
3888             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
3889         }
3890     }
3891 
3892     /**
3893      * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
3894      * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
3895      * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
3896      *
3897      * <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
3898      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
3899      * through a factory reset.
3900      *
3901      * @return card ID of the default eUICC card, if loaded.
3902      */
getCardIdForDefaultEuicc()3903     public int getCardIdForDefaultEuicc() {
3904         try {
3905             ITelephony telephony = getITelephony();
3906             if (telephony == null) {
3907                 return UNINITIALIZED_CARD_ID;
3908             }
3909             return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
3910         } catch (RemoteException e) {
3911             return UNINITIALIZED_CARD_ID;
3912         }
3913     }
3914 
3915     /**
3916      * Gets information about currently inserted UICCs and eUICCs.
3917      * <p>
3918      * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
3919      * <p>
3920      * If the caller has carrier priviliges on any active subscription, then they have permission to
3921      * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
3922      * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the slot index where the card is inserted
3923      * ({@link UiccCardInfo#getSlotIndex()}).
3924      * <p>
3925      * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
3926      * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
3927      * UICC or eUICC card.
3928      * <p>
3929      * See {@link UiccCardInfo} for more details on the kind of information available.
3930      *
3931      * @return a list of UiccCardInfo objects, representing information on the currently inserted
3932      * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
3933      * the caller does not have adequate permissions for that card.
3934      */
3935     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
3936     @NonNull
getUiccCardsInfo()3937     public List<UiccCardInfo> getUiccCardsInfo() {
3938         try {
3939             ITelephony telephony = getITelephony();
3940             if (telephony == null) {
3941                 Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
3942                 return new ArrayList<UiccCardInfo>();
3943             }
3944             return telephony.getUiccCardsInfo(mContext.getOpPackageName());
3945         } catch (RemoteException e) {
3946             Log.e(TAG, "Error in getUiccCardsInfo: " + e);
3947             return new ArrayList<UiccCardInfo>();
3948         }
3949     }
3950 
3951     /**
3952      * Gets all the UICC slots. The objects in the array can be null if the slot info is not
3953      * available, which is possible between phone process starting and getting slot info from modem.
3954      *
3955      * @return UiccSlotInfo array.
3956      *
3957      * @hide
3958      */
3959     @SystemApi
3960     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getUiccSlotsInfo()3961     public UiccSlotInfo[] getUiccSlotsInfo() {
3962         try {
3963             ITelephony telephony = getITelephony();
3964             if (telephony == null) {
3965                 return null;
3966             }
3967             return telephony.getUiccSlotsInfo();
3968         } catch (RemoteException e) {
3969             return null;
3970         }
3971     }
3972 
3973     /**
3974      * Test method to reload the UICC profile.
3975      *
3976      * @hide
3977      */
3978     @TestApi
3979     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
refreshUiccProfile()3980     public void refreshUiccProfile() {
3981         try {
3982             ITelephony telephony = getITelephony();
3983             telephony.refreshUiccProfile(mSubId);
3984         } catch (RemoteException ex) {
3985             Rlog.w(TAG, "RemoteException", ex);
3986         }
3987     }
3988 
3989     /**
3990      * Map logicalSlot to physicalSlot, and activate the physicalSlot if it is inactive. For
3991      * example, passing the physicalSlots array [1, 0] means mapping the first item 1, which is
3992      * physical slot index 1, to the logical slot 0; and mapping the second item 0, which is
3993      * physical slot index 0, to the logical slot 1. The index of the array means the index of the
3994      * logical slots.
3995      *
3996      * @param physicalSlots The content of the array represents the physical slot index. The array
3997      *        size should be same as {@link #getUiccSlotsInfo()}.
3998      * @return boolean Return true if the switch succeeds, false if the switch fails.
3999      * @hide
4000      */
4001     @SystemApi
4002     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchSlots(int[] physicalSlots)4003     public boolean switchSlots(int[] physicalSlots) {
4004         try {
4005             ITelephony telephony = getITelephony();
4006             if (telephony == null) {
4007                 return false;
4008             }
4009             return telephony.switchSlots(physicalSlots);
4010         } catch (RemoteException e) {
4011             return false;
4012         }
4013     }
4014 
4015     /**
4016      * Get the mapping from logical slots to physical slots. The key of the map is the logical slot
4017      * id and the value is the physical slots id mapped to this logical slot id.
4018      *
4019      * @return a map indicates the mapping from logical slots to physical slots. The size of the map
4020      * should be {@link #getPhoneCount()} if success, otherwise return an empty map.
4021      *
4022      * @hide
4023      */
4024     @SystemApi
4025     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4026     @NonNull
getLogicalToPhysicalSlotMapping()4027     public Map<Integer, Integer> getLogicalToPhysicalSlotMapping() {
4028         Map<Integer, Integer> slotMapping = new HashMap<>();
4029         try {
4030             ITelephony telephony = getITelephony();
4031             if (telephony != null) {
4032                 int[] slotMappingArray = telephony.getSlotsMapping();
4033                 for (int i = 0; i < slotMappingArray.length; i++) {
4034                     slotMapping.put(i, slotMappingArray[i]);
4035                 }
4036             }
4037         } catch (RemoteException e) {
4038             Log.e(TAG, "getSlotsMapping RemoteException", e);
4039         }
4040         return slotMapping;
4041     }
4042 
4043     //
4044     //
4045     // Subscriber Info
4046     //
4047     //
4048 
4049     /**
4050      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
4051      * Return null if it is unavailable.
4052      *
4053      * <p>Starting with API level 29, persistent device identifiers are guarded behind additional
4054      * restrictions, and apps are recommended to use resettable identifiers (see <a
4055      * href="/training/articles/user-data-ids">Best practices for unique identifiers</a>). This
4056      * method can be invoked if one of the following requirements is met:
4057      * <ul>
4058      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
4059      *     is a privileged permission that can only be granted to apps preloaded on the device.
4060      *     <li>If the calling app is the device owner of a fully-managed device, a profile
4061      *     owner of an organization-owned device, or their delegates (see {@link
4062      *     android.app.admin.DevicePolicyManager#getEnrollmentSpecificId()}).
4063      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4064      *     <li>If the calling app is the default SMS role holder (see {@link
4065      *     RoleManager#isRoleHeld(String)}).
4066      *     <li>If the calling app has been granted the
4067      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
4068      * </ul>
4069      *
4070      * <p>If the calling app does not meet one of these requirements then this method will behave
4071      * as follows:
4072      *
4073      * <ul>
4074      *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
4075      *     READ_PHONE_STATE permission then null is returned.</li>
4076      *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
4077      *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
4078      *     higher, then a SecurityException is thrown.</li>
4079      * </ul>
4080      */
4081     @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
4082     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSubscriberId()4083     public String getSubscriberId() {
4084         return getSubscriberId(getSubId());
4085     }
4086 
4087     /**
4088      * Returns the unique subscriber ID, for example, the IMSI for a GSM phone
4089      * for a subscription.
4090      * Return null if it is unavailable.
4091      *
4092      * See {@link #getSubscriberId()} for details on the required permissions and behavior
4093      * when the caller does not hold sufficient permissions.
4094      *
4095      * @param subId whose subscriber id is returned
4096      * @hide
4097      */
4098     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4099     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getSubscriberId(int subId)4100     public String getSubscriberId(int subId) {
4101         try {
4102             IPhoneSubInfo info = getSubscriberInfoService();
4103             if (info == null)
4104                 return null;
4105             return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
4106                     mContext.getAttributionTag());
4107         } catch (RemoteException ex) {
4108             return null;
4109         } catch (NullPointerException ex) {
4110             // This could happen before phone restarts due to crashing
4111             return null;
4112         }
4113     }
4114 
4115     /**
4116      * Returns carrier specific information that will be used to encrypt the IMSI and IMPI,
4117      * including the public key and the key identifier; or {@code null} if not available.
4118      * <p>
4119      * For a multi-sim device, the dafault data sim is used if not specified.
4120      * <p>
4121      * Requires Permission: READ_PRIVILEGED_PHONE_STATE.
4122      *
4123      * @param keyType whether the key is being used for EPDG or WLAN. Valid values are
4124      *        {@link #KEY_TYPE_EPDG} or {@link #KEY_TYPE_WLAN}.
4125      * @return ImsiEncryptionInfo Carrier specific information that will be used to encrypt the
4126      *         IMSI and IMPI. This includes the public key and the key identifier. This information
4127      *         will be stored in the device keystore. {@code null} will be returned when no key is
4128      *         found, and the carrier does not require a key.
4129      * @throws IllegalArgumentException when an invalid key is found or when key is required but
4130      *         not found.
4131      * @hide
4132      */
4133     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
4134     @SystemApi
4135     @Nullable
getCarrierInfoForImsiEncryption(@eyType int keyType)4136     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(@KeyType int keyType) {
4137         try {
4138             IPhoneSubInfo info = getSubscriberInfoService();
4139             if (info == null) {
4140                 Rlog.e(TAG,"IMSI error: Subscriber Info is null");
4141                 return null;
4142             }
4143             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4144             if (keyType != KEY_TYPE_EPDG && keyType != KEY_TYPE_WLAN) {
4145                 throw new IllegalArgumentException("IMSI error: Invalid key type");
4146             }
4147             ImsiEncryptionInfo imsiEncryptionInfo = info.getCarrierInfoForImsiEncryption(
4148                     subId, keyType, mContext.getOpPackageName());
4149             if (imsiEncryptionInfo == null && isImsiEncryptionRequired(subId, keyType)) {
4150                 Rlog.e(TAG, "IMSI error: key is required but not found");
4151                 throw new IllegalArgumentException("IMSI error: key is required but not found");
4152             }
4153             return imsiEncryptionInfo;
4154         } catch (RemoteException ex) {
4155             Rlog.e(TAG, "getCarrierInfoForImsiEncryption RemoteException" + ex);
4156         } catch (NullPointerException ex) {
4157             // This could happen before phone restarts due to crashing
4158             Rlog.e(TAG, "getCarrierInfoForImsiEncryption NullPointerException" + ex);
4159         }
4160         return null;
4161     }
4162 
4163     /**
4164      * Resets the carrier keys used to encrypt the IMSI and IMPI.
4165      * <p>
4166      * This involves 2 steps:
4167      *  1. Delete the keys from the database.
4168      *  2. Send an intent to download new Certificates.
4169      * <p>
4170      * For a multi-sim device, the dafault data sim is used if not specified.
4171      * <p>
4172      * Requires Permission: MODIFY_PHONE_STATE.
4173      *
4174      * @see #getCarrierInfoForImsiEncryption
4175      * @hide
4176      */
4177     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
4178     @SystemApi
resetCarrierKeysForImsiEncryption()4179     public void resetCarrierKeysForImsiEncryption() {
4180         try {
4181             IPhoneSubInfo info = getSubscriberInfoService();
4182             if (info == null) {
4183                 throw new RuntimeException("IMSI error: Subscriber Info is null");
4184             }
4185             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
4186             info.resetCarrierKeysForImsiEncryption(subId, mContext.getOpPackageName());
4187         } catch (RemoteException ex) {
4188             Rlog.e(TAG, "Telephony#getCarrierInfoForImsiEncryption RemoteException" + ex);
4189         }
4190     }
4191 
4192     /**
4193      * @param keyAvailability bitmask that defines the availabilty of keys for a type.
4194      * @param keyType the key type which is being checked. (WLAN, EPDG)
4195      * @return true if the digit at position keyType is 1, else false.
4196      * @hide
4197      */
isKeyEnabled(int keyAvailability, @KeyType int keyType)4198     private static boolean isKeyEnabled(int keyAvailability, @KeyType int keyType) {
4199         int returnValue = (keyAvailability >> (keyType - 1)) & 1;
4200         return (returnValue == 1) ? true : false;
4201     }
4202 
4203     /**
4204      * If Carrier requires Imsi to be encrypted.
4205      * @hide
4206      */
isImsiEncryptionRequired(int subId, @KeyType int keyType)4207     private boolean isImsiEncryptionRequired(int subId, @KeyType int keyType) {
4208         CarrierConfigManager configManager =
4209                 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
4210         if (configManager == null) {
4211             return false;
4212         }
4213         PersistableBundle pb = configManager.getConfigForSubId(subId);
4214         if (pb == null) {
4215             return false;
4216         }
4217         int keyAvailability = pb.getInt(CarrierConfigManager.IMSI_KEY_AVAILABILITY_INT);
4218         return isKeyEnabled(keyAvailability, keyType);
4219     }
4220 
4221     /**
4222      * Sets the Carrier specific information that will be used to encrypt the IMSI and IMPI.
4223      * This includes the public key and the key identifier. This information will be stored in the
4224      * device keystore.
4225      * <p>
4226      * Requires Permission:
4227      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
4228      * @param imsiEncryptionInfo which includes the Key Type, the Public Key
4229      *        (java.security.PublicKey) and the Key Identifier.and the Key Identifier.
4230      *        The keyIdentifier Attribute value pair that helps a server locate
4231      *        the private key to decrypt the permanent identity. This field is
4232      *        optional and if it is present then it’s always separated from encrypted
4233      *        permanent identity with “,”. Key identifier AVP is presented in ASCII string
4234      *        with “name=value” format.
4235      * @hide
4236      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4237     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4238         try {
4239             IPhoneSubInfo info = getSubscriberInfoService();
4240             if (info == null) return;
4241             info.setCarrierInfoForImsiEncryption(mSubId, mContext.getOpPackageName(),
4242                     imsiEncryptionInfo);
4243         } catch (NullPointerException ex) {
4244             // This could happen before phone restarts due to crashing
4245             return;
4246         } catch (RemoteException ex) {
4247             Rlog.e(TAG, "setCarrierInfoForImsiEncryption RemoteException", ex);
4248             return;
4249         }
4250     }
4251 
4252     /**
4253      * Exception that may be supplied to the callback in {@link #uploadCallComposerPicture} if
4254      * something goes awry.
4255      */
4256     public static class CallComposerException extends Exception {
4257         /**
4258          * Used internally only, signals success of the upload to the carrier.
4259          * @hide
4260          */
4261         public static final int SUCCESS = -1;
4262         /**
4263          * Indicates that an unknown error was encountered when uploading the call composer picture.
4264          *
4265          * Clients that encounter this error should retry the upload.
4266          */
4267         public static final int ERROR_UNKNOWN = 0;
4268 
4269         /**
4270          * Indicates that the phone process died or otherwise became unavailable while uploading the
4271          * call composer picture.
4272          *
4273          * Clients that encounter this error should retry the upload.
4274          */
4275         public static final int ERROR_REMOTE_END_CLOSED = 1;
4276 
4277         /**
4278          * Indicates that the file or stream supplied exceeds the size limit defined in
4279          * {@link #getMaximumCallComposerPictureSize()}.
4280          *
4281          * Clients that encounter this error should retry the upload after reducing the size of the
4282          * picture.
4283          */
4284         public static final int ERROR_FILE_TOO_LARGE = 2;
4285 
4286         /**
4287          * Indicates that the device failed to authenticate with the carrier when uploading the
4288          * picture.
4289          *
4290          * Clients that encounter this error should not retry the upload unless a reboot or radio
4291          * reset has been performed in the interim.
4292          */
4293         public static final int ERROR_AUTHENTICATION_FAILED = 3;
4294 
4295         /**
4296          * Indicates that the {@link InputStream} passed to {@link #uploadCallComposerPicture}
4297          * was closed.
4298          *
4299          * The caller should retry if this error is encountered, and be sure to not close the stream
4300          * before the callback is called this time.
4301          */
4302         public static final int ERROR_INPUT_CLOSED = 4;
4303 
4304         /**
4305          * Indicates that an {@link IOException} was encountered while reading the picture.
4306          *
4307          * The offending {@link IOException} will be available via {@link #getIOException()}.
4308          * Clients should use the contents of the exception to determine whether a retry is
4309          * warranted.
4310          */
4311         public static final int ERROR_IO_EXCEPTION = 5;
4312 
4313         /**
4314          * Indicates that the device is currently not connected to a network that's capable of
4315          * reaching a carrier's RCS servers.
4316          *
4317          * Clients should prompt the user to remedy the issue by moving to an area with better
4318          * signal, by connecting to a different network, or to retry at another time.
4319          */
4320         public static final int ERROR_NETWORK_UNAVAILABLE = 6;
4321 
4322         /** @hide */
4323         @IntDef(prefix = {"ERROR_"}, value = {
4324                 ERROR_UNKNOWN,
4325                 ERROR_REMOTE_END_CLOSED,
4326                 ERROR_FILE_TOO_LARGE,
4327                 ERROR_AUTHENTICATION_FAILED,
4328                 ERROR_INPUT_CLOSED,
4329                 ERROR_IO_EXCEPTION,
4330                 ERROR_NETWORK_UNAVAILABLE,
4331         })
4332 
4333         @Retention(RetentionPolicy.SOURCE)
4334         public @interface CallComposerError {}
4335 
4336         private final int mErrorCode;
4337         private final IOException mIOException;
4338 
CallComposerException(@allComposerError int errorCode, @Nullable IOException ioException)4339         public CallComposerException(@CallComposerError int errorCode,
4340                 @Nullable IOException ioException) {
4341             mErrorCode = errorCode;
4342             mIOException = ioException;
4343         }
4344 
4345         /**
4346          * Fetches the error code associated with this exception.
4347          * @return An error code.
4348          */
getErrorCode()4349         public @CallComposerError int getErrorCode() {
4350             return mErrorCode;
4351         }
4352 
4353         /**
4354          * Fetches the {@link IOException} that caused the error.
4355          */
4356         // Follows the naming of IOException
4357         @SuppressLint("AcronymName")
getIOException()4358         public @Nullable IOException getIOException() {
4359             return mIOException;
4360         }
4361     }
4362 
4363     /** @hide */
4364     public static final String KEY_CALL_COMPOSER_PICTURE_HANDLE = "call_composer_picture_handle";
4365 
4366     /**
4367      * Uploads a picture to the carrier network for use with call composer.
4368      *
4369      * @see #uploadCallComposerPicture(InputStream, String, Executor, OutcomeReceiver)
4370      * @param pictureToUpload Path to a local file containing the picture to upload.
4371      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg)
4372      * @param executor The {@link Executor} on which the {@code pictureToUpload} file will be read
4373      *                 from disk, as well as on which {@code callback} will be called.
4374      * @param callback A callback called when the upload operation terminates, either in success
4375      *                 or in error.
4376      */
uploadCallComposerPicture(@onNull Path pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)4377     public void uploadCallComposerPicture(@NonNull Path pictureToUpload,
4378             @NonNull String contentType,
4379             @CallbackExecutor @NonNull Executor executor,
4380             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
4381         Objects.requireNonNull(pictureToUpload);
4382         Objects.requireNonNull(executor);
4383         Objects.requireNonNull(callback);
4384 
4385         // Do the role check now so that we can quit early if needed -- there's an additional
4386         // permission check on the other side of the binder call as well.
4387         RoleManager rm = mContext.getSystemService(RoleManager.class);
4388         if (!rm.isRoleHeld(RoleManager.ROLE_DIALER)) {
4389             throw new SecurityException("You must hold RoleManager.ROLE_DIALER to do this");
4390         }
4391 
4392         executor.execute(() -> {
4393             try {
4394                 if (Looper.getMainLooper().isCurrentThread()) {
4395                     Log.w(TAG, "Uploading call composer picture on main thread!"
4396                             + " hic sunt dracones!");
4397                 }
4398                 long size = Files.size(pictureToUpload);
4399                 if (size > getMaximumCallComposerPictureSize()) {
4400                     callback.onError(new CallComposerException(
4401                             CallComposerException.ERROR_FILE_TOO_LARGE, null));
4402                     return;
4403                 }
4404                 InputStream fileStream = Files.newInputStream(pictureToUpload);
4405                 try {
4406                     uploadCallComposerPicture(fileStream, contentType, executor,
4407                             new OutcomeReceiver<ParcelUuid, CallComposerException>() {
4408                                 @Override
4409                                 public void onResult(ParcelUuid result) {
4410                                     try {
4411                                         fileStream.close();
4412                                     } catch (IOException e) {
4413                                         // ignore
4414                                         Log.e(TAG, "Error closing file input stream when"
4415                                                 + " uploading call composer pic");
4416                                     }
4417                                     callback.onResult(result);
4418                                 }
4419 
4420                                 @Override
4421                                 public void onError(CallComposerException error) {
4422                                     try {
4423                                         fileStream.close();
4424                                     } catch (IOException e) {
4425                                         // ignore
4426                                         Log.e(TAG, "Error closing file input stream when"
4427                                                 + " uploading call composer pic");
4428                                     }
4429                                     callback.onError(error);
4430                                 }
4431                             });
4432                 } catch (Exception e) {
4433                     Log.e(TAG, "Got exception calling into stream-version of"
4434                             + " uploadCallComposerPicture: " + e);
4435                     try {
4436                         fileStream.close();
4437                     } catch (IOException e1) {
4438                         // ignore
4439                         Log.e(TAG, "Error closing file input stream when uploading"
4440                                 + " call composer pic");
4441                     }
4442                 }
4443             } catch (IOException e) {
4444                 Log.e(TAG, "IOException when uploading call composer pic:" + e);
4445                 callback.onError(
4446                         new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e));
4447             }
4448         });
4449 
4450     }
4451 
4452     /**
4453      * Uploads a picture to the carrier network for use with call composer.
4454      *
4455      * This method allows a dialer app to upload a picture to the carrier network that can then
4456      * later be attached to an outgoing call. In order to attach the picture to a call, use the
4457      * {@link ParcelUuid} returned from {@code callback} upon successful upload as the value to
4458      * {@link TelecomManager#EXTRA_OUTGOING_PICTURE}.
4459      *
4460      * This functionality is only available to the app filling the {@link RoleManager#ROLE_DIALER}
4461      * role on the device.
4462      *
4463      * This functionality is only available when
4464      * {@link CarrierConfigManager#KEY_SUPPORTS_CALL_COMPOSER_BOOL} is set to {@code true} in the
4465      * bundle returned from {@link #getCarrierConfig()}.
4466      *
4467      * @param pictureToUpload An {@link InputStream} that supplies the bytes representing the
4468      *                        picture to upload. The client bears responsibility for closing this
4469      *                        stream after {@code callback} is called with success or failure.
4470      *
4471      *                        Additionally, if the stream supplies more bytes than the return value
4472      *                        of {@link #getMaximumCallComposerPictureSize()}, the upload will be
4473      *                        aborted and the callback will be called with an exception containing
4474      *                        {@link CallComposerException#ERROR_FILE_TOO_LARGE}.
4475      * @param contentType The MIME type of the picture you're uploading (e.g. image/jpeg). The list
4476      *                    of acceptable content types can be found at 3GPP TS 26.141 sections
4477      *                    4.2 and 4.3.
4478      * @param executor The {@link Executor} on which the {@code pictureToUpload} stream will be
4479      *                 read, as well as on which the callback will be called.
4480      * @param callback A callback called when the upload operation terminates, either in success
4481      *                 or in error.
4482      */
uploadCallComposerPicture(@onNull InputStream pictureToUpload, @NonNull String contentType, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback)4483     public void uploadCallComposerPicture(@NonNull InputStream pictureToUpload,
4484             @NonNull String contentType,
4485             @CallbackExecutor @NonNull Executor executor,
4486             @NonNull OutcomeReceiver<ParcelUuid, CallComposerException> callback) {
4487         Objects.requireNonNull(pictureToUpload);
4488         Objects.requireNonNull(executor);
4489         Objects.requireNonNull(callback);
4490 
4491         ITelephony telephony = getITelephony();
4492         if (telephony == null) {
4493             throw new IllegalStateException("Telephony service not available.");
4494         }
4495 
4496         ParcelFileDescriptor writeFd;
4497         ParcelFileDescriptor readFd;
4498         try {
4499             ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createReliablePipe();
4500             writeFd = pipe[1];
4501             readFd = pipe[0];
4502         } catch (IOException e) {
4503             executor.execute(() -> callback.onError(
4504                     new CallComposerException(CallComposerException.ERROR_IO_EXCEPTION, e)));
4505             return;
4506         }
4507 
4508         OutputStream output = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
4509 
4510         try {
4511             telephony.uploadCallComposerPicture(getSubId(), mContext.getOpPackageName(),
4512                     contentType, readFd, new ResultReceiver(null) {
4513                         @Override
4514                         protected void onReceiveResult(int resultCode, Bundle result) {
4515                             if (resultCode != CallComposerException.SUCCESS) {
4516                                 executor.execute(() -> callback.onError(
4517                                         new CallComposerException(resultCode, null)));
4518                                 return;
4519                             }
4520                             ParcelUuid resultUuid =
4521                                     result.getParcelable(KEY_CALL_COMPOSER_PICTURE_HANDLE);
4522                             if (resultUuid == null) {
4523                                 Log.e(TAG, "Got null uuid without an error"
4524                                         + " while uploading call composer pic");
4525                                 executor.execute(() -> callback.onError(
4526                                         new CallComposerException(
4527                                                 CallComposerException.ERROR_UNKNOWN, null)));
4528                                 return;
4529                             }
4530                             executor.execute(() -> callback.onResult(resultUuid));
4531                         }
4532                     });
4533         } catch (RemoteException e) {
4534             Log.e(TAG, "Remote exception uploading call composer pic:" + e);
4535             e.rethrowAsRuntimeException();
4536         }
4537 
4538         executor.execute(() -> {
4539             if (Looper.getMainLooper().isCurrentThread()) {
4540                 Log.w(TAG, "Uploading call composer picture on main thread!"
4541                         + " hic sunt dracones!");
4542             }
4543 
4544             int totalBytesRead = 0;
4545             byte[] buffer = new byte[16 * 1024];
4546             try {
4547                 while (true) {
4548                     int numRead;
4549                     try {
4550                         numRead = pictureToUpload.read(buffer);
4551                     } catch (IOException e) {
4552                         Log.e(TAG, "IOException reading from input while uploading pic: " + e);
4553                         // Most likely, this was because the stream was closed. We have no way to
4554                         // tell though.
4555                         callback.onError(new CallComposerException(
4556                                 CallComposerException.ERROR_INPUT_CLOSED, e));
4557                         try {
4558                             writeFd.closeWithError("input closed");
4559                         } catch (IOException e1) {
4560                             // log and ignore
4561                             Log.e(TAG, "Error closing fd pipe: " + e1);
4562                         }
4563                         break;
4564                     }
4565 
4566                     if (numRead < 0) {
4567                         break;
4568                     }
4569 
4570                     totalBytesRead += numRead;
4571                     if (totalBytesRead > getMaximumCallComposerPictureSize()) {
4572                         Log.e(TAG, "Read too many bytes from call composer pic stream: "
4573                                 + totalBytesRead);
4574                         try {
4575                             callback.onError(new CallComposerException(
4576                                     CallComposerException.ERROR_FILE_TOO_LARGE, null));
4577                             writeFd.closeWithError("too large");
4578                         } catch (IOException e1) {
4579                             // log and ignore
4580                             Log.e(TAG, "Error closing fd pipe: " + e1);
4581                         }
4582                         break;
4583                     }
4584 
4585                     try {
4586                         output.write(buffer, 0, numRead);
4587                     } catch (IOException e) {
4588                         callback.onError(new CallComposerException(
4589                                 CallComposerException.ERROR_REMOTE_END_CLOSED, e));
4590                         try {
4591                             writeFd.closeWithError("remote end closed");
4592                         } catch (IOException e1) {
4593                             // log and ignore
4594                             Log.e(TAG, "Error closing fd pipe: " + e1);
4595                         }
4596                         break;
4597                     }
4598                 }
4599             } finally {
4600                 try {
4601                     output.close();
4602                 } catch (IOException e) {
4603                     // Ignore -- we might've already closed it.
4604                 }
4605             }
4606         });
4607     }
4608 
4609     /**
4610      * Returns the Group Identifier Level1 for a GSM phone.
4611      * Return null if it is unavailable.
4612      *
4613      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4614      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4615      */
4616     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4617     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getGroupIdLevel1()4618     public String getGroupIdLevel1() {
4619         try {
4620             IPhoneSubInfo info = getSubscriberInfoService();
4621             if (info == null)
4622                 return null;
4623             return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
4624                     mContext.getAttributionTag());
4625         } catch (RemoteException ex) {
4626             return null;
4627         } catch (NullPointerException ex) {
4628             // This could happen before phone restarts due to crashing
4629             return null;
4630         }
4631     }
4632 
4633     /**
4634      * Returns the Group Identifier Level1 for a GSM phone for a particular subscription.
4635      * Return null if it is unavailable.
4636      *
4637      * @param subId whose subscriber id is returned
4638      * @hide
4639      */
4640     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4641     @UnsupportedAppUsage
getGroupIdLevel1(int subId)4642     public String getGroupIdLevel1(int subId) {
4643         try {
4644             IPhoneSubInfo info = getSubscriberInfoService();
4645             if (info == null)
4646                 return null;
4647             return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
4648                     mContext.getAttributionTag());
4649         } catch (RemoteException ex) {
4650             return null;
4651         } catch (NullPointerException ex) {
4652             // This could happen before phone restarts due to crashing
4653             return null;
4654         }
4655     }
4656 
4657     /**
4658      * Returns the phone number string for line 1, for example, the MSISDN
4659      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4660      * <p>
4661      * The default SMS app can also use this.
4662      *
4663      * <p>Requires Permission:
4664      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4665      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4666      *     that the caller is the default SMS app,
4667      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4668      *     for any API level.
4669      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4670      *     for apps targeting SDK API level 29 and below.
4671      */
4672     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges or default SMS app
4673     @RequiresPermission(anyOf = {
4674             android.Manifest.permission.READ_PHONE_STATE,
4675             android.Manifest.permission.READ_SMS,
4676             android.Manifest.permission.READ_PHONE_NUMBERS
4677     })
getLine1Number()4678     public String getLine1Number() {
4679         return getLine1Number(getSubId());
4680     }
4681 
4682     /**
4683      * Returns the phone number string for line 1, for example, the MSISDN
4684      * for a GSM phone for a particular subscription. Return null if it is unavailable.
4685      * <p>
4686      * The default SMS app can also use this.
4687      *
4688      * <p>Requires Permission:
4689      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4690      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4691      *     that the caller is the default SMS app,
4692      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4693      *     for any API level.
4694      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4695      *     for apps targeting SDK API level 29 and below.
4696      *
4697      * @param subId whose phone number for line 1 is returned
4698      * @hide
4699      */
4700     @RequiresPermission(anyOf = {
4701             android.Manifest.permission.READ_PHONE_STATE,
4702             android.Manifest.permission.READ_SMS,
4703             android.Manifest.permission.READ_PHONE_NUMBERS
4704     })
4705     @UnsupportedAppUsage
getLine1Number(int subId)4706     public String getLine1Number(int subId) {
4707         String number = null;
4708         try {
4709             ITelephony telephony = getITelephony();
4710             if (telephony != null)
4711                 number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
4712                          mContext.getAttributionTag());
4713         } catch (RemoteException ex) {
4714         } catch (NullPointerException ex) {
4715         }
4716         if (number != null) {
4717             return number;
4718         }
4719         try {
4720             IPhoneSubInfo info = getSubscriberInfoService();
4721             if (info == null)
4722                 return null;
4723             return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
4724                     mContext.getAttributionTag());
4725         } catch (RemoteException ex) {
4726             return null;
4727         } catch (NullPointerException ex) {
4728             // This could happen before phone restarts due to crashing
4729             return null;
4730         }
4731     }
4732 
4733     /**
4734      * Set the line 1 phone number string and its alphatag for the current ICCID
4735      * for display purpose only, for example, displayed in Phone Status. It won't
4736      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4737      * value.
4738      *
4739      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4740      *
4741      * @param alphaTag alpha-tagging of the dailing nubmer
4742      * @param number The dialing number
4743      * @return true if the operation was executed correctly.
4744      */
setLine1NumberForDisplay(String alphaTag, String number)4745     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
4746         return setLine1NumberForDisplay(getSubId(), alphaTag, number);
4747     }
4748 
4749     /**
4750      * Set the line 1 phone number string and its alphatag for the current ICCID
4751      * for display purpose only, for example, displayed in Phone Status. It won't
4752      * change the actual MSISDN/MDN. To unset alphatag or number, pass in a null
4753      * value.
4754      *
4755      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4756      *
4757      * @param subId the subscriber that the alphatag and dialing number belongs to.
4758      * @param alphaTag alpha-tagging of the dailing nubmer
4759      * @param number The dialing number
4760      * @return true if the operation was executed correctly.
4761      * @hide
4762      */
setLine1NumberForDisplay(int subId, String alphaTag, String number)4763     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
4764         try {
4765             ITelephony telephony = getITelephony();
4766             if (telephony != null)
4767                 return telephony.setLine1NumberForDisplayForSubscriber(subId, alphaTag, number);
4768         } catch (RemoteException ex) {
4769         } catch (NullPointerException ex) {
4770         }
4771         return false;
4772     }
4773 
4774     /**
4775      * Returns the alphabetic identifier associated with the line 1 number.
4776      * Return null if it is unavailable.
4777      * @hide
4778      * nobody seems to call this.
4779      */
4780     @UnsupportedAppUsage
4781     @TestApi
4782     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getLine1AlphaTag()4783     public String getLine1AlphaTag() {
4784         return getLine1AlphaTag(getSubId());
4785     }
4786 
4787     /**
4788      * Returns the alphabetic identifier associated with the line 1 number
4789      * for a subscription.
4790      * Return null if it is unavailable.
4791      * @param subId whose alphabetic identifier associated with line 1 is returned
4792      * nobody seems to call this.
4793      * @hide
4794      */
4795     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4796     @UnsupportedAppUsage
getLine1AlphaTag(int subId)4797     public String getLine1AlphaTag(int subId) {
4798         String alphaTag = null;
4799         try {
4800             ITelephony telephony = getITelephony();
4801             if (telephony != null)
4802                 alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
4803                         getOpPackageName(), getAttributionTag());
4804         } catch (RemoteException ex) {
4805         } catch (NullPointerException ex) {
4806         }
4807         if (alphaTag != null) {
4808             return alphaTag;
4809         }
4810         try {
4811             IPhoneSubInfo info = getSubscriberInfoService();
4812             if (info == null)
4813                 return null;
4814             return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
4815                     getAttributionTag());
4816         } catch (RemoteException ex) {
4817             return null;
4818         } catch (NullPointerException ex) {
4819             // This could happen before phone restarts due to crashing
4820             return null;
4821         }
4822     }
4823 
4824     /**
4825      * Return the set of subscriber IDs that should be considered "merged together" for data usage
4826      * purposes. This is commonly {@code null} to indicate no merging is required. Any returned
4827      * subscribers are sorted in a deterministic order.
4828      * <p>
4829      * The returned set of subscriber IDs will include the subscriber ID corresponding to this
4830      * TelephonyManager's subId.
4831      *
4832      * This is deprecated and {@link #getMergedImsisFromGroup()} should be used for data
4833      * usage merging purpose.
4834      * TODO: remove this API.
4835      *
4836      * @hide
4837      */
4838     @UnsupportedAppUsage
4839     @Deprecated
getMergedSubscriberIds()4840     public @Nullable String[] getMergedSubscriberIds() {
4841         try {
4842             ITelephony telephony = getITelephony();
4843             if (telephony != null)
4844                 return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
4845                         getAttributionTag());
4846         } catch (RemoteException ex) {
4847         } catch (NullPointerException ex) {
4848         }
4849         return null;
4850     }
4851 
4852     /**
4853      * Return the set of IMSIs that should be considered "merged together" for data usage
4854      * purposes. This API merges IMSIs based on subscription grouping: IMSI of those in the same
4855      * group will all be returned.
4856      * Return the current IMSI if there is no subscription group, see
4857      * {@link SubscriptionManager#createSubscriptionGroup(List)} for the definition of a group,
4858      * otherwise return an empty array if there is a failure.
4859      *
4860      * @hide
4861      */
4862     @SystemApi
4863     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMergedImsisFromGroup()4864     public @NonNull String[] getMergedImsisFromGroup() {
4865         try {
4866             ITelephony telephony = getITelephony();
4867             if (telephony != null) {
4868                 return telephony.getMergedImsisFromGroup(getSubId(), getOpPackageName());
4869             }
4870         } catch (RemoteException ex) {
4871         }
4872         return new String[0];
4873     }
4874 
4875     /**
4876      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4877      *
4878      * <p>Requires Permission:
4879      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4880      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4881      *     that the caller is the default SMS app,
4882      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4883      *     for any API level.
4884      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4885      *     for apps targeting SDK API level 29 and below.
4886      *
4887      * @hide
4888      */
4889     @RequiresPermission(anyOf = {
4890             android.Manifest.permission.READ_PHONE_STATE,
4891             android.Manifest.permission.READ_SMS,
4892             android.Manifest.permission.READ_PHONE_NUMBERS
4893     })
4894     @UnsupportedAppUsage
getMsisdn()4895     public String getMsisdn() {
4896         return getMsisdn(getSubId());
4897     }
4898 
4899     /**
4900      * Returns the MSISDN string for a GSM phone. Return null if it is unavailable.
4901      *
4902      * @param subId for which msisdn is returned
4903      *
4904      * <p>Requires Permission:
4905      *     {@link android.Manifest.permission#READ_SMS READ_SMS},
4906      *     {@link android.Manifest.permission#READ_PHONE_NUMBERS READ_PHONE_NUMBERS},
4907      *     that the caller is the default SMS app,
4908      *     or that the caller has carrier privileges (see {@link #hasCarrierPrivileges})
4909      *     for any API level.
4910      *     {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4911      *     for apps targeting SDK API level 29 and below.
4912      *
4913      * @hide
4914      */
4915     @RequiresPermission(anyOf = {
4916             android.Manifest.permission.READ_PHONE_STATE,
4917             android.Manifest.permission.READ_SMS,
4918             android.Manifest.permission.READ_PHONE_NUMBERS
4919     })
4920     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getMsisdn(int subId)4921     public String getMsisdn(int subId) {
4922         try {
4923             IPhoneSubInfo info = getSubscriberInfoService();
4924             if (info == null)
4925                 return null;
4926             return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
4927         } catch (RemoteException ex) {
4928             return null;
4929         } catch (NullPointerException ex) {
4930             // This could happen before phone restarts due to crashing
4931             return null;
4932         }
4933     }
4934 
4935     /**
4936      * Returns the voice mail number. Return null if it is unavailable.
4937      *
4938      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
4939      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4940      */
4941     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
4942     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailNumber()4943     public String getVoiceMailNumber() {
4944         return getVoiceMailNumber(getSubId());
4945     }
4946 
4947     /**
4948      * Returns the voice mail number for a subscription.
4949      * Return null if it is unavailable.
4950      * @param subId whose voice mail number is returned
4951      * @hide
4952      */
4953     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
4954     @UnsupportedAppUsage
getVoiceMailNumber(int subId)4955     public String getVoiceMailNumber(int subId) {
4956         try {
4957             IPhoneSubInfo info = getSubscriberInfoService();
4958             if (info == null)
4959                 return null;
4960             return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
4961                     getAttributionTag());
4962         } catch (RemoteException ex) {
4963             return null;
4964         } catch (NullPointerException ex) {
4965             // This could happen before phone restarts due to crashing
4966             return null;
4967         }
4968     }
4969 
4970     /**
4971      * Sets the voice mail number.
4972      *
4973      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4974      *
4975      * @param alphaTag The alpha tag to display.
4976      * @param number The voicemail number.
4977      */
setVoiceMailNumber(String alphaTag, String number)4978     public boolean setVoiceMailNumber(String alphaTag, String number) {
4979         return setVoiceMailNumber(getSubId(), alphaTag, number);
4980     }
4981 
4982     /**
4983      * Sets the voicemail number for the given subscriber.
4984      *
4985      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
4986      *
4987      * @param subId The subscription id.
4988      * @param alphaTag The alpha tag to display.
4989      * @param number The voicemail number.
4990      * @hide
4991      */
setVoiceMailNumber(int subId, String alphaTag, String number)4992     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
4993         try {
4994             ITelephony telephony = getITelephony();
4995             if (telephony != null)
4996                 return telephony.setVoiceMailNumber(subId, alphaTag, number);
4997         } catch (RemoteException ex) {
4998         } catch (NullPointerException ex) {
4999         }
5000         return false;
5001     }
5002 
5003     /**
5004      * Enables or disables the visual voicemail client for a phone account.
5005      *
5006      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
5007      * {@link #hasCarrierPrivileges}), or has permission
5008      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
5009      *
5010      * @param phoneAccountHandle the phone account to change the client state
5011      * @param enabled the new state of the client
5012      * @hide
5013      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5014      * be implemented instead.
5015      */
5016     @SystemApi
5017     @SuppressLint("RequiresPermission")
setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)5018     public void setVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled){
5019     }
5020 
5021     /**
5022      * Returns whether the visual voicemail client is enabled.
5023      *
5024      * @param phoneAccountHandle the phone account to check for.
5025      * @return {@code true} when the visual voicemail client is enabled for this client
5026      * @hide
5027      * @deprecated Visual voicemail no longer in telephony. {@link VisualVoicemailService} should
5028      * be implemented instead.
5029      */
5030     @SystemApi
5031     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5032     @SuppressLint("RequiresPermission")
isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle)5033     public boolean isVisualVoicemailEnabled(PhoneAccountHandle phoneAccountHandle){
5034         return false;
5035     }
5036 
5037     /**
5038      * Returns an opaque bundle of settings formerly used by the visual voicemail client for the
5039      * subscription ID pinned to the TelephonyManager, or {@code null} if the subscription ID is
5040      * invalid. This method allows the system dialer to migrate settings out of the pre-O visual
5041      * voicemail client in telephony.
5042      *
5043      * <p>Requires the caller to be the system dialer.
5044      *
5045      * @see #KEY_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL
5046      * @see #KEY_VOICEMAIL_SCRAMBLED_PIN_STRING
5047      *
5048      * @hide
5049      */
5050     @SystemApi
5051     @SuppressLint("RequiresPermission")
5052     @Nullable
getVisualVoicemailSettings()5053     public Bundle getVisualVoicemailSettings(){
5054         try {
5055             ITelephony telephony = getITelephony();
5056             if (telephony != null) {
5057                 return telephony
5058                         .getVisualVoicemailSettings(mContext.getOpPackageName(), mSubId);
5059             }
5060         } catch (RemoteException ex) {
5061         } catch (NullPointerException ex) {
5062         }
5063         return null;
5064     }
5065 
5066     /**
5067      * Returns the package responsible of processing visual voicemail for the subscription ID pinned
5068      * to the TelephonyManager. Returns {@code null} when there is no package responsible for
5069      * processing visual voicemail for the subscription.
5070      *
5071      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5072      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5073      *
5074      * @see #createForSubscriptionId(int)
5075      * @see #createForPhoneAccountHandle(PhoneAccountHandle)
5076      * @see VisualVoicemailService
5077      */
5078     @Nullable
5079     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5080     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVisualVoicemailPackageName()5081     public String getVisualVoicemailPackageName() {
5082         try {
5083             ITelephony telephony = getITelephony();
5084             if (telephony != null) {
5085                 return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
5086                         getAttributionTag(), getSubId());
5087             }
5088         } catch (RemoteException ex) {
5089         } catch (NullPointerException ex) {
5090         }
5091         return null;
5092     }
5093 
5094     /**
5095      * Set the visual voicemail SMS filter settings for the subscription ID pinned
5096      * to the TelephonyManager.
5097      * When the filter is enabled, {@link
5098      * VisualVoicemailService#onSmsReceived(VisualVoicemailTask, VisualVoicemailSms)} will be
5099      * called when a SMS matching the settings is received. Caller must be the default dialer,
5100      * system dialer, or carrier visual voicemail app.
5101      *
5102      * @param settings The settings for the filter, or {@code null} to disable the filter.
5103      *
5104      * @see TelecomManager#getDefaultDialerPackage()
5105      * @see CarrierConfigManager#KEY_CARRIER_VVM_PACKAGE_NAME_STRING_ARRAY
5106      */
setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings)5107     public void setVisualVoicemailSmsFilterSettings(VisualVoicemailSmsFilterSettings settings) {
5108         if (settings == null) {
5109             disableVisualVoicemailSmsFilter(mSubId);
5110         } else {
5111             enableVisualVoicemailSmsFilter(mSubId, settings);
5112         }
5113     }
5114 
5115     /**
5116      * Send a visual voicemail SMS. The caller must be the current default dialer.
5117      * A {@link VisualVoicemailService} uses this method to send a command via SMS to the carrier's
5118      * visual voicemail server.  Some examples for carriers using the OMTP standard include
5119      * activating and deactivating visual voicemail, or requesting the current visual voicemail
5120      * provisioning status.  See the OMTP Visual Voicemail specification for more information on the
5121      * format of these SMS messages.
5122      *
5123      * <p>Requires Permission:
5124      * {@link android.Manifest.permission#SEND_SMS SEND_SMS}
5125      *
5126      * @param number The destination number.
5127      * @param port The destination port for data SMS, or 0 for text SMS.
5128      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5129      * @param sentIntent The sent intent passed to the {@link SmsManager}
5130      *
5131      * @throws SecurityException if the caller is not the current default dialer
5132      *
5133      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5134      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5135      */
sendVisualVoicemailSms(String number, int port, String text, PendingIntent sentIntent)5136     public void sendVisualVoicemailSms(String number, int port, String text,
5137             PendingIntent sentIntent) {
5138         sendVisualVoicemailSmsForSubscriber(mSubId, number, port, text, sentIntent);
5139     }
5140 
5141     /**
5142      * Enables the visual voicemail SMS filter for a phone account. When the filter is
5143      * enabled, Incoming SMS messages matching the OMTP VVM SMS interface will be redirected to the
5144      * visual voicemail client with
5145      * {@link android.provider.VoicemailContract.ACTION_VOICEMAIL_SMS_RECEIVED}.
5146      *
5147      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5148      * settings persist through default dialer changes, but the filter will only honor the setting
5149      * set by the current default dialer.
5150      *
5151      *
5152      * @param subId The subscription id of the phone account.
5153      * @param settings The settings for the filter.
5154      */
5155     /** @hide */
enableVisualVoicemailSmsFilter(int subId, VisualVoicemailSmsFilterSettings settings)5156     public void enableVisualVoicemailSmsFilter(int subId,
5157             VisualVoicemailSmsFilterSettings settings) {
5158         if(settings == null){
5159             throw new IllegalArgumentException("Settings cannot be null");
5160         }
5161         try {
5162             ITelephony telephony = getITelephony();
5163             if (telephony != null) {
5164                 telephony.enableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId,
5165                         settings);
5166             }
5167         } catch (RemoteException ex) {
5168         } catch (NullPointerException ex) {
5169         }
5170     }
5171 
5172     /**
5173      * Disables the visual voicemail SMS filter for a phone account.
5174      *
5175      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5176      * settings persist through default dialer changes, but the filter will only honor the setting
5177      * set by the current default dialer.
5178      */
5179     /** @hide */
disableVisualVoicemailSmsFilter(int subId)5180     public void disableVisualVoicemailSmsFilter(int subId) {
5181         try {
5182             ITelephony telephony = getITelephony();
5183             if (telephony != null) {
5184                 telephony.disableVisualVoicemailSmsFilter(mContext.getOpPackageName(), subId);
5185             }
5186         } catch (RemoteException ex) {
5187         } catch (NullPointerException ex) {
5188         }
5189     }
5190 
5191     /**
5192      * @returns the settings of the visual voicemail SMS filter for a phone account, or {@code null}
5193      * if the filter is disabled.
5194      *
5195      * <p>This takes effect only when the caller is the default dialer. The enabled status and
5196      * settings persist through default dialer changes, but the filter will only honor the setting
5197      * set by the current default dialer.
5198      */
5199     /** @hide */
5200     @Nullable
getVisualVoicemailSmsFilterSettings(int subId)5201     public VisualVoicemailSmsFilterSettings getVisualVoicemailSmsFilterSettings(int subId) {
5202         try {
5203             ITelephony telephony = getITelephony();
5204             if (telephony != null) {
5205                 return telephony
5206                         .getVisualVoicemailSmsFilterSettings(mContext.getOpPackageName(), subId);
5207             }
5208         } catch (RemoteException ex) {
5209         } catch (NullPointerException ex) {
5210         }
5211 
5212         return null;
5213     }
5214 
5215     /**
5216      * @returns the settings of the visual voicemail SMS filter for a phone account set by the
5217      * current active visual voicemail client, or {@code null} if the filter is disabled.
5218      *
5219      * <p>Requires the calling app to have READ_PRIVILEGED_PHONE_STATE permission.
5220      */
5221     /** @hide */
5222     @Nullable
getActiveVisualVoicemailSmsFilterSettings(int subId)5223     public VisualVoicemailSmsFilterSettings getActiveVisualVoicemailSmsFilterSettings(int subId) {
5224         try {
5225             ITelephony telephony = getITelephony();
5226             if (telephony != null) {
5227                 return telephony.getActiveVisualVoicemailSmsFilterSettings(subId);
5228             }
5229         } catch (RemoteException ex) {
5230         } catch (NullPointerException ex) {
5231         }
5232 
5233         return null;
5234     }
5235 
5236     /**
5237      * Send a visual voicemail SMS. The IPC caller must be the current default dialer.
5238      *
5239      * @param phoneAccountHandle The account to send the SMS with.
5240      * @param number The destination number.
5241      * @param port The destination port for data SMS, or 0 for text SMS.
5242      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
5243      * @param sentIntent The sent intent passed to the {@link SmsManager}
5244      *
5245      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
5246      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
5247      *
5248      * @hide
5249      */
5250     @RequiresPermission(android.Manifest.permission.SEND_SMS)
sendVisualVoicemailSmsForSubscriber(int subId, String number, int port, String text, PendingIntent sentIntent)5251     public void sendVisualVoicemailSmsForSubscriber(int subId, String number, int port,
5252             String text, PendingIntent sentIntent) {
5253         try {
5254             ITelephony telephony = getITelephony();
5255             if (telephony != null) {
5256                 telephony.sendVisualVoicemailSmsForSubscriber(
5257                         mContext.getOpPackageName(), mContext.getAttributionTag(), subId, number,
5258                         port, text, sentIntent);
5259             }
5260         } catch (RemoteException ex) {
5261         }
5262     }
5263 
5264     /**
5265      * Initial SIM activation state, unknown. Not set by any carrier apps.
5266      * @hide
5267      */
5268     @SystemApi
5269     public static final int SIM_ACTIVATION_STATE_UNKNOWN = 0;
5270 
5271     /**
5272      * indicate SIM is under activation procedure now.
5273      * intermediate state followed by another state update with activation procedure result:
5274      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5275      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5276      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5277      * @hide
5278      */
5279     @SystemApi
5280     public static final int SIM_ACTIVATION_STATE_ACTIVATING = 1;
5281 
5282     /**
5283      * Indicate SIM has been successfully activated with full service
5284      * @hide
5285      */
5286     @SystemApi
5287     public static final int SIM_ACTIVATION_STATE_ACTIVATED = 2;
5288 
5289     /**
5290      * Indicate SIM has been deactivated by the carrier so that service is not available
5291      * and requires activation service to enable services.
5292      * Carrier apps could be signalled to set activation state to deactivated if detected
5293      * deactivated sim state and set it back to activated after successfully run activation service.
5294      * @hide
5295      */
5296     @SystemApi
5297     public static final int SIM_ACTIVATION_STATE_DEACTIVATED = 3;
5298 
5299     /**
5300      * Restricted state indicate SIM has been activated but service are restricted.
5301      * note this is currently available for data activation state. For example out of byte sim.
5302      * @hide
5303      */
5304     @SystemApi
5305     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
5306 
5307      /**
5308       * Sets the voice activation state
5309       *
5310       * <p>Requires Permission:
5311       * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5312       * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5313       *
5314       * @param activationState The voice activation state
5315       * @see #SIM_ACTIVATION_STATE_UNKNOWN
5316       * @see #SIM_ACTIVATION_STATE_ACTIVATING
5317       * @see #SIM_ACTIVATION_STATE_ACTIVATED
5318       * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5319       * @hide
5320       */
5321     @SystemApi
5322     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(@imActivationState int activationState)5323     public void setVoiceActivationState(@SimActivationState int activationState) {
5324         setVoiceActivationState(getSubId(), activationState);
5325     }
5326 
5327     /**
5328      * Sets the voice activation state for the given subscriber.
5329      *
5330      * <p>Requires Permission:
5331      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5332      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5333      *
5334      * @param subId The subscription id.
5335      * @param activationState The voice activation state of the given subscriber.
5336      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5337      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5338      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5339      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5340      * @hide
5341      */
5342     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setVoiceActivationState(int subId, @SimActivationState int activationState)5343     public void setVoiceActivationState(int subId, @SimActivationState int activationState) {
5344         try {
5345            ITelephony telephony = getITelephony();
5346            if (telephony != null)
5347                telephony.setVoiceActivationState(subId, activationState);
5348        } catch (RemoteException ex) {
5349        } catch (NullPointerException ex) {
5350        }
5351     }
5352 
5353     /**
5354      * Sets the data activation state
5355      *
5356      * <p>Requires Permission:
5357      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5358      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5359      *
5360      * @param activationState The data activation state
5361      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5362      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5363      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5364      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5365      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5366      * @hide
5367      */
5368     @SystemApi
5369     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(@imActivationState int activationState)5370     public void setDataActivationState(@SimActivationState int activationState) {
5371         setDataActivationState(getSubId(), activationState);
5372     }
5373 
5374     /**
5375      * Sets the data activation state for the given subscriber.
5376      *
5377      * <p>Requires Permission:
5378      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
5379      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5380      *
5381      * @param subId The subscription id.
5382      * @param activationState The data activation state of the given subscriber.
5383      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5384      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5385      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5386      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5387      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5388      * @hide
5389      */
5390     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataActivationState(int subId, @SimActivationState int activationState)5391     public void setDataActivationState(int subId, @SimActivationState int activationState) {
5392         try {
5393             ITelephony telephony = getITelephony();
5394             if (telephony != null)
5395                 telephony.setDataActivationState(subId, activationState);
5396         } catch (RemoteException ex) {
5397         } catch (NullPointerException ex) {
5398         }
5399     }
5400 
5401     /**
5402      * Returns the voice activation state
5403      *
5404      * <p>Requires Permission:
5405      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5406      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5407      *
5408      * @return voiceActivationState
5409      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5410      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5411      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5412      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5413      * @hide
5414      */
5415     @SystemApi
5416     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState()5417     public @SimActivationState int getVoiceActivationState() {
5418         return getVoiceActivationState(getSubId());
5419     }
5420 
5421     /**
5422      * Returns the voice activation state for the given subscriber.
5423      *
5424      * <p>Requires Permission:
5425      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5426      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5427      *
5428      * @param subId The subscription id.
5429      *
5430      * @return voiceActivationState for the given subscriber
5431      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5432      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5433      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5434      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5435      * @hide
5436      */
5437     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getVoiceActivationState(int subId)5438     public @SimActivationState int getVoiceActivationState(int subId) {
5439         try {
5440             ITelephony telephony = getITelephony();
5441             if (telephony != null)
5442                 return telephony.getVoiceActivationState(subId, getOpPackageName());
5443         } catch (RemoteException ex) {
5444         } catch (NullPointerException ex) {
5445         }
5446         return SIM_ACTIVATION_STATE_UNKNOWN;
5447     }
5448 
5449     /**
5450      * Returns the data activation state
5451      *
5452      * <p>Requires Permission:
5453      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5454      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5455      *
5456      * @return dataActivationState for the given subscriber
5457      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5458      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5459      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5460      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5461      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5462      * @hide
5463      */
5464     @SystemApi
5465     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState()5466     public @SimActivationState int getDataActivationState() {
5467         return getDataActivationState(getSubId());
5468     }
5469 
5470     /**
5471      * Returns the data activation state for the given subscriber.
5472      *
5473      * <p>Requires Permission:
5474      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5475      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5476      *
5477      * @param subId The subscription id.
5478      *
5479      * @return dataActivationState for the given subscriber
5480      * @see #SIM_ACTIVATION_STATE_UNKNOWN
5481      * @see #SIM_ACTIVATION_STATE_ACTIVATING
5482      * @see #SIM_ACTIVATION_STATE_ACTIVATED
5483      * @see #SIM_ACTIVATION_STATE_DEACTIVATED
5484      * @see #SIM_ACTIVATION_STATE_RESTRICTED
5485      * @hide
5486      */
5487     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getDataActivationState(int subId)5488     public @SimActivationState int getDataActivationState(int subId) {
5489         try {
5490             ITelephony telephony = getITelephony();
5491             if (telephony != null)
5492                 return telephony.getDataActivationState(subId, getOpPackageName());
5493         } catch (RemoteException ex) {
5494         } catch (NullPointerException ex) {
5495         }
5496         return SIM_ACTIVATION_STATE_UNKNOWN;
5497     }
5498 
5499     /**
5500      * Returns the voice mail count. Return 0 if unavailable, -1 if there are unread voice messages
5501      * but the count is unknown.
5502      * @hide
5503      */
5504     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5505     @UnsupportedAppUsage
getVoiceMessageCount()5506     public int getVoiceMessageCount() {
5507         return getVoiceMessageCount(getSubId());
5508     }
5509 
5510     /**
5511      * Returns the voice mail count for a subscription. Return 0 if unavailable or the caller does
5512      * not have the READ_PHONE_STATE permission.
5513      * @param subId whose voice message count is returned
5514      * @hide
5515      */
5516     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5517     @UnsupportedAppUsage
getVoiceMessageCount(int subId)5518     public int getVoiceMessageCount(int subId) {
5519         try {
5520             ITelephony telephony = getITelephony();
5521             if (telephony == null)
5522                 return 0;
5523             return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
5524                     getAttributionTag());
5525         } catch (RemoteException ex) {
5526             return 0;
5527         } catch (NullPointerException ex) {
5528             // This could happen before phone restarts due to crashing
5529             return 0;
5530         }
5531     }
5532 
5533     /**
5534      * Retrieves the alphabetic identifier associated with the voice
5535      * mail number.
5536      *
5537      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
5538      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
5539      */
5540     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
5541     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getVoiceMailAlphaTag()5542     public String getVoiceMailAlphaTag() {
5543         return getVoiceMailAlphaTag(getSubId());
5544     }
5545 
5546     /**
5547      * Retrieves the alphabetic identifier associated with the voice
5548      * mail number for a subscription.
5549      * @param subId whose alphabetic identifier associated with the
5550      * voice mail number is returned
5551      * @hide
5552      */
5553     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
5554     @UnsupportedAppUsage
getVoiceMailAlphaTag(int subId)5555     public String getVoiceMailAlphaTag(int subId) {
5556         try {
5557             IPhoneSubInfo info = getSubscriberInfoService();
5558             if (info == null)
5559                 return null;
5560             return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
5561                     getAttributionTag());
5562         } catch (RemoteException ex) {
5563             return null;
5564         } catch (NullPointerException ex) {
5565             // This could happen before phone restarts due to crashing
5566             return null;
5567         }
5568     }
5569 
5570     /**
5571      * Send the special dialer code. The IPC caller must be the current default dialer or have
5572      * carrier privileges (see {@link #hasCarrierPrivileges}).
5573      *
5574      * @param inputCode The special dialer code to send
5575      *
5576      * @throws SecurityException if the caller does not have carrier privileges or is not the
5577      *         current default dialer
5578      */
sendDialerSpecialCode(String inputCode)5579     public void sendDialerSpecialCode(String inputCode) {
5580         try {
5581             final ITelephony telephony = getITelephony();
5582             if (telephony == null) {
5583                 return;
5584             }
5585             telephony.sendDialerSpecialCode(mContext.getOpPackageName(), inputCode);
5586         } catch (RemoteException ex) {
5587             Rlog.e(TAG, "Telephony#sendDialerSpecialCode RemoteException" + ex);
5588         }
5589     }
5590 
5591     /**
5592      * Returns the IMS private user identity (IMPI) that was loaded from the ISIM.
5593      * @return the IMPI, or null if not present or not loaded
5594      * @hide
5595      */
5596     @UnsupportedAppUsage
getIsimImpi()5597     public String getIsimImpi() {
5598         try {
5599             IPhoneSubInfo info = getSubscriberInfoService();
5600             if (info == null)
5601                 return null;
5602             //get the Isim Impi based on subId
5603             return info.getIsimImpi(getSubId());
5604         } catch (RemoteException ex) {
5605             return null;
5606         } catch (NullPointerException ex) {
5607             // This could happen before phone restarts due to crashing
5608             return null;
5609         }
5610     }
5611 
5612     /**
5613      * Returns the IMS home network domain name that was loaded from the ISIM {@see #APPTYPE_ISIM}.
5614      * @return the IMS domain name. Returns {@code null} if ISIM hasn't been loaded or IMS domain
5615      * hasn't been loaded or isn't present on the ISIM.
5616      *
5617      * <p>Requires Permission:
5618      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
5619      * @hide
5620      */
5621     @Nullable
5622     @SystemApi
5623     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimDomain()5624     public String getIsimDomain() {
5625         try {
5626             IPhoneSubInfo info = getSubscriberInfoService();
5627             if (info == null)
5628                 return null;
5629             //get the Isim Domain based on subId
5630             return info.getIsimDomain(getSubId());
5631         } catch (RemoteException ex) {
5632             return null;
5633         } catch (NullPointerException ex) {
5634             // This could happen before phone restarts due to crashing
5635             return null;
5636         }
5637     }
5638 
5639     /**
5640      * Returns the IMS public user identities (IMPU) that were loaded from the ISIM.
5641      * @return an array of IMPU strings, with one IMPU per string, or null if
5642      *      not present or not loaded
5643      * @hide
5644      */
5645     @UnsupportedAppUsage
5646     @Nullable
5647     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimImpu()5648     public String[] getIsimImpu() {
5649         try {
5650             IPhoneSubInfo info = getSubscriberInfoService();
5651             if (info == null)
5652                 return null;
5653             //get the Isim Impu based on subId
5654             return info.getIsimImpu(getSubId());
5655         } catch (RemoteException ex) {
5656             return null;
5657         } catch (NullPointerException ex) {
5658             // This could happen before phone restarts due to crashing
5659             return null;
5660         }
5661     }
5662 
5663     /**
5664      * Device call state: No activity.
5665      */
5666     public static final int CALL_STATE_IDLE = 0;
5667     /**
5668      * Device call state: Ringing. A new call arrived and is
5669      *  ringing or waiting. In the latter case, another call is
5670      *  already active.
5671      */
5672     public static final int CALL_STATE_RINGING = 1;
5673     /**
5674      * Device call state: Off-hook. At least one call exists
5675      * that is dialing, active, or on hold, and no calls are ringing
5676      * or waiting.
5677      */
5678     public static final int CALL_STATE_OFFHOOK = 2;
5679 
5680     /**
5681      * Returns the state of all calls on the device.
5682      * <p>
5683      * This method considers not only calls in the Telephony stack, but also calls via other
5684      * {@link android.telecom.ConnectionService} implementations.
5685      * <p>
5686      * Note: The call state returned via this method may differ from what is reported by
5687      * {@link PhoneStateListener#onCallStateChanged(int, String)}, as that callback only considers
5688      * Telephony (mobile) calls.
5689      * <p>
5690      * Requires Permission:
5691      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
5692      * targeting API level 31+.
5693      *
5694      * @return the current call state.
5695      * @deprecated Use {@link #getCallStateForSubscription} to retrieve the call state for a
5696      * specific telephony subscription (which allows carrier privileged apps),
5697      * {@link TelephonyCallback.CallStateListener} for real-time call state updates, or
5698      * {@link TelecomManager#isInCall()}, which supplies an aggregate "in call" state for the entire
5699      * device.
5700      */
5701     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
5702     @Deprecated
getCallState()5703     public @CallState int getCallState() {
5704         if (mContext != null) {
5705             TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
5706             if (telecomManager != null) {
5707                 return telecomManager.getCallState();
5708             }
5709         }
5710         return CALL_STATE_IDLE;
5711     }
5712 
5713     /**
5714      * Retrieve the call state for a specific subscription that was specified when this
5715      * TelephonyManager instance was created.
5716      * <p>Requires Permission:
5717      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the calling
5718      * application has carrier privileges (see {@link #hasCarrierPrivileges}).
5719      * @see TelephonyManager#createForSubscriptionId(int)
5720      * @see TelephonyManager#createForPhoneAccountHandle(PhoneAccountHandle)
5721      * @return The call state of the subscription associated with this TelephonyManager instance.
5722      */
5723     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCallStateForSubscription()5724     public @CallState int getCallStateForSubscription() {
5725         return getCallState(getSubId());
5726     }
5727 
5728     /**
5729      * Returns the Telephony call state for calls on a specific subscription.
5730      * <p>
5731      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5732      * considers the state of calls from other {@link android.telecom.ConnectionService}
5733      * implementations.
5734      * <p>
5735      * Requires Permission:
5736      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
5737      * targeting API level 31+ or that the calling application has carrier privileges
5738      * (see {@link #hasCarrierPrivileges()}).
5739      *
5740      * @param subId the subscription to check call state for.
5741      * @hide
5742      */
5743     @UnsupportedAppUsage
5744     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
getCallState(int subId)5745     public @CallState int getCallState(int subId) {
5746         ITelephony telephony = getITelephony();
5747         if (telephony == null) {
5748             return CALL_STATE_IDLE;
5749         }
5750         try {
5751             return telephony.getCallStateForSubscription(subId, mContext.getPackageName(),
5752                     mContext.getAttributionTag());
5753         } catch (RemoteException e) {
5754             return CALL_STATE_IDLE;
5755         }
5756     }
5757 
5758     /**
5759     * @hide
5760     */
5761     @UnsupportedAppUsage
getSubscriberInfo()5762     private IPhoneSubInfo getSubscriberInfo() {
5763         return getSubscriberInfoService();
5764     }
5765 
5766     /**
5767      * Returns the Telephony call state for calls on a specific SIM slot.
5768      * <p>
5769      * Note: This method considers ONLY telephony/mobile calls, where {@link #getCallState()}
5770      * considers the state of calls from other {@link android.telecom.ConnectionService}
5771      * implementations.
5772      * <p>
5773      * Requires Permission:
5774      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} for applications
5775      * targeting API level 31+ or that the calling application has carrier privileges
5776      * (see {@link #hasCarrierPrivileges()}).
5777      *
5778      * @param slotIndex the SIM slot index to check call state for.
5779      * @hide
5780      */
5781     @RequiresPermission(value = android.Manifest.permission.READ_PHONE_STATE, conditional = true)
getCallStateForSlot(int slotIndex)5782     public @CallState int getCallStateForSlot(int slotIndex) {
5783         try {
5784             int[] subId = SubscriptionManager.getSubId(slotIndex);
5785             ITelephony telephony = getITelephony();
5786             if (telephony == null || subId == null || subId.length  == 0) {
5787                 return CALL_STATE_IDLE;
5788             }
5789             return telephony.getCallStateForSubscription(subId[0], mContext.getPackageName(),
5790                     mContext.getAttributionTag());
5791         } catch (RemoteException | NullPointerException ex) {
5792             // the phone process is restarting.
5793             return CALL_STATE_IDLE;
5794         }
5795     }
5796 
5797 
5798     /** Data connection activity: No traffic. */
5799     public static final int DATA_ACTIVITY_NONE = 0x00000000;
5800     /** Data connection activity: Currently receiving IP PPP traffic. */
5801     public static final int DATA_ACTIVITY_IN = 0x00000001;
5802     /** Data connection activity: Currently sending IP PPP traffic. */
5803     public static final int DATA_ACTIVITY_OUT = 0x00000002;
5804     /** Data connection activity: Currently both sending and receiving
5805      *  IP PPP traffic. */
5806     public static final int DATA_ACTIVITY_INOUT = DATA_ACTIVITY_IN | DATA_ACTIVITY_OUT;
5807     /**
5808      * Data connection is active, but physical link is down
5809      */
5810     public static final int DATA_ACTIVITY_DORMANT = 0x00000004;
5811 
5812     /**
5813      * Returns a constant indicating the type of activity on a data connection
5814      * (cellular).
5815      *
5816      * @see #DATA_ACTIVITY_NONE
5817      * @see #DATA_ACTIVITY_IN
5818      * @see #DATA_ACTIVITY_OUT
5819      * @see #DATA_ACTIVITY_INOUT
5820      * @see #DATA_ACTIVITY_DORMANT
5821      */
getDataActivity()5822     public int getDataActivity() {
5823         try {
5824             ITelephony telephony = getITelephony();
5825             if (telephony == null)
5826                 return DATA_ACTIVITY_NONE;
5827             return telephony.getDataActivityForSubId(
5828                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5829         } catch (RemoteException ex) {
5830             // the phone process is restarting.
5831             return DATA_ACTIVITY_NONE;
5832         } catch (NullPointerException ex) {
5833           // the phone process is restarting.
5834           return DATA_ACTIVITY_NONE;
5835       }
5836     }
5837 
5838     /** @hide */
5839     @IntDef(prefix = {"DATA_"}, value = {
5840             DATA_UNKNOWN,
5841             DATA_DISCONNECTED,
5842             DATA_CONNECTING,
5843             DATA_CONNECTED,
5844             DATA_SUSPENDED,
5845             DATA_DISCONNECTING,
5846     })
5847     @Retention(RetentionPolicy.SOURCE)
5848     public @interface DataState{}
5849 
5850     /** Data connection state: Unknown.  Used before we know the state. */
5851     public static final int DATA_UNKNOWN        = -1;
5852     /** Data connection state: Disconnected. IP traffic not available. */
5853     public static final int DATA_DISCONNECTED   = 0;
5854     /** Data connection state: Currently setting up a data connection. */
5855     public static final int DATA_CONNECTING     = 1;
5856     /** Data connection state: Connected. IP traffic should be available. */
5857     public static final int DATA_CONNECTED      = 2;
5858     /** Data connection state: Suspended. The connection is up, but IP
5859      * traffic is temporarily unavailable. For example, in a 2G network,
5860      * data activity may be suspended when a voice call arrives. */
5861     public static final int DATA_SUSPENDED      = 3;
5862     /**
5863      * Data connection state: Disconnecting.
5864      *
5865      * IP traffic may be available but will cease working imminently.
5866      */
5867     public static final int DATA_DISCONNECTING = 4;
5868 
5869     /**
5870      * Used for checking if the SDK version for {@link TelephonyManager#getDataState} is above Q.
5871      */
5872     @ChangeId
5873     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
5874     private static final long GET_DATA_STATE_R_VERSION = 148534348L;
5875 
5876     /**
5877      * Returns a constant indicating the current data connection state
5878      * (cellular).
5879      *
5880      * @see #DATA_DISCONNECTED
5881      * @see #DATA_CONNECTING
5882      * @see #DATA_CONNECTED
5883      * @see #DATA_SUSPENDED
5884      * @see #DATA_DISCONNECTING
5885      */
getDataState()5886     public int getDataState() {
5887         try {
5888             ITelephony telephony = getITelephony();
5889             if (telephony == null)
5890                 return DATA_DISCONNECTED;
5891             int state = telephony.getDataStateForSubId(
5892                     getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
5893             if (state == TelephonyManager.DATA_DISCONNECTING
5894                     && !Compatibility.isChangeEnabled(GET_DATA_STATE_R_VERSION)) {
5895                 return TelephonyManager.DATA_CONNECTED;
5896             }
5897 
5898             return state;
5899         } catch (RemoteException ex) {
5900             // the phone process is restarting.
5901             return DATA_DISCONNECTED;
5902         } catch (NullPointerException ex) {
5903             return DATA_DISCONNECTED;
5904         }
5905     }
5906 
5907     /**
5908      * @hide
5909      */
5910     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getITelephony()5911     private ITelephony getITelephony() {
5912         // Keeps cache disabled until test fixes are checked into AOSP.
5913         if (!sServiceHandleCacheEnabled) {
5914             return ITelephony.Stub.asInterface(
5915                     TelephonyFrameworkInitializer
5916                             .getTelephonyServiceManager()
5917                             .getTelephonyServiceRegisterer()
5918                             .get());
5919         }
5920 
5921         if (sITelephony == null) {
5922             ITelephony temp = ITelephony.Stub.asInterface(
5923                     TelephonyFrameworkInitializer
5924                             .getTelephonyServiceManager()
5925                             .getTelephonyServiceRegisterer()
5926                             .get());
5927             synchronized (sCacheLock) {
5928                 if (sITelephony == null && temp != null) {
5929                     try {
5930                         sITelephony = temp;
5931                         sITelephony.asBinder().linkToDeath(sServiceDeath, 0);
5932                     } catch (Exception e) {
5933                         // something has gone horribly wrong
5934                         sITelephony = null;
5935                     }
5936                 }
5937             }
5938         }
5939         return sITelephony;
5940     }
5941 
getIOns()5942     private IOns getIOns() {
5943         return IOns.Stub.asInterface(
5944                 TelephonyFrameworkInitializer
5945                         .getTelephonyServiceManager()
5946                         .getOpportunisticNetworkServiceRegisterer()
5947                         .get());
5948     }
5949 
5950     //
5951     //
5952     // PhoneStateListener
5953     //
5954     //
5955 
5956     /**
5957      * Registers a listener object to receive notification of changes
5958      * in specified telephony states.
5959      * <p>
5960      * To register a listener, pass a {@link PhoneStateListener} and specify at least one telephony
5961      * state of interest in the events argument.
5962      *
5963      * At registration, and when a specified telephony state changes, the telephony manager invokes
5964      * the appropriate callback method on the listener object and passes the current (updated)
5965      * values.
5966      * <p>
5967      * To un-register a listener, pass the listener object and set the events argument to
5968      * {@link PhoneStateListener#LISTEN_NONE LISTEN_NONE} (0).
5969      *
5970      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
5971      * applies to the given subId. Otherwise, applies to
5972      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To listen events for multiple subIds,
5973      * pass a separate listener object to each TelephonyManager object created with
5974      * {@link #createForSubscriptionId}.
5975      *
5976      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
5977      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
5978      * {@link SecurityException} will be thrown otherwise.
5979      *
5980      * This API should be used sparingly -- large numbers of listeners will cause system
5981      * instability. If a process has registered too many listeners without unregistering them, it
5982      * may encounter an {@link IllegalStateException} when trying to register more listeners.
5983      *
5984      * @param listener The {@link PhoneStateListener} object to register
5985      *                 (or unregister)
5986      * @param events The telephony state(s) of interest to the listener,
5987      *               as a bitwise-OR combination of {@link PhoneStateListener}
5988      *               LISTEN_ flags.
5989      * @deprecated Use {@link #registerTelephonyCallback(Executor, TelephonyCallback)}.
5990      */
5991     @Deprecated
listen(PhoneStateListener listener, int events)5992     public void listen(PhoneStateListener listener, int events) {
5993         if (mContext == null) return;
5994         boolean notifyNow = (getITelephony() != null);
5995         TelephonyRegistryManager telephonyRegistry =
5996                 (TelephonyRegistryManager)
5997                         mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
5998         if (telephonyRegistry != null) {
5999             telephonyRegistry.listenFromListener(mSubId, getOpPackageName(),
6000                     getAttributionTag(), listener, events, notifyNow);
6001         } else {
6002             Rlog.w(TAG, "telephony registry not ready.");
6003         }
6004     }
6005 
6006     /** @hide */
6007     @Retention(RetentionPolicy.SOURCE)
6008     @IntDef(prefix = {"ERI_"}, value = {
6009             ERI_ON,
6010             ERI_OFF,
6011             ERI_FLASH
6012     })
6013     public @interface EriIconIndex {}
6014 
6015     /**
6016      * ERI (Enhanced Roaming Indicator) is ON i.e value 0 defined by
6017      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6018      */
6019     public static final int ERI_ON = 0;
6020 
6021     /**
6022      * ERI (Enhanced Roaming Indicator) is OFF i.e value 1 defined by
6023      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6024      */
6025     public static final int ERI_OFF = 1;
6026 
6027     /**
6028      * ERI (Enhanced Roaming Indicator) is FLASH i.e value 2 defined by
6029      * 3GPP2 C.R1001-H v1.0 Table 8.1-1.
6030      */
6031     public static final int ERI_FLASH = 2;
6032 
6033     /** @hide */
6034     @Retention(RetentionPolicy.SOURCE)
6035     @IntDef(prefix = {"ERI_ICON_MODE_"}, value = {
6036             ERI_ICON_MODE_NORMAL,
6037             ERI_ICON_MODE_FLASH
6038     })
6039     public @interface EriIconMode {}
6040 
6041     /**
6042      * ERI (Enhanced Roaming Indicator) icon mode is normal. This constant represents that
6043      * the ERI icon should be displayed normally.
6044      *
6045      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6046      * @hide
6047      */
6048     public static final int ERI_ICON_MODE_NORMAL = 0;
6049 
6050     /**
6051      * ERI (Enhanced Roaming Indicator) icon mode flash. This constant represents that
6052      * the ERI icon should be flashing.
6053      *
6054      * Note: ERI is defined 3GPP2 C.R1001-H Table 8.1-1
6055      * @hide
6056      */
6057     public static final int ERI_ICON_MODE_FLASH = 1;
6058 
6059     /**
6060      * Returns the CDMA ERI icon display number. The number is assigned by
6061      * 3GPP2 C.R1001-H v1.0 Table 8.1-1. Additionally carriers define their own ERI display numbers.
6062      * Defined values are {@link #ERI_ON}, {@link #ERI_OFF}, and {@link #ERI_FLASH}.
6063      * @hide
6064      */
6065     @SystemApi
6066     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaEnhancedRoamingIndicatorDisplayNumber()6067     public @EriIconIndex int getCdmaEnhancedRoamingIndicatorDisplayNumber() {
6068         return getCdmaEriIconIndex(getSubId());
6069     }
6070 
6071     /**
6072      * Returns the CDMA ERI icon index to display for a subscription.
6073      * @hide
6074      */
6075     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6076     @UnsupportedAppUsage
getCdmaEriIconIndex(int subId)6077     public @EriIconIndex int getCdmaEriIconIndex(int subId) {
6078         try {
6079             ITelephony telephony = getITelephony();
6080             if (telephony == null)
6081                 return -1;
6082             return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
6083                     getAttributionTag());
6084         } catch (RemoteException ex) {
6085             // the phone process is restarting.
6086             return -1;
6087         } catch (NullPointerException ex) {
6088             return -1;
6089         }
6090     }
6091 
6092     /**
6093      * Returns the CDMA ERI icon mode for a subscription.
6094      * 0 - ON
6095      * 1 - FLASHING
6096      *
6097      * @hide
6098      */
6099     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
6100     @UnsupportedAppUsage
getCdmaEriIconMode(int subId)6101     public @EriIconMode int getCdmaEriIconMode(int subId) {
6102         try {
6103             ITelephony telephony = getITelephony();
6104             if (telephony == null)
6105                 return -1;
6106             return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
6107                     getAttributionTag());
6108         } catch (RemoteException ex) {
6109             // the phone process is restarting.
6110             return -1;
6111         } catch (NullPointerException ex) {
6112             return -1;
6113         }
6114     }
6115 
6116     /**
6117      * Returns the CDMA ERI text,
6118      *
6119      * @hide
6120      */
6121     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getCdmaEriText()6122     public String getCdmaEriText() {
6123         return getCdmaEriText(getSubId());
6124     }
6125 
6126     /**
6127      * Returns the CDMA ERI text, of a subscription
6128      *
6129      * @hide
6130      */
6131     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
6132     @UnsupportedAppUsage
getCdmaEriText(int subId)6133     public String getCdmaEriText(int subId) {
6134         try {
6135             ITelephony telephony = getITelephony();
6136             if (telephony == null)
6137                 return null;
6138             return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
6139                     getAttributionTag());
6140         } catch (RemoteException ex) {
6141             // the phone process is restarting.
6142             return null;
6143         } catch (NullPointerException ex) {
6144             return null;
6145         }
6146     }
6147 
6148     /**
6149      * @return true if the current device is "voice capable".
6150      * <p>
6151      * "Voice capable" means that this device supports circuit-switched
6152      * (i.e. voice) phone calls over the telephony network, and is allowed
6153      * to display the in-call UI while a cellular voice call is active.
6154      * This will be false on "data only" devices which can't make voice
6155      * calls and don't support any in-call UI.
6156      * <p>
6157      * Note: the meaning of this flag is subtly different from the
6158      * PackageManager.FEATURE_TELEPHONY system feature, which is available
6159      * on any device with a telephony radio, even if the device is
6160      * data-only.
6161      */
isVoiceCapable()6162     public boolean isVoiceCapable() {
6163         if (mContext == null) return true;
6164         return mContext.getResources().getBoolean(
6165                 com.android.internal.R.bool.config_voice_capable);
6166     }
6167 
6168     /**
6169      * @return true if the current device supports sms service.
6170      * <p>
6171      * If true, this means that the device supports both sending and
6172      * receiving sms via the telephony network.
6173      * <p>
6174      * Note: Voicemail waiting sms, cell broadcasting sms, and MMS are
6175      *       disabled when device doesn't support sms.
6176      */
isSmsCapable()6177     public boolean isSmsCapable() {
6178         if (mContext == null) return true;
6179         return mContext.getResources().getBoolean(
6180                 com.android.internal.R.bool.config_sms_capable);
6181     }
6182 
6183     /**
6184      * Requests all available cell information from all radios on the device including the
6185      * camped/registered, serving, and neighboring cells.
6186      *
6187      * <p>The response can include one or more {@link android.telephony.CellInfoGsm CellInfoGsm},
6188      * {@link android.telephony.CellInfoCdma CellInfoCdma},
6189      * {@link android.telephony.CellInfoTdscdma CellInfoTdscdma},
6190      * {@link android.telephony.CellInfoLte CellInfoLte}, and
6191      * {@link android.telephony.CellInfoWcdma CellInfoWcdma} objects, in any combination.
6192      * It is typical to see instances of one or more of any these in the list. In addition, zero
6193      * or more of the returned objects may be considered registered; that is, their
6194      * {@link android.telephony.CellInfo#isRegistered CellInfo.isRegistered()}
6195      * methods may return true, indicating that the cell is being used or would be used for
6196      * signaling communication if necessary.
6197      *
6198      * <p>Beginning with {@link android.os.Build.VERSION_CODES#Q Android Q},
6199      * if this API results in a change of the cached CellInfo, that change will be reported via
6200      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}.
6201      *
6202      * <p>Apps targeting {@link android.os.Build.VERSION_CODES#Q Android Q} or higher will no
6203      * longer trigger a refresh of the cached CellInfo by invoking this API. Instead, those apps
6204      * will receive the latest cached results, which may not be current. Apps targeting
6205      * {@link android.os.Build.VERSION_CODES#Q Android Q} or higher that wish to request updated
6206      * CellInfo should call
6207      * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()};
6208      * however, in all cases, updates will be rate-limited and are not guaranteed. To determine the
6209      * recency of CellInfo data, callers should check
6210      * {@link android.telephony.CellInfo#getTimeStamp CellInfo#getTimeStamp()}.
6211      *
6212      * <p>This method returns valid data for devices with
6213      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. In cases
6214      * where only partial information is available for a particular CellInfo entry, unavailable
6215      * fields will be reported as {@link android.telephony.CellInfo#UNAVAILABLE}. All reported
6216      * cells will include at least a valid set of technology-specific identification info and a
6217      * power level measurement.
6218      *
6219      * <p>This method is preferred over using {@link
6220      * android.telephony.TelephonyManager#getCellLocation getCellLocation()}.
6221      *
6222      * @return List of {@link android.telephony.CellInfo}; null if cell
6223      * information is unavailable.
6224      */
6225     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
getAllCellInfo()6226     public List<CellInfo> getAllCellInfo() {
6227         try {
6228             ITelephony telephony = getITelephony();
6229             if (telephony == null)
6230                 return null;
6231             return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
6232         } catch (RemoteException ex) {
6233         } catch (NullPointerException ex) {
6234         }
6235         return null;
6236     }
6237 
6238     /** Callback for providing asynchronous {@link CellInfo} on request */
6239     public abstract static class CellInfoCallback {
6240         /**
6241          * Success response to
6242          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
6243          *
6244          * Invoked when there is a response to
6245          * {@link android.telephony.TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}
6246          * to provide a list of {@link CellInfo}. If no {@link CellInfo} is available then an empty
6247          * list will be provided. If an error occurs, null will be provided unless the onError
6248          * callback is overridden.
6249          *
6250          * @param cellInfo a list of {@link CellInfo}, an empty list, or null.
6251          *
6252          * {@see android.telephony.TelephonyManager#getAllCellInfo getAllCellInfo()}
6253          */
onCellInfo(@onNull List<CellInfo> cellInfo)6254         public abstract void onCellInfo(@NonNull List<CellInfo> cellInfo);
6255 
6256         /** @hide */
6257         @Retention(RetentionPolicy.SOURCE)
6258         @IntDef(prefix = {"ERROR_"}, value = {ERROR_TIMEOUT, ERROR_MODEM_ERROR})
6259         public @interface CellInfoCallbackError {}
6260 
6261         /**
6262          * The system timed out waiting for a response from the Radio.
6263          */
6264         public static final int ERROR_TIMEOUT = 1;
6265 
6266         /**
6267          * The modem returned a failure.
6268          */
6269         public static final int ERROR_MODEM_ERROR = 2;
6270 
6271         /**
6272          * Error response to
6273          * {@link TelephonyManager#requestCellInfoUpdate requestCellInfoUpdate()}.
6274          *
6275          * Invoked when an error condition prevents updated {@link CellInfo} from being fetched
6276          * and returned from the modem. Callers of requestCellInfoUpdate() should override this
6277          * function to receive detailed status information in the event of an error. By default,
6278          * this function will invoke onCellInfo() with null.
6279          *
6280          * @param errorCode an error code indicating the type of failure.
6281          * @param detail a Throwable object with additional detail regarding the failure if
6282          *     available, otherwise null.
6283          */
onError(@ellInfoCallbackError int errorCode, @Nullable Throwable detail)6284         public void onError(@CellInfoCallbackError int errorCode, @Nullable Throwable detail) {
6285             // By default, simply invoke the success callback with an empty list.
6286             onCellInfo(new ArrayList<CellInfo>());
6287         }
6288     };
6289 
6290     /**
6291      * Used for checking if the target SDK version for the current process is S or above.
6292      *
6293      * <p> Applies to the following methods:
6294      * {@link #requestCellInfoUpdate},
6295      * {@link #setPreferredOpportunisticDataSubscription},
6296      * {@link #updateAvailableNetworks},
6297      * requestNumberVerification(),
6298      * setSimPowerStateForSlot(),
6299      */
6300     @ChangeId
6301     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.R)
6302     private static final long NULL_TELEPHONY_THROW_NO_CB = 182185642L;
6303 
6304     /**
6305      * Requests all available cell information from the current subscription for observed
6306      * camped/registered, serving, and neighboring cells.
6307      *
6308      * <p>Any available results from this request will be provided by calls to
6309      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
6310      * for each active subscription.
6311      *
6312      * <p>This method returns valid data for devices with
6313      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
6314      * that do not implement this feature, the behavior is not reliable.
6315      *
6316      * @param executor the executor on which callback will be invoked.
6317      * @param callback a callback to receive CellInfo.
6318      */
6319     @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
requestCellInfoUpdate( @onNull @allbackExecutor Executor executor, @NonNull CellInfoCallback callback)6320     public void requestCellInfoUpdate(
6321             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
6322         try {
6323             ITelephony telephony = getITelephony();
6324             if (telephony == null) {
6325                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
6326                     throw new IllegalStateException("Telephony is null");
6327                 } else {
6328                     return;
6329                 }
6330             }
6331 
6332             telephony.requestCellInfoUpdate(
6333                     getSubId(),
6334                     new ICellInfoCallback.Stub() {
6335                         @Override
6336                         public void onCellInfo(List<CellInfo> cellInfo) {
6337                             final long identity = Binder.clearCallingIdentity();
6338                             try {
6339                                 executor.execute(() -> callback.onCellInfo(cellInfo));
6340                             } finally {
6341                                 Binder.restoreCallingIdentity(identity);
6342                             }
6343                         }
6344 
6345                         @Override
6346                         public void onError(int errorCode, String exceptionName, String message) {
6347                             final long identity = Binder.clearCallingIdentity();
6348                             try {
6349                                 executor.execute(() -> callback.onError(
6350                                         errorCode,
6351                                         createThrowableByClassName(exceptionName, message)));
6352                             } finally {
6353                                 Binder.restoreCallingIdentity(identity);
6354                             }
6355                         }
6356                     }, getOpPackageName(), getAttributionTag());
6357         } catch (RemoteException ex) {
6358             runOnBackgroundThread(() -> executor.execute(
6359                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
6360         }
6361     }
6362 
6363     /**
6364      * Requests all available cell information from the current subscription for observed
6365      * camped/registered, serving, and neighboring cells.
6366      *
6367      * <p>Any available results from this request will be provided by calls to
6368      * {@link android.telephony.PhoneStateListener#onCellInfoChanged onCellInfoChanged()}
6369      * for each active subscription.
6370      *
6371      * <p>This method returns valid data for devices with
6372      * {@link android.content.pm.PackageManager#FEATURE_TELEPHONY FEATURE_TELEPHONY}. On devices
6373      * that do not implement this feature, the behavior is not reliable.
6374      *
6375      * @param workSource the requestor to whom the power consumption for this should be attributed.
6376      * @param executor the executor on which callback will be invoked.
6377      * @param callback a callback to receive CellInfo.
6378      * @hide
6379      */
6380     @SystemApi
6381     @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
6382             android.Manifest.permission.MODIFY_PHONE_STATE})
requestCellInfoUpdate(@onNull WorkSource workSource, @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback)6383     public void requestCellInfoUpdate(@NonNull WorkSource workSource,
6384             @NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
6385         try {
6386             ITelephony telephony = getITelephony();
6387             if (telephony == null) {
6388                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
6389                     throw new IllegalStateException("Telephony is null");
6390                 } else {
6391                     return;
6392                 }
6393             }
6394 
6395             telephony.requestCellInfoUpdateWithWorkSource(
6396                     getSubId(),
6397                     new ICellInfoCallback.Stub() {
6398                         @Override
6399                         public void onCellInfo(List<CellInfo> cellInfo) {
6400                             final long identity = Binder.clearCallingIdentity();
6401                             try {
6402                                 executor.execute(() -> callback.onCellInfo(cellInfo));
6403                             } finally {
6404                                 Binder.restoreCallingIdentity(identity);
6405                             }
6406 
6407                         }
6408 
6409                         @Override
6410                         public void onError(int errorCode, String exceptionName, String message) {
6411                             final long identity = Binder.clearCallingIdentity();
6412                             try {
6413                                 executor.execute(() -> callback.onError(
6414                                         errorCode,
6415                                         createThrowableByClassName(exceptionName, message)));
6416                             } finally {
6417                                 Binder.restoreCallingIdentity(identity);
6418                             }
6419                         }
6420                     }, getOpPackageName(), getAttributionTag(), workSource);
6421         } catch (RemoteException ex) {
6422             runOnBackgroundThread(() -> executor.execute(
6423                     () -> callback.onError(CellInfoCallback.ERROR_MODEM_ERROR, ex)));
6424         }
6425     }
6426 
createThrowableByClassName(String className, String message)6427     private static Throwable createThrowableByClassName(String className, String message) {
6428         if (className == null) {
6429             return null;
6430         }
6431         try {
6432             Class<?> c = Class.forName(className);
6433             return (Throwable) c.getConstructor(String.class).newInstance(message);
6434         } catch (ReflectiveOperationException | ClassCastException e) {
6435         }
6436         return new RuntimeException(className + ": " + message);
6437     }
6438 
6439     /**
6440      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
6441      * PhoneStateListener.onCellInfoChanged} will be invoked.
6442      *<p>
6443      * The default, 0, means invoke onCellInfoChanged when any of the reported
6444      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
6445      * A onCellInfoChanged.
6446      *<p>
6447      * @param rateInMillis the rate
6448      *
6449      * @hide
6450      */
setCellInfoListRate(int rateInMillis)6451     public void setCellInfoListRate(int rateInMillis) {
6452         try {
6453             ITelephony telephony = getITelephony();
6454             if (telephony != null)
6455                 telephony.setCellInfoListRate(rateInMillis);
6456         } catch (RemoteException ex) {
6457         } catch (NullPointerException ex) {
6458         }
6459     }
6460 
6461     /**
6462      * Returns the MMS user agent.
6463      */
getMmsUserAgent()6464     public String getMmsUserAgent() {
6465         try {
6466             ITelephony telephony = getITelephony();
6467             if (telephony != null) {
6468                 return telephony.getMmsUserAgent(getSubId());
6469             }
6470         } catch (RemoteException ex) {
6471         } catch (NullPointerException ex) {
6472         }
6473         return null;
6474     }
6475 
6476     /**
6477      * Returns the MMS user agent profile URL.
6478      */
getMmsUAProfUrl()6479     public String getMmsUAProfUrl() {
6480         try {
6481             ITelephony telephony = getITelephony();
6482             if (telephony != null) {
6483                 return telephony.getMmsUAProfUrl(getSubId());
6484             }
6485         } catch (RemoteException ex) {
6486         } catch (NullPointerException ex) {
6487         }
6488         return null;
6489     }
6490 
6491     /**
6492      * Opens a logical channel to the ICC card.
6493      *
6494      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6495      *
6496      * <p>Requires Permission:
6497      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6498      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6499      *
6500      * @param AID Application id. See ETSI 102.221 and 101.220.
6501      * @return an IccOpenLogicalChannelResponse object.
6502      * @deprecated Replaced by {@link #iccOpenLogicalChannel(String, int)}
6503      */
6504     @Deprecated
iccOpenLogicalChannel(String AID)6505     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
6506         return iccOpenLogicalChannel(getSubId(), AID, -1);
6507     }
6508 
6509     /**
6510      * Opens a logical channel to the ICC card using the physical slot index.
6511      *
6512      * Use this method when no subscriptions are available on the SIM and the operation must be
6513      * performed using the physical slot index.
6514      *
6515      * This operation wraps two APDU instructions:
6516      * <ul>
6517      *     <li>MANAGE CHANNEL to open a logical channel</li>
6518      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6519      * </ul>
6520      *
6521      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6522      * and 0x0C are guaranteed to be supported.
6523      *
6524      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6525      * considered an error and the channel shall not be opened.
6526      *
6527      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6528      *
6529      * <p>Requires Permission:
6530      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6531      *
6532      * @param slotIndex the physical slot index of the ICC card
6533      * @param aid Application id. See ETSI 102.221 and 101.220.
6534      * @param p2 P2 parameter (described in ISO 7816-4).
6535      * @return an IccOpenLogicalChannelResponse object.
6536      * @hide
6537      */
6538     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6539     @SystemApi
6540     @Nullable
iccOpenLogicalChannelBySlot(int slotIndex, @Nullable String aid, int p2)6541     public IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int slotIndex,
6542             @Nullable String aid, int p2) {
6543         try {
6544             ITelephony telephony = getITelephony();
6545             if (telephony != null) {
6546                 return telephony.iccOpenLogicalChannelBySlot(slotIndex, getOpPackageName(), aid,
6547                         p2);
6548             }
6549         } catch (RemoteException ex) {
6550         } catch (NullPointerException ex) {
6551         }
6552         return null;
6553     }
6554 
6555     /**
6556      * Opens a logical channel to the ICC card.
6557      *
6558      * This operation wraps two APDU instructions:
6559      * <ul>
6560      *     <li>MANAGE CHANNEL to open a logical channel</li>
6561      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6562      * </ul>
6563      *
6564      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6565      * and 0x0C are guaranteed to be supported.
6566      *
6567      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6568      * considered an error and the channel shall not be opened.
6569      *
6570      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6571      *
6572      * <p>Requires Permission:
6573      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6574      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6575      *
6576      * @param AID Application id. See ETSI 102.221 and 101.220.
6577      * @param p2 P2 parameter (described in ISO 7816-4).
6578      * @return an IccOpenLogicalChannelResponse object.
6579      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6580      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6581      *             {@link android.se.omapi.Reader#openSession()},
6582      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
6583      */
6584     @Deprecated
iccOpenLogicalChannel(String AID, int p2)6585     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID, int p2) {
6586         return iccOpenLogicalChannel(getSubId(), AID, p2);
6587     }
6588 
6589     /**
6590      * Opens a logical channel to the ICC card.
6591      *
6592      * This operation wraps two APDU instructions:
6593      * <ul>
6594      *     <li>MANAGE CHANNEL to open a logical channel</li>
6595      *     <li>SELECT the given {@code AID} using the given {@code p2}</li>
6596      * </ul>
6597      *
6598      * Per Open Mobile API Specification v3.2 section 6.2.7.h, only p2 values of 0x00, 0x04, 0x08,
6599      * and 0x0C are guaranteed to be supported.
6600      *
6601      * If the SELECT command's status word is not '9000', '62xx', or '63xx', the status word will be
6602      * considered an error and the channel shall not be opened.
6603      *
6604      * Input parameters equivalent to TS 27.007 AT+CCHO command.
6605      *
6606      * <p>Requires Permission:
6607      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6608      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6609      *
6610      * @param subId The subscription to use.
6611      * @param AID Application id. See ETSI 102.221 and 101.220.
6612      * @param p2 P2 parameter (described in ISO 7816-4).
6613      * @return an IccOpenLogicalChannelResponse object.
6614      * @hide
6615      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6616      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6617      *             {@link android.se.omapi.Reader#openSession()},
6618      *             {@link android.se.omapi.Session#openLogicalChannel(byte[], byte)}.
6619      */
6620     @Deprecated
iccOpenLogicalChannel(int subId, String AID, int p2)6621     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID, int p2) {
6622         try {
6623             ITelephony telephony = getITelephony();
6624             if (telephony != null)
6625                 return telephony.iccOpenLogicalChannel(subId, getOpPackageName(), AID, p2);
6626         } catch (RemoteException ex) {
6627         } catch (NullPointerException ex) {
6628         }
6629         return null;
6630     }
6631 
6632     /**
6633      * Closes a previously opened logical channel to the ICC card using the physical slot index.
6634      *
6635      * Use this method when no subscriptions are available on the SIM and the operation must be
6636      * performed using the physical slot index.
6637      *
6638      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6639      *
6640      * <p>Requires Permission:
6641      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6642      *
6643      * @param slotIndex the physical slot index of the ICC card
6644      * @param channel is the channel id to be closed as returned by a successful
6645      *            iccOpenLogicalChannel.
6646      * @return true if the channel was closed successfully.
6647      * @hide
6648      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6649      *             {@link android.se.omapi.Channel#close()}.
6650      */
6651     @Deprecated
6652     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6653     @SystemApi
iccCloseLogicalChannelBySlot(int slotIndex, int channel)6654     public boolean iccCloseLogicalChannelBySlot(int slotIndex, int channel) {
6655         try {
6656             ITelephony telephony = getITelephony();
6657             if (telephony != null) {
6658                 return telephony.iccCloseLogicalChannelBySlot(slotIndex, channel);
6659             }
6660         } catch (RemoteException ex) {
6661         } catch (NullPointerException ex) {
6662         }
6663         return false;
6664     }
6665 
6666     /**
6667      * Closes a previously opened logical channel to the ICC card.
6668      *
6669      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6670      *
6671      * <p>Requires Permission:
6672      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6673      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6674      *
6675      * @param channel is the channel id to be closed as returned by a successful
6676      *            iccOpenLogicalChannel.
6677      * @return true if the channel was closed successfully.
6678      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6679      *             {@link android.se.omapi.Channel#close()}.
6680      */
6681     @Deprecated
iccCloseLogicalChannel(int channel)6682     public boolean iccCloseLogicalChannel(int channel) {
6683         return iccCloseLogicalChannel(getSubId(), channel);
6684     }
6685 
6686     /**
6687      * Closes a previously opened logical channel to the ICC card.
6688      *
6689      * Input parameters equivalent to TS 27.007 AT+CCHC command.
6690      *
6691      * <p>Requires Permission:
6692      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6693      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6694      *
6695      * @param subId The subscription to use.
6696      * @param channel is the channel id to be closed as returned by a successful
6697      *            iccOpenLogicalChannel.
6698      * @return true if the channel was closed successfully.
6699      * @hide
6700      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6701      *             {@link android.se.omapi.Channel#close()}.
6702      */
6703     @Deprecated
iccCloseLogicalChannel(int subId, int channel)6704     public boolean iccCloseLogicalChannel(int subId, int channel) {
6705         try {
6706             ITelephony telephony = getITelephony();
6707             if (telephony != null)
6708                 return telephony.iccCloseLogicalChannel(subId, channel);
6709         } catch (RemoteException ex) {
6710         } catch (NullPointerException ex) {
6711         }
6712         return false;
6713     }
6714 
6715     /**
6716      * Transmit an APDU to the ICC card over a logical channel using the physical slot index.
6717      *
6718      * Use this method when no subscriptions are available on the SIM and the operation must be
6719      * performed using the physical slot index.
6720      *
6721      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6722      *
6723      * <p>Requires Permission:
6724      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6725      *
6726      * @param slotIndex the physical slot index of the ICC card
6727      * @param channel is the channel id to be closed as returned by a successful
6728      *            iccOpenLogicalChannel.
6729      * @param cla Class of the APDU command.
6730      * @param instruction Instruction of the APDU command.
6731      * @param p1 P1 value of the APDU command.
6732      * @param p2 P2 value of the APDU command.
6733      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6734      *            is sent to the SIM.
6735      * @param data Data to be sent with the APDU.
6736      * @return The APDU response from the ICC card with the status appended at the end, or null if
6737      * there is an issue connecting to the Telephony service.
6738      * @hide
6739      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6740      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6741      */
6742     @Deprecated
6743     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6744     @SystemApi
6745     @Nullable
iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6746     public String iccTransmitApduLogicalChannelBySlot(int slotIndex, int channel, int cla,
6747             int instruction, int p1, int p2, int p3, @Nullable String data) {
6748         try {
6749             ITelephony telephony = getITelephony();
6750             if (telephony != null) {
6751                 return telephony.iccTransmitApduLogicalChannelBySlot(slotIndex, channel, cla,
6752                         instruction, p1, p2, p3, data);
6753             }
6754         } catch (RemoteException ex) {
6755         } catch (NullPointerException ex) {
6756         }
6757         return null;
6758     }
6759 
6760     /**
6761      * Transmit an APDU to the ICC card over a logical channel.
6762      *
6763      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6764      *
6765      * <p>Requires Permission:
6766      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6767      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6768      *
6769      * @param channel is the channel id to be closed as returned by a successful
6770      *            iccOpenLogicalChannel.
6771      * @param cla Class of the APDU command.
6772      * @param instruction Instruction of the APDU command.
6773      * @param p1 P1 value of the APDU command.
6774      * @param p2 P2 value of the APDU command.
6775      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6776      *            is sent to the SIM.
6777      * @param data Data to be sent with the APDU.
6778      * @return The APDU response from the ICC card with the status appended at
6779      *            the end.
6780      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6781      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6782      */
6783     @Deprecated
iccTransmitApduLogicalChannel(int channel, int cla, int instruction, int p1, int p2, int p3, String data)6784     public String iccTransmitApduLogicalChannel(int channel, int cla,
6785             int instruction, int p1, int p2, int p3, String data) {
6786         return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
6787                     instruction, p1, p2, p3, data);
6788     }
6789 
6790     /**
6791      * Transmit an APDU to the ICC card over a logical channel.
6792      *
6793      * Input parameters equivalent to TS 27.007 AT+CGLA command.
6794      *
6795      * <p>Requires Permission:
6796      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6797      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6798      *
6799      * @param subId The subscription to use.
6800      * @param channel is the channel id to be closed as returned by a successful
6801      *            iccOpenLogicalChannel.
6802      * @param cla Class of the APDU command.
6803      * @param instruction Instruction of the APDU command.
6804      * @param p1 P1 value of the APDU command.
6805      * @param p2 P2 value of the APDU command.
6806      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6807      *            is sent to the SIM.
6808      * @param data Data to be sent with the APDU.
6809      * @return The APDU response from the ICC card with the status appended at
6810      *            the end.
6811      * @hide
6812      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6813      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6814      */
6815     @Deprecated
iccTransmitApduLogicalChannel(int subId, int channel, int cla, int instruction, int p1, int p2, int p3, String data)6816     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
6817             int instruction, int p1, int p2, int p3, String data) {
6818         try {
6819             ITelephony telephony = getITelephony();
6820             if (telephony != null)
6821                 return telephony.iccTransmitApduLogicalChannel(subId, channel, cla,
6822                     instruction, p1, p2, p3, data);
6823         } catch (RemoteException ex) {
6824         } catch (NullPointerException ex) {
6825         }
6826         return "";
6827     }
6828 
6829     /**
6830      * Transmit an APDU to the ICC card over the basic channel using the physical slot index.
6831      *
6832      * Use this method when no subscriptions are available on the SIM and the operation must be
6833      * performed using the physical slot index.
6834      *
6835      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6836      *
6837      * <p>Requires Permission:
6838      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
6839      *
6840      * @param slotIndex the physical slot index of the ICC card to target
6841      * @param cla Class of the APDU command.
6842      * @param instruction Instruction of the APDU command.
6843      * @param p1 P1 value of the APDU command.
6844      * @param p2 P2 value of the APDU command.
6845      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6846      *            is sent to the SIM.
6847      * @param data Data to be sent with the APDU.
6848      * @return The APDU response from the ICC card with the status appended at
6849      *            the end.
6850      * @hide
6851      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6852      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6853      *             {@link android.se.omapi.Reader#openSession()},
6854      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6855      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6856      */
6857     @Deprecated
6858     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
6859     @SystemApi
6860     @NonNull
iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1, int p2, int p3, @Nullable String data)6861     public String iccTransmitApduBasicChannelBySlot(int slotIndex, int cla, int instruction, int p1,
6862             int p2, int p3, @Nullable String data) {
6863         try {
6864             ITelephony telephony = getITelephony();
6865             if (telephony != null) {
6866                 return telephony.iccTransmitApduBasicChannelBySlot(slotIndex, getOpPackageName(),
6867                         cla, instruction, p1, p2, p3, data);
6868             }
6869         } catch (RemoteException ex) {
6870         } catch (NullPointerException ex) {
6871         }
6872         return null;
6873     }
6874 
6875     /**
6876      * Transmit an APDU to the ICC card over the basic channel.
6877      *
6878      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6879      *
6880      * <p>Requires Permission:
6881      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6882      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6883      *
6884      * @param cla Class of the APDU command.
6885      * @param instruction Instruction of the APDU command.
6886      * @param p1 P1 value of the APDU command.
6887      * @param p2 P2 value of the APDU command.
6888      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6889      *            is sent to the SIM.
6890      * @param data Data to be sent with the APDU.
6891      * @return The APDU response from the ICC card with the status appended at
6892      *            the end.
6893      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6894      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6895      *             {@link android.se.omapi.Reader#openSession()},
6896      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6897      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6898      */
6899     @Deprecated
iccTransmitApduBasicChannel(int cla, int instruction, int p1, int p2, int p3, String data)6900     public String iccTransmitApduBasicChannel(int cla,
6901             int instruction, int p1, int p2, int p3, String data) {
6902         return iccTransmitApduBasicChannel(getSubId(), cla,
6903                     instruction, p1, p2, p3, data);
6904     }
6905 
6906     /**
6907      * Transmit an APDU to the ICC card over the basic channel.
6908      *
6909      * Input parameters equivalent to TS 27.007 AT+CSIM command.
6910      *
6911      * <p>Requires Permission:
6912      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6913      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6914      *
6915      * @param subId The subscription to use.
6916      * @param cla Class of the APDU command.
6917      * @param instruction Instruction of the APDU command.
6918      * @param p1 P1 value of the APDU command.
6919      * @param p2 P2 value of the APDU command.
6920      * @param p3 P3 value of the APDU command. If p3 is negative a 4 byte APDU
6921      *            is sent to the SIM.
6922      * @param data Data to be sent with the APDU.
6923      * @return The APDU response from the ICC card with the status appended at
6924      *            the end.
6925      * @hide
6926      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6927      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6928      *             {@link android.se.omapi.Reader#openSession()},
6929      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6930      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6931      */
6932     @Deprecated
iccTransmitApduBasicChannel(int subId, int cla, int instruction, int p1, int p2, int p3, String data)6933     public String iccTransmitApduBasicChannel(int subId, int cla,
6934             int instruction, int p1, int p2, int p3, String data) {
6935         try {
6936             ITelephony telephony = getITelephony();
6937             if (telephony != null)
6938                 return telephony.iccTransmitApduBasicChannel(subId, getOpPackageName(), cla,
6939                     instruction, p1, p2, p3, data);
6940         } catch (RemoteException ex) {
6941         } catch (NullPointerException ex) {
6942         }
6943         return "";
6944     }
6945 
6946     /**
6947      * Returns the response APDU for a command APDU sent through SIM_IO.
6948      *
6949      * <p>Requires Permission:
6950      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6951      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6952      *
6953      * @param fileID
6954      * @param command
6955      * @param p1 P1 value of the APDU command.
6956      * @param p2 P2 value of the APDU command.
6957      * @param p3 P3 value of the APDU command.
6958      * @param filePath
6959      * @return The APDU response.
6960      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6961      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6962      *             {@link android.se.omapi.Reader#openSession()},
6963      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6964      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6965      */
6966     @Deprecated
iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3, String filePath)6967     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
6968             String filePath) {
6969         return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
6970     }
6971 
6972     /**
6973      * Returns the response APDU for a command APDU sent through SIM_IO.
6974      *
6975      * <p>Requires Permission:
6976      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
6977      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
6978      *
6979      * @param subId The subscription to use.
6980      * @param fileID
6981      * @param command
6982      * @param p1 P1 value of the APDU command.
6983      * @param p2 P2 value of the APDU command.
6984      * @param p3 P3 value of the APDU command.
6985      * @param filePath
6986      * @return The APDU response.
6987      * @hide
6988      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
6989      *             {@link android.se.omapi.SEService#getUiccReader(int)},
6990      *             {@link android.se.omapi.Reader#openSession()},
6991      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
6992      *             {@link android.se.omapi.Channel#transmit(byte[])}.
6993      */
6994     @Deprecated
iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3, String filePath)6995     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
6996             int p3, String filePath) {
6997         try {
6998             ITelephony telephony = getITelephony();
6999             if (telephony != null)
7000                 return telephony.iccExchangeSimIO(subId, fileID, command, p1, p2, p3, filePath);
7001         } catch (RemoteException ex) {
7002         } catch (NullPointerException ex) {
7003         }
7004         return null;
7005     }
7006 
7007     /**
7008      * Send ENVELOPE to the SIM and return the response.
7009      *
7010      * <p>Requires Permission:
7011      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7012      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7013      *
7014      * @param content String containing SAT/USAT response in hexadecimal
7015      *                format starting with command tag. See TS 102 223 for
7016      *                details.
7017      * @return The APDU response from the ICC card in hexadecimal format
7018      *         with the last 4 bytes being the status word. If the command fails,
7019      *         returns an empty string.
7020      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
7021      *             {@link android.se.omapi.SEService#getUiccReader(int)},
7022      *             {@link android.se.omapi.Reader#openSession()},
7023      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
7024      *             {@link android.se.omapi.Channel#transmit(byte[])}.
7025      */
7026     @Deprecated
sendEnvelopeWithStatus(String content)7027     public String sendEnvelopeWithStatus(String content) {
7028         return sendEnvelopeWithStatus(getSubId(), content);
7029     }
7030 
7031     /**
7032      * Send ENVELOPE to the SIM and return the response.
7033      *
7034      * <p>Requires Permission:
7035      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7036      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7037      *
7038      * @param subId The subscription to use.
7039      * @param content String containing SAT/USAT response in hexadecimal
7040      *                format starting with command tag. See TS 102 223 for
7041      *                details.
7042      * @return The APDU response from the ICC card in hexadecimal format
7043      *         with the last 4 bytes being the status word. If the command fails,
7044      *         returns an empty string.
7045      * @hide
7046      * @deprecated Use {@link android.se.omapi.SEService} APIs instead. See
7047      *             {@link android.se.omapi.SEService#getUiccReader(int)},
7048      *             {@link android.se.omapi.Reader#openSession()},
7049      *             {@link android.se.omapi.Session#openBasicChannel(byte[], byte)},
7050      *             {@link android.se.omapi.Channel#transmit(byte[])}.
7051      */
7052     @Deprecated
sendEnvelopeWithStatus(int subId, String content)7053     public String sendEnvelopeWithStatus(int subId, String content) {
7054         try {
7055             ITelephony telephony = getITelephony();
7056             if (telephony != null)
7057                 return telephony.sendEnvelopeWithStatus(subId, content);
7058         } catch (RemoteException ex) {
7059         } catch (NullPointerException ex) {
7060         }
7061         return "";
7062     }
7063 
7064     /**
7065      * Read one of the NV items defined in com.android.internal.telephony.RadioNVItems.
7066      * Used for device configuration by some CDMA operators.
7067      *
7068      * <p>Requires Permission:
7069      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7070      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7071      *
7072      * @param itemID the ID of the item to read.
7073      * @return the NV item as a String, or null on any failure.
7074      *
7075      * @hide
7076      */
7077     @UnsupportedAppUsage
nvReadItem(int itemID)7078     public String nvReadItem(int itemID) {
7079         try {
7080             ITelephony telephony = getITelephony();
7081             if (telephony != null)
7082                 return telephony.nvReadItem(itemID);
7083         } catch (RemoteException ex) {
7084             Rlog.e(TAG, "nvReadItem RemoteException", ex);
7085         } catch (NullPointerException ex) {
7086             Rlog.e(TAG, "nvReadItem NPE", ex);
7087         }
7088         return "";
7089     }
7090 
7091     /**
7092      * Write one of the NV items defined in com.android.internal.telephony.RadioNVItems.
7093      * Used for device configuration by some CDMA operators.
7094      *
7095      * <p>Requires Permission:
7096      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7097      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7098      *
7099      * @param itemID the ID of the item to read.
7100      * @param itemValue the value to write, as a String.
7101      * @return true on success; false on any failure.
7102      *
7103      * @hide
7104      */
nvWriteItem(int itemID, String itemValue)7105     public boolean nvWriteItem(int itemID, String itemValue) {
7106         try {
7107             ITelephony telephony = getITelephony();
7108             if (telephony != null)
7109                 return telephony.nvWriteItem(itemID, itemValue);
7110         } catch (RemoteException ex) {
7111             Rlog.e(TAG, "nvWriteItem RemoteException", ex);
7112         } catch (NullPointerException ex) {
7113             Rlog.e(TAG, "nvWriteItem NPE", ex);
7114         }
7115         return false;
7116     }
7117 
7118     /**
7119      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
7120      * Used for device configuration by some CDMA operators.
7121      *
7122      * <p>Requires Permission:
7123      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7124      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7125      *
7126      * @param preferredRoamingList byte array containing the new PRL.
7127      * @return true on success; false on any failure.
7128      *
7129      * @hide
7130      */
nvWriteCdmaPrl(byte[] preferredRoamingList)7131     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
7132         try {
7133             ITelephony telephony = getITelephony();
7134             if (telephony != null)
7135                 return telephony.nvWriteCdmaPrl(preferredRoamingList);
7136         } catch (RemoteException ex) {
7137             Rlog.e(TAG, "nvWriteCdmaPrl RemoteException", ex);
7138         } catch (NullPointerException ex) {
7139             Rlog.e(TAG, "nvWriteCdmaPrl NPE", ex);
7140         }
7141         return false;
7142     }
7143 
7144     /**
7145      * Perform the specified type of NV config reset. The radio will be taken offline
7146      * and the device must be rebooted after the operation. Used for device
7147      * configuration by some CDMA operators.
7148      *
7149      * <p>Requires Permission:
7150      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7151      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7152      *
7153      * TODO: remove this one. use {@link #rebootRadio()} for reset type 1 and
7154      * {@link #resetRadioConfig()} for reset type 3
7155      *
7156      * @param resetType reset type: 1: reload NV reset, 2: erase NV reset, 3: factory NV reset
7157      * @return true on success; false on any failure.
7158      *
7159      * @hide
7160      */
7161     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
nvResetConfig(int resetType)7162     public boolean nvResetConfig(int resetType) {
7163         try {
7164             ITelephony telephony = getITelephony();
7165             if (telephony != null) {
7166                 if (resetType == 1 /*1: reload NV reset */) {
7167                     return telephony.rebootModem(getSlotIndex());
7168                 } else if (resetType == 3 /*3: factory NV reset */) {
7169                     return telephony.resetModemConfig(getSlotIndex());
7170                 } else {
7171                     Rlog.e(TAG, "nvResetConfig unsupported reset type");
7172                 }
7173             }
7174         } catch (RemoteException ex) {
7175             Rlog.e(TAG, "nvResetConfig RemoteException", ex);
7176         } catch (NullPointerException ex) {
7177             Rlog.e(TAG, "nvResetConfig NPE", ex);
7178         }
7179         return false;
7180     }
7181 
7182     /**
7183      * Rollback modem configurations to factory default except some config which are in whitelist.
7184      * Used for device configuration by some carriers.
7185      *
7186      * <p>Requires Permission:
7187      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7188      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7189      *
7190      * @return {@code true} on success; {@code false} on any failure.
7191      *
7192      * @hide
7193      */
7194     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7195     @SystemApi
resetRadioConfig()7196     public boolean resetRadioConfig() {
7197         try {
7198             ITelephony telephony = getITelephony();
7199             if (telephony != null) {
7200                 return telephony.resetModemConfig(getSlotIndex());
7201             }
7202         } catch (RemoteException ex) {
7203             Rlog.e(TAG, "resetRadioConfig RemoteException", ex);
7204         } catch (NullPointerException ex) {
7205             Rlog.e(TAG, "resetRadioConfig NPE", ex);
7206         }
7207         return false;
7208     }
7209 
7210     /**
7211      * Generate a radio modem reset. Used for device configuration by some carriers.
7212      *
7213      * <p>Requires Permission:
7214      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
7215      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
7216      *
7217      * @return {@code true} on success; {@code false} on any failure.
7218      *
7219      * @hide
7220      */
7221     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
7222     @SystemApi
rebootRadio()7223     public boolean rebootRadio() {
7224         try {
7225             ITelephony telephony = getITelephony();
7226             if (telephony != null) {
7227                 return telephony.rebootModem(getSlotIndex());
7228             }
7229         } catch (RemoteException ex) {
7230             Rlog.e(TAG, "rebootRadio RemoteException", ex);
7231         } catch (NullPointerException ex) {
7232             Rlog.e(TAG, "rebootRadio NPE", ex);
7233         }
7234         return false;
7235     }
7236 
7237     /**
7238      * Return an appropriate subscription ID for any situation.
7239      *
7240      * If this object has been created with {@link #createForSubscriptionId}, then the provided
7241      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
7242      *
7243      */
getSubscriptionId()7244     public int getSubscriptionId() {
7245         return getSubId();
7246     }
7247 
7248     /**
7249      * Return an appropriate subscription ID for any situation.
7250      *
7251      * If this object has been created with {@link #createForSubscriptionId}, then the provided
7252      * subscription ID is returned. Otherwise, the default subscription ID will be returned.
7253      *
7254      */
getSubId()7255     private int getSubId() {
7256       if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
7257         return mSubId;
7258       }
7259       return SubscriptionManager.getDefaultSubscriptionId();
7260     }
7261 
7262     /**
7263      * Return an appropriate subscription ID for any situation.
7264      *
7265      * If this object has been created with {@link #createForSubscriptionId}, then the provided
7266      * subId is returned. Otherwise, the preferred subId which is based on caller's context is
7267      * returned.
7268      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
7269      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
7270      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
7271      */
7272     @UnsupportedAppUsage
getSubId(int preferredSubId)7273     private int getSubId(int preferredSubId) {
7274         if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
7275             return mSubId;
7276         }
7277         return preferredSubId;
7278     }
7279 
7280     /**
7281      * Return an appropriate phone ID for any situation.
7282      *
7283      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
7284      * associated with the provided subId is returned. Otherwise, the default phoneId associated
7285      * with the default subId will be returned.
7286      */
getPhoneId()7287     private int getPhoneId() {
7288         return SubscriptionManager.getPhoneId(getSubId());
7289     }
7290 
7291     /**
7292      * Return an appropriate phone ID for any situation.
7293      *
7294      * If this object has been created with {@link #createForSubscriptionId}, then the phoneId
7295      * associated with the provided subId is returned. Otherwise, return the phoneId associated
7296      * with the preferred subId based on caller's context.
7297      * {@see SubscriptionManager#getDefaultDataSubscriptionId()}
7298      * {@see SubscriptionManager#getDefaultVoiceSubscriptionId()}
7299      * {@see SubscriptionManager#getDefaultSmsSubscriptionId()}
7300      */
7301     @UnsupportedAppUsage
getPhoneId(int preferredSubId)7302     private int getPhoneId(int preferredSubId) {
7303         return SubscriptionManager.getPhoneId(getSubId(preferredSubId));
7304     }
7305 
7306     /**
7307      * Return an appropriate slot index for any situation.
7308      *
7309      * if this object has been created with {@link #createForSubscriptionId}, then the slot index
7310      * associated with the provided subId is returned. Otherwise, return the slot index associated
7311      * with the default subId.
7312      * If SIM is not inserted, return default SIM slot index.
7313      *
7314      * {@hide}
7315      */
7316     @VisibleForTesting
7317     @UnsupportedAppUsage
getSlotIndex()7318     public int getSlotIndex() {
7319         int slotIndex = SubscriptionManager.getSlotIndex(getSubId());
7320         if (slotIndex == SubscriptionManager.SIM_NOT_INSERTED) {
7321             slotIndex = SubscriptionManager.DEFAULT_SIM_SLOT_INDEX;
7322         }
7323         return slotIndex;
7324     }
7325 
7326     /**
7327      * Request that the next incoming call from a number matching {@code range} be intercepted.
7328      *
7329      * This API is intended for OEMs to provide a service for apps to verify the device's phone
7330      * number. When called, the Telephony stack will store the provided {@link PhoneNumberRange} and
7331      * intercept the next incoming call from a number that lies within the range, within a timeout
7332      * specified by {@code timeoutMillis}.
7333      *
7334      * If such a phone call is received, the caller will be notified via
7335      * {@link NumberVerificationCallback#onCallReceived(String)} on the provided {@link Executor}.
7336      * If verification fails for any reason, the caller will be notified via
7337      * {@link NumberVerificationCallback#onVerificationFailed(int)}
7338      * on the provided {@link Executor}.
7339      *
7340      * In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of this
7341      * API must also be listed in the device configuration as an authorized app in
7342      * {@code packages/services/Telephony/res/values/config.xml} under the
7343      * {@code config_number_verification_package_name} key.
7344      *
7345      * @hide
7346      * @param range The range of phone numbers the caller expects a phone call from.
7347      * @param timeoutMillis The amount of time to wait for such a call, or the value of
7348      *                      {@link #getMaxNumberVerificationTimeoutMillis()}, whichever is lesser.
7349      * @param executor The {@link Executor} that callbacks should be executed on.
7350      * @param callback The callback to use for delivering results.
7351      */
7352     @SystemApi
7353     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
requestNumberVerification(@onNull PhoneNumberRange range, long timeoutMillis, @NonNull @CallbackExecutor Executor executor, @NonNull NumberVerificationCallback callback)7354     public void requestNumberVerification(@NonNull PhoneNumberRange range, long timeoutMillis,
7355             @NonNull @CallbackExecutor Executor executor,
7356             @NonNull NumberVerificationCallback callback) {
7357         if (executor == null) {
7358             throw new NullPointerException("Executor must be non-null");
7359         }
7360         if (callback == null) {
7361             throw new NullPointerException("Callback must be non-null");
7362         }
7363 
7364         INumberVerificationCallback internalCallback = new INumberVerificationCallback.Stub() {
7365             @Override
7366             public void onCallReceived(String phoneNumber) {
7367                 final long identity = Binder.clearCallingIdentity();
7368                 try {
7369                     executor.execute(() ->
7370                             callback.onCallReceived(phoneNumber));
7371                 } finally {
7372                     Binder.restoreCallingIdentity(identity);
7373                 }
7374             }
7375 
7376             @Override
7377             public void onVerificationFailed(int reason) {
7378                 final long identity = Binder.clearCallingIdentity();
7379                 try {
7380                     executor.execute(() ->
7381                             callback.onVerificationFailed(reason));
7382                 } finally {
7383                     Binder.restoreCallingIdentity(identity);
7384                 }
7385             }
7386         };
7387 
7388         try {
7389             ITelephony telephony = getITelephony();
7390             if (telephony == null) {
7391                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
7392                     throw new IllegalStateException("Telephony is null");
7393                 } else {
7394                     return;
7395                 }
7396             }
7397 
7398             telephony.requestNumberVerification(range, timeoutMillis, internalCallback,
7399                     getOpPackageName());
7400         } catch (RemoteException ex) {
7401             Rlog.e(TAG, "requestNumberVerification RemoteException", ex);
7402             runOnBackgroundThread(() -> executor.execute(
7403                     () -> callback.onVerificationFailed(
7404                             NumberVerificationCallback.REASON_UNSPECIFIED)));
7405         }
7406     }
7407 
7408     /**
7409      * Inserts or updates a list property. Expands the list if its length is not enough.
7410      */
updateTelephonyProperty(List<T> prop, int phoneId, T value)7411     private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
7412         List<T> ret = new ArrayList<>(prop);
7413         while (ret.size() <= phoneId) ret.add(null);
7414         ret.set(phoneId, value);
7415         return ret;
7416     }
7417     /**
7418      * Convenience function for retrieving a value from the secure settings
7419      * value list as an integer.  Note that internally setting values are
7420      * always stored as strings; this function converts the string to an
7421      * integer for you.
7422      * <p>
7423      * This version does not take a default value.  If the setting has not
7424      * been set, or the string value is not a number,
7425      * it throws {@link SettingNotFoundException}.
7426      *
7427      * @param cr The ContentResolver to access.
7428      * @param name The name of the setting to retrieve.
7429      * @param index The index of the list
7430      *
7431      * @throws SettingNotFoundException Thrown if a setting by the given
7432      * name can't be found or the setting value is not an integer.
7433      *
7434      * @return The value at the given index of settings.
7435      * @hide
7436      */
7437     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getIntAtIndex(android.content.ContentResolver cr, String name, int index)7438     public static int getIntAtIndex(android.content.ContentResolver cr,
7439             String name, int index)
7440             throws android.provider.Settings.SettingNotFoundException {
7441         String v = android.provider.Settings.Global.getString(cr, name);
7442         if (v != null) {
7443             String valArray[] = v.split(",");
7444             if ((index >= 0) && (index < valArray.length) && (valArray[index] != null)) {
7445                 try {
7446                     return Integer.parseInt(valArray[index]);
7447                 } catch (NumberFormatException e) {
7448                     //Log.e(TAG, "Exception while parsing Integer: ", e);
7449                 }
7450             }
7451         }
7452         throw new android.provider.Settings.SettingNotFoundException(name);
7453     }
7454 
7455     /**
7456      * Convenience function for updating settings value as coma separated
7457      * integer values. This will either create a new entry in the table if the
7458      * given name does not exist, or modify the value of the existing row
7459      * with that name.  Note that internally setting values are always
7460      * stored as strings, so this function converts the given value to a
7461      * string before storing it.
7462      *
7463      * @param cr The ContentResolver to access.
7464      * @param name The name of the setting to modify.
7465      * @param index The index of the list
7466      * @param value The new value for the setting to be added to the list.
7467      * @return true if the value was set, false on database errors
7468      * @hide
7469      */
7470     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
putIntAtIndex(android.content.ContentResolver cr, String name, int index, int value)7471     public static boolean putIntAtIndex(android.content.ContentResolver cr,
7472             String name, int index, int value) {
7473         String data = "";
7474         String valArray[] = null;
7475         String v = android.provider.Settings.Global.getString(cr, name);
7476 
7477         if (index == Integer.MAX_VALUE) {
7478             throw new IllegalArgumentException("putIntAtIndex index == MAX_VALUE index=" + index);
7479         }
7480         if (index < 0) {
7481             throw new IllegalArgumentException("putIntAtIndex index < 0 index=" + index);
7482         }
7483         if (v != null) {
7484             valArray = v.split(",");
7485         }
7486 
7487         // Copy the elements from valArray till index
7488         for (int i = 0; i < index; i++) {
7489             String str = "";
7490             if ((valArray != null) && (i < valArray.length)) {
7491                 str = valArray[i];
7492             }
7493             data = data + str + ",";
7494         }
7495 
7496         data = data + value;
7497 
7498         // Copy the remaining elements from valArray if any.
7499         if (valArray != null) {
7500             for (int i = index+1; i < valArray.length; i++) {
7501                 data = data + "," + valArray[i];
7502             }
7503         }
7504         return android.provider.Settings.Global.putString(cr, name, data);
7505     }
7506 
7507     /**
7508      * Gets a per-phone telephony property from a property name.
7509      *
7510      * @hide
7511      */
7512     @UnsupportedAppUsage
getTelephonyProperty(int phoneId, String property, String defaultVal)7513     public static String getTelephonyProperty(int phoneId, String property, String defaultVal) {
7514         String propVal = null;
7515         String prop = SystemProperties.get(property);
7516         if ((prop != null) && (prop.length() > 0)) {
7517             String values[] = prop.split(",");
7518             if ((phoneId >= 0) && (phoneId < values.length) && (values[phoneId] != null)) {
7519                 propVal = values[phoneId];
7520             }
7521         }
7522         return propVal == null ? defaultVal : propVal;
7523     }
7524 
7525     /**
7526      * Gets a typed per-phone telephony property from a schematized list property.
7527      */
getTelephonyProperty(int phoneId, List<T> prop, T defaultValue)7528     private static <T> T getTelephonyProperty(int phoneId, List<T> prop, T defaultValue) {
7529         T ret = null;
7530         if (phoneId >= 0 && phoneId < prop.size()) ret = prop.get(phoneId);
7531         return ret != null ? ret : defaultValue;
7532     }
7533 
7534     /**
7535      * Gets a global telephony property.
7536      *
7537      * See also getTelephonyProperty(phoneId, property, defaultVal). Most telephony properties are
7538      * per-phone.
7539      *
7540      * @hide
7541      */
7542     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getTelephonyProperty(String property, String defaultVal)7543     public static String getTelephonyProperty(String property, String defaultVal) {
7544         String propVal = SystemProperties.get(property);
7545         return TextUtils.isEmpty(propVal) ? defaultVal : propVal;
7546     }
7547 
7548     /** @hide */
7549     @UnsupportedAppUsage
getSimCount()7550     public int getSimCount() {
7551         // FIXME Need to get it from Telephony Dev Controller when that gets implemented!
7552         // and then this method shouldn't be used at all!
7553         return getPhoneCount();
7554     }
7555 
7556     /**
7557      * Returns the IMS Service Table (IST) that was loaded from the ISIM.
7558      *
7559      * See 3GPP TS 31.103 (Section 4.2.7) for the definition and more information on this table.
7560      *
7561      * @return IMS Service Table or null if not present or not loaded
7562      * @hide
7563      */
7564     @Nullable
7565     @SystemApi
7566     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getIsimIst()7567     public String getIsimIst() {
7568         try {
7569             IPhoneSubInfo info = getSubscriberInfoService();
7570             if (info == null)
7571                 return null;
7572             //get the Isim Ist based on subId
7573             return info.getIsimIst(getSubId());
7574         } catch (RemoteException ex) {
7575             return null;
7576         } catch (NullPointerException ex) {
7577             // This could happen before phone restarts due to crashing
7578             return null;
7579         }
7580     }
7581 
7582     /**
7583      * Returns the IMS Proxy Call Session Control Function(PCSCF) that were loaded from the ISIM.
7584      * @return an array of PCSCF strings with one PCSCF per string, or null if
7585      *         not present or not loaded
7586      * @hide
7587      */
7588     @UnsupportedAppUsage
getIsimPcscf()7589     public String[] getIsimPcscf() {
7590         try {
7591             IPhoneSubInfo info = getSubscriberInfoService();
7592             if (info == null)
7593                 return null;
7594             //get the Isim Pcscf based on subId
7595             return info.getIsimPcscf(getSubId());
7596         } catch (RemoteException ex) {
7597             return null;
7598         } catch (NullPointerException ex) {
7599             // This could happen before phone restarts due to crashing
7600             return null;
7601         }
7602     }
7603 
7604     /** UICC application type is unknown or not specified */
7605     public static final int APPTYPE_UNKNOWN = PhoneConstants.APPTYPE_UNKNOWN;
7606     /** UICC application type is SIM */
7607     public static final int APPTYPE_SIM = PhoneConstants.APPTYPE_SIM;
7608     /** UICC application type is USIM */
7609     public static final int APPTYPE_USIM = PhoneConstants.APPTYPE_USIM;
7610     /** UICC application type is RUIM */
7611     public static final int APPTYPE_RUIM = PhoneConstants.APPTYPE_RUIM;
7612     /** UICC application type is CSIM */
7613     public static final int APPTYPE_CSIM = PhoneConstants.APPTYPE_CSIM;
7614     /** UICC application type is ISIM */
7615     public static final int APPTYPE_ISIM = PhoneConstants.APPTYPE_ISIM;
7616 
7617     // authContext (parameter P2) when doing UICC challenge,
7618     // per 3GPP TS 31.102 (Section 7.1.2)
7619     /** Authentication type for UICC challenge is EAP SIM. See RFC 4186 for details. */
7620     public static final int AUTHTYPE_EAP_SIM = PhoneConstants.AUTH_CONTEXT_EAP_SIM;
7621     /** Authentication type for UICC challenge is EAP AKA. See RFC 4187 for details. */
7622     public static final int AUTHTYPE_EAP_AKA = PhoneConstants.AUTH_CONTEXT_EAP_AKA;
7623 
7624     /**
7625      * Returns the response of authentication for the default subscription.
7626      * Returns null if the authentication hasn't been successful
7627      *
7628      * <p>Requires one of the following permissions:
7629      * <ul>
7630      *     <li>READ_PRIVILEGED_PHONE_STATE
7631      *     <li>the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7632      *     <li>the calling app has been granted the
7633      *     {@link Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER} permission.
7634      * </ul>
7635      *
7636      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7637      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
7638      * {@link #AUTHTYPE_EAP_SIM}
7639      * @param data authentication challenge data, base64 encoded.
7640      * See 3GPP TS 31.102 7.1.2 for more details.
7641      * @return the response of authentication. This value will be null in the following cases:
7642      *   Authentication error, incorrect MAC
7643      *   Authentication error, security context not supported
7644      *   Key freshness failure
7645      *   Authentication error, no memory space available
7646      *   Authentication error, no memory space available in EFMUK
7647      */
7648     // TODO(b/73660190): This should probably require MODIFY_PHONE_STATE, not
7649     // READ_PRIVILEGED_PHONE_STATE. It certainly shouldn't reference the permission in Javadoc since
7650     // it's not public API.
getIccAuthentication(int appType, int authType, String data)7651     public String getIccAuthentication(int appType, int authType, String data) {
7652         return getIccAuthentication(getSubId(), appType, authType, data);
7653     }
7654 
7655     /**
7656      * Returns the response of USIM Authentication for specified subId.
7657      * Returns null if the authentication hasn't been successful
7658      *
7659      * <p>See {@link #getIccAuthentication(int, int, String)} for details on the required
7660      * permissions.
7661      *
7662      * @param subId subscription ID used for authentication
7663      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7664      * @param authType the authentication type, {@link #AUTHTYPE_EAP_AKA} or
7665      * {@link #AUTHTYPE_EAP_SIM}
7666      * @param data authentication challenge data, base64 encoded.
7667      * See 3GPP TS 31.102 7.1.2 for more details.
7668      * @return the response of authentication. This value will be null in the following cases only
7669      * (see 3GPP TS 31.102 7.3.1):
7670      *   Authentication error, incorrect MAC
7671      *   Authentication error, security context not supported
7672      *   Key freshness failure
7673      *   Authentication error, no memory space available
7674      *   Authentication error, no memory space available in EFMUK
7675      * @hide
7676      */
7677     @UnsupportedAppUsage
getIccAuthentication(int subId, int appType, int authType, String data)7678     public String getIccAuthentication(int subId, int appType, int authType, String data) {
7679         try {
7680             IPhoneSubInfo info = getSubscriberInfoService();
7681             if (info == null)
7682                 return null;
7683             return info.getIccSimChallengeResponse(subId, appType, authType, data,
7684                     getOpPackageName(), getAttributionTag());
7685         } catch (RemoteException ex) {
7686             return null;
7687         } catch (NullPointerException ex) {
7688             // This could happen before phone starts
7689             return null;
7690         }
7691     }
7692 
7693     /**
7694      * Returns an array of Forbidden PLMNs from the USIM App
7695      * Returns null if the query fails.
7696      *
7697      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
7698      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7699      *
7700      * @return an array of forbidden PLMNs or null if not available
7701      */
7702     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7703     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns()7704     public String[] getForbiddenPlmns() {
7705       return getForbiddenPlmns(getSubId(), APPTYPE_USIM);
7706     }
7707 
7708     /**
7709      * Returns an array of Forbidden PLMNs from the specified SIM App
7710      * Returns null if the query fails.
7711      *
7712      * @param subId subscription ID used for authentication
7713      * @param appType the icc application type, like {@link #APPTYPE_USIM}
7714      * @return fplmns an array of forbidden PLMNs
7715      * @hide
7716      */
7717     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getForbiddenPlmns(int subId, int appType)7718     public String[] getForbiddenPlmns(int subId, int appType) {
7719         try {
7720             ITelephony telephony = getITelephony();
7721             if (telephony == null)
7722                 return null;
7723             return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
7724                     getAttributionTag());
7725         } catch (RemoteException ex) {
7726             return null;
7727         } catch (NullPointerException ex) {
7728             // This could happen before phone starts
7729             return null;
7730         }
7731     }
7732 
7733     /**
7734      * Replace the contents of the forbidden PLMN SIM file with the provided values.
7735      * Passing an empty list will clear the contents of the EFfplmn file.
7736      * If the provided list is shorter than the size of EFfplmn, then the list will be padded
7737      * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
7738      * If the list is longer than the size of EFfplmn, then the file will be written from the
7739      * beginning of the list up to the file size.
7740      *
7741      * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
7742      * MODIFY_PHONE_STATE}
7743      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
7744      *
7745      * @param fplmns a list of PLMNs to be forbidden.
7746      *
7747      * @return number of PLMNs that were successfully written to the SIM FPLMN list.
7748      * This may be less than the number of PLMNs passed in where the SIM file does not have enough
7749      * room for all of the values passed in. Return -1 in the event of an unexpected failure
7750      */
7751     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
7752     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setForbiddenPlmns(@onNull List<String> fplmns)7753     public int setForbiddenPlmns(@NonNull List<String> fplmns) {
7754         try {
7755             ITelephony telephony = getITelephony();
7756             if (telephony == null) return -1;
7757             return telephony.setForbiddenPlmns(
7758                     getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
7759         } catch (RemoteException ex) {
7760             Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
7761         } catch (NullPointerException ex) {
7762             // This could happen before phone starts
7763             Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
7764         }
7765         return -1;
7766     }
7767 
7768     /**
7769      * Get P-CSCF address from PCO after data connection is established or modified.
7770      * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN
7771      * @return array of P-CSCF address
7772      * @hide
7773      */
getPcscfAddress(String apnType)7774     public String[] getPcscfAddress(String apnType) {
7775         try {
7776             ITelephony telephony = getITelephony();
7777             if (telephony == null)
7778                 return new String[0];
7779             return telephony.getPcscfAddress(apnType, getOpPackageName(), getAttributionTag());
7780         } catch (RemoteException e) {
7781             return new String[0];
7782         }
7783     }
7784 
7785 
7786     /**
7787      * Resets the {@link android.telephony.ims.ImsService} associated with the specified sim slot.
7788      * Used by diagnostic apps to force the IMS stack to be disabled and re-enabled in an effort to
7789      * recover from scenarios where the {@link android.telephony.ims.ImsService} gets in to a bad
7790      * state.
7791      *
7792      * @param slotIndex the sim slot to reset the IMS stack on.
7793      * @hide */
7794     @SystemApi
7795     @WorkerThread
7796     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetIms(int slotIndex)7797     public void resetIms(int slotIndex) {
7798         try {
7799             ITelephony telephony = getITelephony();
7800             if (telephony != null) {
7801                 telephony.resetIms(slotIndex);
7802             }
7803         } catch (RemoteException e) {
7804             Rlog.e(TAG, "toggleImsOnOff, RemoteException: "
7805                     + e.getMessage());
7806         }
7807     }
7808 
7809     /**
7810      * Enables IMS for the framework. This will trigger IMS registration and ImsFeature capability
7811      * status updates, if not already enabled.
7812      * @hide
7813      */
enableIms(int slotId)7814     public void enableIms(int slotId) {
7815         try {
7816             ITelephony telephony = getITelephony();
7817             if (telephony != null) {
7818                 telephony.enableIms(slotId);
7819             }
7820         } catch (RemoteException e) {
7821             Rlog.e(TAG, "enableIms, RemoteException: "
7822                     + e.getMessage());
7823         }
7824     }
7825 
7826     /**
7827      * Disables IMS for the framework. This will trigger IMS de-registration and trigger ImsFeature
7828      * status updates to disabled.
7829      * @hide
7830      */
disableIms(int slotId)7831     public void disableIms(int slotId) {
7832         try {
7833             ITelephony telephony = getITelephony();
7834             if (telephony != null) {
7835                 telephony.disableIms(slotId);
7836             }
7837         } catch (RemoteException e) {
7838             Rlog.e(TAG, "disableIms, RemoteException: "
7839                     + e.getMessage());
7840         }
7841     }
7842 
7843     /**
7844      * @return the {@IImsRegistration} interface that corresponds with the slot index and feature.
7845      * @param slotIndex The SIM slot corresponding to the ImsService ImsRegistration is active for.
7846      * @param feature An integer indicating the feature that we wish to get the ImsRegistration for.
7847      * Corresponds to features defined in ImsFeature.
7848      * @hide
7849      */
7850     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsRegistration(int slotIndex, int feature)7851     public @Nullable IImsRegistration getImsRegistration(int slotIndex, int feature) {
7852         try {
7853             ITelephony telephony = getITelephony();
7854             if (telephony != null) {
7855                 return telephony.getImsRegistration(slotIndex, feature);
7856             }
7857         } catch (RemoteException e) {
7858             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7859         }
7860         return null;
7861     }
7862 
7863     /**
7864      * @return the {@IImsConfig} interface that corresponds with the slot index and feature.
7865      * @param slotIndex The SIM slot corresponding to the ImsService ImsConfig is active for.
7866      * @param feature An integer indicating the feature that we wish to get the ImsConfig for.
7867      * Corresponds to features defined in ImsFeature.
7868      * @hide
7869      */
7870     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsConfig(int slotIndex, int feature)7871     public @Nullable IImsConfig getImsConfig(int slotIndex, int feature) {
7872         try {
7873             ITelephony telephony = getITelephony();
7874             if (telephony != null) {
7875                 return telephony.getImsConfig(slotIndex, feature);
7876             }
7877         } catch (RemoteException e) {
7878             Rlog.e(TAG, "getImsRegistration, RemoteException: " + e.getMessage());
7879         }
7880         return null;
7881     }
7882 
7883     /**
7884      * Set IMS registration state on all active subscriptions.
7885      * <p/>
7886      * Use {@link android.telephony.ims.stub.ImsRegistrationImplBase#onRegistered} and
7887      * {@link android.telephony.ims.stub.ImsRegistrationImplBase#onDeregistered} to set Ims
7888      * registration state instead.
7889      *
7890      * @param registered whether ims is registered
7891      *
7892      * @hide
7893      */
7894     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setImsRegistrationState(final boolean registered)7895     public void setImsRegistrationState(final boolean registered) {
7896         try {
7897             final ITelephony telephony = getITelephony();
7898             if (telephony != null)
7899                 telephony.setImsRegistrationState(registered);
7900         } catch (final RemoteException e) {
7901         }
7902     }
7903 
7904     /** @hide */
7905     @IntDef(prefix = { "NETWORK_MODE_" }, value = {
7906             NETWORK_MODE_WCDMA_PREF,
7907             NETWORK_MODE_GSM_ONLY,
7908             NETWORK_MODE_WCDMA_ONLY,
7909             NETWORK_MODE_GSM_UMTS,
7910             NETWORK_MODE_CDMA_EVDO,
7911             NETWORK_MODE_CDMA_NO_EVDO,
7912             NETWORK_MODE_EVDO_NO_CDMA,
7913             NETWORK_MODE_GLOBAL,
7914             NETWORK_MODE_LTE_CDMA_EVDO,
7915             NETWORK_MODE_LTE_GSM_WCDMA,
7916             NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA,
7917             NETWORK_MODE_LTE_ONLY,
7918             NETWORK_MODE_LTE_WCDMA,
7919             NETWORK_MODE_TDSCDMA_ONLY,
7920             NETWORK_MODE_TDSCDMA_WCDMA,
7921             NETWORK_MODE_LTE_TDSCDMA,
7922             NETWORK_MODE_TDSCDMA_GSM,
7923             NETWORK_MODE_LTE_TDSCDMA_GSM,
7924             NETWORK_MODE_TDSCDMA_GSM_WCDMA,
7925             NETWORK_MODE_LTE_TDSCDMA_WCDMA,
7926             NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA,
7927             NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7928             NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA,
7929             NETWORK_MODE_NR_ONLY,
7930             NETWORK_MODE_NR_LTE,
7931             NETWORK_MODE_NR_LTE_CDMA_EVDO,
7932             NETWORK_MODE_NR_LTE_GSM_WCDMA,
7933             NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA,
7934             NETWORK_MODE_NR_LTE_WCDMA,
7935             NETWORK_MODE_NR_LTE_TDSCDMA,
7936             NETWORK_MODE_NR_LTE_TDSCDMA_GSM,
7937             NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA,
7938             NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA,
7939             NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA
7940     })
7941     @Retention(RetentionPolicy.SOURCE)
7942     public @interface PrefNetworkMode{}
7943 
7944     /**
7945      * Preferred network mode is GSM/WCDMA (WCDMA preferred).
7946      * @hide
7947      */
7948     public static final int NETWORK_MODE_WCDMA_PREF = RILConstants.NETWORK_MODE_WCDMA_PREF;
7949 
7950     /**
7951      * Preferred network mode is GSM only.
7952      * @hide
7953      */
7954     public static final int NETWORK_MODE_GSM_ONLY = RILConstants.NETWORK_MODE_GSM_ONLY;
7955 
7956     /**
7957      * Preferred network mode is WCDMA only.
7958      * @hide
7959      */
7960     public static final int NETWORK_MODE_WCDMA_ONLY = RILConstants.NETWORK_MODE_WCDMA_ONLY;
7961 
7962     /**
7963      * Preferred network mode is GSM/WCDMA (auto mode, according to PRL).
7964      * @hide
7965      */
7966     public static final int NETWORK_MODE_GSM_UMTS = RILConstants.NETWORK_MODE_GSM_UMTS;
7967 
7968     /**
7969      * Preferred network mode is CDMA and EvDo (auto mode, according to PRL).
7970      * @hide
7971      */
7972     public static final int NETWORK_MODE_CDMA_EVDO = RILConstants.NETWORK_MODE_CDMA;
7973 
7974     /**
7975      * Preferred network mode is CDMA only.
7976      * @hide
7977      */
7978     public static final int NETWORK_MODE_CDMA_NO_EVDO = RILConstants.NETWORK_MODE_CDMA_NO_EVDO;
7979 
7980     /**
7981      * Preferred network mode is EvDo only.
7982      * @hide
7983      */
7984     public static final int NETWORK_MODE_EVDO_NO_CDMA = RILConstants.NETWORK_MODE_EVDO_NO_CDMA;
7985 
7986     /**
7987      * Preferred network mode is GSM/WCDMA, CDMA, and EvDo (auto mode, according to PRL).
7988      * @hide
7989      */
7990     public static final int NETWORK_MODE_GLOBAL = RILConstants.NETWORK_MODE_GLOBAL;
7991 
7992     /**
7993      * Preferred network mode is LTE, CDMA and EvDo.
7994      * @hide
7995      */
7996     public static final int NETWORK_MODE_LTE_CDMA_EVDO = RILConstants.NETWORK_MODE_LTE_CDMA_EVDO;
7997 
7998     /**
7999      * Preferred network mode is LTE, GSM/WCDMA.
8000      * @hide
8001      */
8002     public static final int NETWORK_MODE_LTE_GSM_WCDMA = RILConstants.NETWORK_MODE_LTE_GSM_WCDMA;
8003 
8004     /**
8005      * Preferred network mode is LTE, CDMA, EvDo, GSM/WCDMA.
8006      * @hide
8007      */
8008     public static final int NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA =
8009             RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA;
8010 
8011     /**
8012      * Preferred network mode is LTE Only.
8013      * @hide
8014      */
8015     public static final int NETWORK_MODE_LTE_ONLY = RILConstants.NETWORK_MODE_LTE_ONLY;
8016 
8017     /**
8018      * Preferred network mode is LTE/WCDMA.
8019      * @hide
8020      */
8021     public static final int NETWORK_MODE_LTE_WCDMA = RILConstants.NETWORK_MODE_LTE_WCDMA;
8022 
8023     /**
8024      * Preferred network mode is TD-SCDMA only.
8025      * @hide
8026      */
8027     public static final int NETWORK_MODE_TDSCDMA_ONLY = RILConstants.NETWORK_MODE_TDSCDMA_ONLY;
8028 
8029     /**
8030      * Preferred network mode is TD-SCDMA and WCDMA.
8031      * @hide
8032      */
8033     public static final int NETWORK_MODE_TDSCDMA_WCDMA = RILConstants.NETWORK_MODE_TDSCDMA_WCDMA;
8034 
8035     /**
8036      * Preferred network mode is TD-SCDMA and LTE.
8037      * @hide
8038      */
8039     public static final int NETWORK_MODE_LTE_TDSCDMA = RILConstants.NETWORK_MODE_LTE_TDSCDMA;
8040 
8041     /**
8042      * Preferred network mode is TD-SCDMA and GSM.
8043      * @hide
8044      */
8045     public static final int NETWORK_MODE_TDSCDMA_GSM = RILConstants.NETWORK_MODE_TDSCDMA_GSM;
8046 
8047     /**
8048      * Preferred network mode is TD-SCDMA,GSM and LTE.
8049      * @hide
8050      */
8051     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM =
8052             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM;
8053 
8054     /**
8055      * Preferred network mode is TD-SCDMA, GSM/WCDMA.
8056      * @hide
8057      */
8058     public static final int NETWORK_MODE_TDSCDMA_GSM_WCDMA =
8059             RILConstants.NETWORK_MODE_TDSCDMA_GSM_WCDMA;
8060 
8061     /**
8062      * Preferred network mode is TD-SCDMA, WCDMA and LTE.
8063      * @hide
8064      */
8065     public static final int NETWORK_MODE_LTE_TDSCDMA_WCDMA =
8066             RILConstants.NETWORK_MODE_LTE_TDSCDMA_WCDMA;
8067 
8068     /**
8069      * Preferred network mode is TD-SCDMA, GSM/WCDMA and LTE.
8070      * @hide
8071      */
8072     public static final int NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA =
8073             RILConstants.NETWORK_MODE_LTE_TDSCDMA_GSM_WCDMA;
8074 
8075     /**
8076      * Preferred network mode is TD-SCDMA,EvDo,CDMA,GSM/WCDMA.
8077      * @hide
8078      */
8079     public static final int NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
8080             RILConstants.NETWORK_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
8081     /**
8082      * Preferred network mode is TD-SCDMA/LTE/GSM/WCDMA, CDMA, and EvDo.
8083      * @hide
8084      */
8085     public static final int NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
8086             RILConstants.NETWORK_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
8087 
8088     /**
8089      * Preferred network mode is NR 5G only.
8090      * @hide
8091      */
8092     public static final int NETWORK_MODE_NR_ONLY = RILConstants.NETWORK_MODE_NR_ONLY;
8093 
8094     /**
8095      * Preferred network mode is NR 5G, LTE.
8096      * @hide
8097      */
8098     public static final int NETWORK_MODE_NR_LTE = RILConstants.NETWORK_MODE_NR_LTE;
8099 
8100     /**
8101      * Preferred network mode is NR 5G, LTE, CDMA and EvDo.
8102      * @hide
8103      */
8104     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO =
8105             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO;
8106 
8107     /**
8108      * Preferred network mode is NR 5G, LTE, GSM and WCDMA.
8109      * @hide
8110      */
8111     public static final int NETWORK_MODE_NR_LTE_GSM_WCDMA =
8112             RILConstants.NETWORK_MODE_NR_LTE_GSM_WCDMA;
8113 
8114     /**
8115      * Preferred network mode is NR 5G, LTE, CDMA, EvDo, GSM and WCDMA.
8116      * @hide
8117      */
8118     public static final int NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA =
8119             RILConstants.NETWORK_MODE_NR_LTE_CDMA_EVDO_GSM_WCDMA;
8120 
8121     /**
8122      * Preferred network mode is NR 5G, LTE and WCDMA.
8123      * @hide
8124      */
8125     public static final int NETWORK_MODE_NR_LTE_WCDMA = RILConstants.NETWORK_MODE_NR_LTE_WCDMA;
8126 
8127     /**
8128      * Preferred network mode is NR 5G, LTE and TDSCDMA.
8129      * @hide
8130      */
8131     public static final int NETWORK_MODE_NR_LTE_TDSCDMA = RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA;
8132 
8133     /**
8134      * Preferred network mode is NR 5G, LTE, TD-SCDMA and GSM.
8135      * @hide
8136      */
8137     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM =
8138             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM;
8139 
8140     /**
8141      * Preferred network mode is NR 5G, LTE, TD-SCDMA, WCDMA.
8142      * @hide
8143      */
8144     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA =
8145             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA;
8146 
8147     /**
8148      * Preferred network mode is NR 5G, LTE, TD-SCDMA, GSM and WCDMA.
8149      * @hide
8150      */
8151     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA =
8152             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_GSM_WCDMA;
8153 
8154     /**
8155      * Preferred network mode is NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA.
8156      * @hide
8157      */
8158     public static final int NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA =
8159             RILConstants.NETWORK_MODE_NR_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA;
8160 
8161     /**
8162      * The default preferred network mode constant.
8163      *
8164      * <p> This constant is used in case of nothing is set in
8165      * TelephonyProperties#default_network().
8166      *
8167      * @hide
8168      */
8169     public static final int DEFAULT_PREFERRED_NETWORK_MODE =
8170             RILConstants.PREFERRED_NETWORK_MODE;
8171 
8172     /**
8173      * Get the preferred network type.
8174      * Used for device configuration by some CDMA operators.
8175      *
8176      * <p>Requires Permission:
8177      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8178      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8179      *
8180      * @return the preferred network type.
8181      * @hide
8182      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
8183      */
8184     @Deprecated
8185     @RequiresPermission((android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE))
8186     @UnsupportedAppUsage
getPreferredNetworkType(int subId)8187     public @PrefNetworkMode int getPreferredNetworkType(int subId) {
8188         return RadioAccessFamily.getNetworkTypeFromRaf((int) getAllowedNetworkTypesBitmask());
8189     }
8190 
8191     /**
8192      * Get the preferred network type bitmask.
8193      *
8194      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8195      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8196      *
8197      * <p>Requires Permission:
8198      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8199      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8200      *
8201      * @return The bitmask of preferred network types.
8202      *
8203      * @hide
8204      * @deprecated Use {@link #getAllowedNetworkTypesBitmask} instead.
8205      */
8206     @Deprecated
8207     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8208     @SystemApi
getPreferredNetworkTypeBitmask()8209     public @NetworkTypeBitMask long getPreferredNetworkTypeBitmask() {
8210         return getAllowedNetworkTypesBitmask();
8211     }
8212 
8213     /**
8214      * Get the allowed network type bitmask.
8215      * Note that the device can only register on the network of {@link NetworkTypeBitmask}
8216      * (except for emergency call cases).
8217      *
8218      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8219      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8220      *
8221      * <p>Requires Permission:
8222      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8223      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8224      *
8225      * @return The bitmask of allowed network types.
8226      *
8227      * @hide
8228      */
8229     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8230     @SystemApi
getAllowedNetworkTypesBitmask()8231     public @NetworkTypeBitMask long getAllowedNetworkTypesBitmask() {
8232         try {
8233             ITelephony telephony = getITelephony();
8234             if (telephony != null) {
8235                 return (long) telephony.getAllowedNetworkTypesBitmask(getSubId());
8236             }
8237         } catch (RemoteException ex) {
8238             Rlog.e(TAG, "getAllowedNetworkTypesBitmask RemoteException", ex);
8239         }
8240         return 0;
8241     }
8242 
8243     /**
8244      * Get the allowed network types by carriers.
8245      *
8246      * <p>Requires Permission:
8247      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
8248      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8249      *
8250      * @return the allowed network type bitmask
8251      * @hide
8252      * @deprecated Use {@link #getAllowedNetworkTypesForReason} instead.
8253      */
8254     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8255     @SystemApi
8256     @Deprecated
getAllowedNetworkTypes()8257     public @NetworkTypeBitMask long getAllowedNetworkTypes() {
8258         try {
8259             ITelephony telephony = getITelephony();
8260             if (telephony != null) {
8261                 return telephony.getAllowedNetworkTypesForReason(getSubId(),
8262                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER);
8263             }
8264         } catch (RemoteException ex) {
8265             Rlog.e(TAG, "getAllowedNetworkTypes RemoteException", ex);
8266         }
8267         return -1;
8268     }
8269 
8270     /**
8271      * Sets the network selection mode to automatic.
8272      *
8273      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8274      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8275      *
8276      * <p>Requires Permission:
8277      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8278      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8279      */
8280     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8281     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeAutomatic()8282     public void setNetworkSelectionModeAutomatic() {
8283         try {
8284             ITelephony telephony = getITelephony();
8285             if (telephony != null) {
8286                 telephony.setNetworkSelectionModeAutomatic(getSubId());
8287             }
8288         } catch (RemoteException ex) {
8289             Rlog.e(TAG, "setNetworkSelectionModeAutomatic RemoteException", ex);
8290         } catch (NullPointerException ex) {
8291             Rlog.e(TAG, "setNetworkSelectionModeAutomatic NPE", ex);
8292         }
8293     }
8294 
8295     /**
8296      * Perform a radio scan and return the list of available networks.
8297      *
8298      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8299      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8300      *
8301      * <p> Note that this scan can take a long time (sometimes minutes) to happen.
8302      *
8303      * <p>Requires Permissions:
8304      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
8305      * privileges (see {@link #hasCarrierPrivileges})
8306      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
8307      *
8308      * @return {@link CellNetworkScanResult} with the status
8309      * {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
8310      * {@link com.android.internal.telephony.OperatorInfo} if it's available. Otherwise, the failure
8311      * caused will be included in the result.
8312      *
8313      * @hide
8314      */
8315     @RequiresPermission(allOf = {
8316             android.Manifest.permission.MODIFY_PHONE_STATE,
8317             Manifest.permission.ACCESS_COARSE_LOCATION
8318     })
getAvailableNetworks()8319     public CellNetworkScanResult getAvailableNetworks() {
8320         try {
8321             ITelephony telephony = getITelephony();
8322             if (telephony != null) {
8323                 return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
8324                         getAttributionTag());
8325             }
8326         } catch (RemoteException ex) {
8327             Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
8328         } catch (NullPointerException ex) {
8329             Rlog.e(TAG, "getAvailableNetworks NPE", ex);
8330         }
8331         return new CellNetworkScanResult(
8332                 CellNetworkScanResult.STATUS_UNKNOWN_ERROR, null /* OperatorInfo */);
8333     }
8334 
8335     /**
8336      * Request a network scan.
8337      *
8338      * This method is asynchronous, so the network scan results will be returned by callback.
8339      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
8340      *
8341      * <p>Requires Permission:
8342      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8343      * app has carrier privileges (see {@link #hasCarrierPrivileges})
8344      * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
8345      *
8346      * If the system-wide location switch is off, apps may still call this API, with the
8347      * following constraints:
8348      * <ol>
8349      *     <li>The app must hold the {@code android.permission.NETWORK_SCAN} permission.</li>
8350      *     <li>The app must not supply any specific bands or channels to scan.</li>
8351      *     <li>The app must only specify MCC/MNC pairs that are
8352      *     associated to a SIM in the device.</li>
8353      *     <li>Returned results will have no meaningful info other than signal strength
8354      *     and MCC/MNC info.</li>
8355      * </ol>
8356      *
8357      * @param request Contains all the RAT with bands/channels that need to be scanned.
8358      * @param executor The executor through which the callback should be invoked. Since the scan
8359      *        request may trigger multiple callbacks and they must be invoked in the same order as
8360      *        they are received by the platform, the user should provide an executor which executes
8361      *        tasks one at a time in serial order. For example AsyncTask.SERIAL_EXECUTOR.
8362      * @param callback Returns network scan results or errors.
8363      * @return A NetworkScan obj which contains a callback which can be used to stop the scan.
8364      */
8365     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8366     @RequiresPermission(allOf = {
8367             android.Manifest.permission.MODIFY_PHONE_STATE,
8368             Manifest.permission.ACCESS_FINE_LOCATION
8369     })
requestNetworkScan( NetworkScanRequest request, Executor executor, TelephonyScanManager.NetworkScanCallback callback)8370     public NetworkScan requestNetworkScan(
8371             NetworkScanRequest request, Executor executor,
8372             TelephonyScanManager.NetworkScanCallback callback) {
8373         synchronized (this) {
8374             if (mTelephonyScanManager == null) {
8375                 mTelephonyScanManager = new TelephonyScanManager();
8376             }
8377         }
8378         return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback,
8379                 getOpPackageName(), getAttributionTag());
8380     }
8381 
8382     /**
8383      * @deprecated
8384      * Use {@link
8385      * #requestNetworkScan(NetworkScanRequest, Executor, TelephonyScanManager.NetworkScanCallback)}
8386      * @removed
8387      */
8388     @Deprecated
8389     @RequiresPermission(allOf = {
8390             android.Manifest.permission.MODIFY_PHONE_STATE,
8391             Manifest.permission.ACCESS_FINE_LOCATION
8392     })
requestNetworkScan( NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback)8393     public NetworkScan requestNetworkScan(
8394         NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
8395         return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
8396     }
8397 
8398     /**
8399      * Ask the radio to connect to the input network and change selection mode to manual.
8400      *
8401      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8402      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8403      *
8404      * <p>Requires Permission:
8405      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8406      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8407      *
8408      * @param operatorNumeric the PLMN ID of the network to select.
8409      * @param persistSelection whether the selection will persist until reboot. If true, only allows
8410      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
8411      * normal network selection next time.
8412      * @return {@code true} on success; {@code false} on any failure.
8413      */
8414     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
8415     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection)8416     public boolean setNetworkSelectionModeManual(String operatorNumeric, boolean persistSelection) {
8417         return setNetworkSelectionModeManual(
8418                 new OperatorInfo(
8419                         "" /* operatorAlphaLong */, "" /* operatorAlphaShort */, operatorNumeric),
8420                 persistSelection);
8421     }
8422 
8423     /**
8424      * Ask the radio to connect to the input network and change selection mode to manual.
8425      *
8426      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8427      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8428      *
8429      * <p>Requires Permission:
8430      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8431      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8432      *
8433      * @param operatorNumeric the PLMN ID of the network to select.
8434      * @param persistSelection whether the selection will persist until reboot.
8435      *         If true, only allows attaching to the selected PLMN until reboot; otherwise,
8436      *         attach to the chosen PLMN and resume normal network selection next time.
8437      * @param ran the initial suggested radio access network type.
8438      *         If registration fails, the RAN is not available after, the RAN is not within the
8439      *         network types specified by the preferred network types, or the value is
8440      *         {@link AccessNetworkConstants.AccessNetworkType#UNKNOWN}, modem will select
8441      *         the next best RAN for network registration.
8442      * @return {@code true} on success; {@code false} on any failure.
8443      */
8444     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual(@onNull String operatorNumeric, boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran)8445     public boolean setNetworkSelectionModeManual(@NonNull String operatorNumeric,
8446             boolean persistSelection, @AccessNetworkConstants.RadioAccessNetworkType int ran) {
8447         return setNetworkSelectionModeManual(new OperatorInfo("" /* operatorAlphaLong */,
8448                 "" /* operatorAlphaShort */, operatorNumeric, ran), persistSelection);
8449     }
8450 
8451     /**
8452      * Ask the radio to connect to the input network and change selection mode to manual.
8453      *
8454      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8455      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8456      *
8457      * <p>Requires Permission:
8458      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8459      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8460      *
8461      * @param operatorInfo included the PLMN id, long name, short name of the operator to attach to.
8462      * @param persistSelection whether the selection will persist until reboot. If true, only allows
8463      * attaching to the selected PLMN until reboot; otherwise, attach to the chosen PLMN and resume
8464      * normal network selection next time.
8465      * @return {@code true} on success; {@code true} on any failure.
8466      *
8467      * @hide
8468      */
8469     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setNetworkSelectionModeManual( OperatorInfo operatorInfo, boolean persistSelection)8470     public boolean setNetworkSelectionModeManual(
8471             OperatorInfo operatorInfo, boolean persistSelection) {
8472         try {
8473             ITelephony telephony = getITelephony();
8474             if (telephony != null) {
8475                 return telephony.setNetworkSelectionModeManual(
8476                         getSubId(), operatorInfo, persistSelection);
8477             }
8478         } catch (RemoteException ex) {
8479             Rlog.e(TAG, "setNetworkSelectionModeManual RemoteException", ex);
8480         }
8481         return false;
8482     }
8483 
8484     /**
8485      * Get the network selection mode.
8486      *
8487      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8488      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8489      *  <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
8490      * READ_PRECISE_PHONE_STATE}
8491      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8492      *
8493      * @return the network selection mode.
8494      */
8495     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
8496     @RequiresPermission(anyOf = {
8497             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
8498             android.Manifest.permission.READ_PRECISE_PHONE_STATE
8499     })
getNetworkSelectionMode()8500     public @NetworkSelectionMode int getNetworkSelectionMode() {
8501         int mode = NETWORK_SELECTION_MODE_UNKNOWN;
8502         try {
8503             ITelephony telephony = getITelephony();
8504             if (telephony != null) {
8505                 mode = telephony.getNetworkSelectionMode(getSubId());
8506             }
8507         } catch (RemoteException ex) {
8508             Rlog.e(TAG, "getNetworkSelectionMode RemoteException", ex);
8509         }
8510         return mode;
8511     }
8512 
8513     /**
8514      * Get the PLMN chosen for Manual Network Selection if active.
8515      * Return null string if in automatic selection.
8516      *
8517      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
8518      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
8519      * (see {@link #hasCarrierPrivileges})
8520      *
8521      * @return manually selected network info on success or null string on failure
8522      */
8523     @SuppressAutoDoc // No support carrier privileges (b/72967236).
8524     @RequiresPermission(android.Manifest.permission.READ_PRECISE_PHONE_STATE)
getManualNetworkSelectionPlmn()8525     public @NonNull String getManualNetworkSelectionPlmn() {
8526         try {
8527             ITelephony telephony = getITelephony();
8528             if (telephony != null && isManualNetworkSelectionAllowed()) {
8529                 return telephony.getManualNetworkSelectionPlmn(getSubId());
8530             }
8531         } catch (RemoteException ex) {
8532             Rlog.e(TAG, "getManualNetworkSelectionPlmn RemoteException", ex);
8533         }
8534         return null;
8535     }
8536 
8537     /**
8538      * Query Telephony to see if there has recently been an emergency SMS sent to the network by the
8539      * user and we are still within the time interval after the emergency SMS was sent that we are
8540      * considered in Emergency SMS mode.
8541      *
8542      * <p>This mode is used by other applications to allow them to perform special functionality,
8543      * such as allow the GNSS service to provide user location to the carrier network for emergency
8544      * when an emergency SMS is sent. This interval is set by
8545      * {@link CarrierConfigManager#KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT}. If
8546      * the carrier does not support this mode, this function will always return false.
8547      *
8548      * @return {@code true} if this device is in emergency SMS mode, {@code false} otherwise.
8549      *
8550      * @hide
8551      */
8552     @SystemApi
8553     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isInEmergencySmsMode()8554     public boolean isInEmergencySmsMode() {
8555         try {
8556             ITelephony telephony = getITelephony();
8557             if (telephony != null) {
8558                 return telephony.isInEmergencySmsMode();
8559             }
8560         } catch (RemoteException ex) {
8561             Rlog.e(TAG, "isInEmergencySmsMode RemoteException", ex);
8562         }
8563         return false;
8564     }
8565 
8566     /**
8567      * Set the preferred network type.
8568      *
8569      * <p>Requires Permission:
8570      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8571      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8572      * <p>
8573      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
8574      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
8575      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
8576      * setPreferredNetworkTypesBitmap is used instead.
8577      *
8578      * @param subId the id of the subscription to set the preferred network type for.
8579      * @param networkType the preferred network type
8580      * @return true on success; false on any failure.
8581      * @hide
8582      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
8583      */
8584     @Deprecated
8585     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setPreferredNetworkType(int subId, @PrefNetworkMode int networkType)8586     public boolean setPreferredNetworkType(int subId, @PrefNetworkMode int networkType) {
8587         try {
8588             ITelephony telephony = getITelephony();
8589             if (telephony != null) {
8590                 return telephony.setAllowedNetworkTypesForReason(subId,
8591                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
8592                         RadioAccessFamily.getRafFromNetworkType(networkType));
8593             }
8594         } catch (RemoteException ex) {
8595             Rlog.e(TAG, "setPreferredNetworkType RemoteException", ex);
8596         }
8597         return false;
8598     }
8599 
8600     /**
8601      * Set the preferred network type bitmask but if {@link #setAllowedNetworkTypes} has been set,
8602      * only the allowed network type will set to the modem.
8603      *
8604      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
8605      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
8606      *
8607      * <p>Requires Permission:
8608      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
8609      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
8610      * <p>
8611      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
8612      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
8613      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
8614      * setPreferredNetworkTypesBitmap is used instead.
8615      *
8616      * @param networkTypeBitmask The bitmask of preferred network types.
8617      * @return true on success; false on any failure.
8618      * @hide
8619      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
8620      */
8621     @Deprecated
8622     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8623     @SystemApi
setPreferredNetworkTypeBitmask(@etworkTypeBitMask long networkTypeBitmask)8624     public boolean setPreferredNetworkTypeBitmask(@NetworkTypeBitMask long networkTypeBitmask) {
8625         try {
8626             ITelephony telephony = getITelephony();
8627             if (telephony != null) {
8628                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
8629                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER, networkTypeBitmask);
8630             }
8631         } catch (RemoteException ex) {
8632             Rlog.e(TAG, "setPreferredNetworkTypeBitmask RemoteException", ex);
8633         }
8634         return false;
8635     }
8636 
8637     /**
8638      * Set the allowed network types of the device. This is for carrier or privileged apps to
8639      * enable/disable certain network types on the device. The user preferred network types should
8640      * be set through {@link #setPreferredNetworkTypeBitmask}.
8641      * <p>
8642      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
8643      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
8644      * setAllowedNetworkTypesBitmap is used on the radio interface.  Otherwise,
8645      * setPreferredNetworkTypesBitmap is used instead.
8646      *
8647      * @param allowedNetworkTypes The bitmask of allowed network types.
8648      * @return true on success; false on any failure.
8649      * @hide
8650      * @deprecated Use {@link #setAllowedNetworkTypesForReason} instead.
8651      */
8652     @Deprecated
8653     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8654     @RequiresFeature(
8655             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
8656             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
8657     @SystemApi
setAllowedNetworkTypes(@etworkTypeBitMask long allowedNetworkTypes)8658     public boolean setAllowedNetworkTypes(@NetworkTypeBitMask long allowedNetworkTypes) {
8659         try {
8660             ITelephony telephony = getITelephony();
8661             if (telephony != null) {
8662                 return telephony.setAllowedNetworkTypesForReason(getSubId(),
8663                         TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER, allowedNetworkTypes);
8664             }
8665         } catch (RemoteException ex) {
8666             Rlog.e(TAG, "setAllowedNetworkTypes RemoteException", ex);
8667         }
8668         return false;
8669     }
8670 
8671     /** @hide */
8672     @IntDef({
8673             ALLOWED_NETWORK_TYPES_REASON_USER,
8674             ALLOWED_NETWORK_TYPES_REASON_POWER,
8675             ALLOWED_NETWORK_TYPES_REASON_CARRIER,
8676             ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G
8677     })
8678     @Retention(RetentionPolicy.SOURCE)
8679     public @interface AllowedNetworkTypesReason {
8680     }
8681 
8682     /**
8683      * To indicate allowed network type change is requested by user.
8684      *
8685      * @hide
8686      */
8687     @SystemApi
8688     public static final int ALLOWED_NETWORK_TYPES_REASON_USER = 0;
8689 
8690     /**
8691      * To indicate allowed network type change is requested by power manager.
8692      * Power Manger configuration won't affect the settings configured through
8693      * other reasons and will result in allowing network types that are in both
8694      * configurations (i.e intersection of both sets).
8695      *
8696      * @hide
8697      */
8698     @SystemApi
8699     public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 1;
8700 
8701     /**
8702      * To indicate allowed network type change is requested by carrier.
8703      * Carrier configuration won't affect the settings configured through
8704      * other reasons and will result in allowing network types that are in both
8705      * configurations (i.e intersection of both sets).
8706      *
8707      * @hide
8708      */
8709     @SystemApi
8710     public static final int ALLOWED_NETWORK_TYPES_REASON_CARRIER = 2;
8711 
8712     /**
8713      * To indicate allowed network type change is requested by the user via the 2G toggle.
8714      *
8715      * @hide
8716      */
8717     @SystemApi
8718     public static final int ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G = 3;
8719 
8720     /**
8721      * Set the allowed network types of the device and provide the reason triggering the allowed
8722      * network change.
8723      * This can be called for following reasons
8724      * <ol>
8725      * <li>Allowed network types control by USER {@link #ALLOWED_NETWORK_TYPES_REASON_USER}
8726      * <li>Allowed network types control by power manager
8727      * {@link #ALLOWED_NETWORK_TYPES_REASON_POWER}
8728      * <li>Allowed network types control by carrier {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}
8729      * <li>Allowed network types control by the user-controlled "Allow 2G" toggle
8730      * {@link #ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G}
8731      * </ol>
8732      * This API will result in allowing an intersection of allowed network types for all reasons,
8733      * including the configuration done through other reasons.
8734      *
8735      * The functionality of this API with the parameter
8736      * {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER} is the same as the API
8737      * {@link TelephonyManager#setAllowedNetworkTypes}. Use this API instead of
8738      * {@link TelephonyManager#setAllowedNetworkTypes}.
8739      * <p>
8740      * If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
8741      * ({@link TelephonyManager#CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK}) returns true, then
8742      * setAllowedNetworkTypesBitmap is used on the radio interface. Otherwise,
8743      * setPreferredNetworkTypesBitmap is used instead.
8744      *
8745      * @param reason the reason the allowed network type change is taking place
8746      * @param allowedNetworkTypes The bitmask of allowed network types.
8747      * @throws IllegalStateException if the Telephony process is not currently available.
8748      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8749      * @hide
8750      */
8751     @SystemApi
8752     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8753     @RequiresFeature(
8754             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
8755             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
setAllowedNetworkTypesForReason(@llowedNetworkTypesReason int reason, @NetworkTypeBitMask long allowedNetworkTypes)8756     public void setAllowedNetworkTypesForReason(@AllowedNetworkTypesReason int reason,
8757             @NetworkTypeBitMask long allowedNetworkTypes) {
8758         if (!isValidAllowedNetworkTypesReason(reason)) {
8759             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8760         }
8761 
8762         try {
8763             ITelephony telephony = getITelephony();
8764             if (telephony != null) {
8765                 telephony.setAllowedNetworkTypesForReason(getSubId(), reason,
8766                         allowedNetworkTypes);
8767             } else {
8768                 throw new IllegalStateException("telephony service is null.");
8769             }
8770         } catch (RemoteException ex) {
8771             Rlog.e(TAG, "setAllowedNetworkTypesForReason RemoteException", ex);
8772             ex.rethrowFromSystemServer();
8773         }
8774     }
8775 
8776     /**
8777      * Get the allowed network types for certain reason.
8778      *
8779      * {@link #getAllowedNetworkTypesForReason} returns allowed network type for a
8780      * specific reason.
8781      *
8782      * @param reason the reason the allowed network type change is taking place
8783      * @return the allowed network type bitmask
8784      * @throws IllegalStateException    if the Telephony process is not currently available.
8785      * @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
8786      * @hide
8787      */
8788     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
8789     @RequiresFeature(
8790             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
8791             value = TelephonyManager.CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK)
8792     @SystemApi
getAllowedNetworkTypesForReason( @llowedNetworkTypesReason int reason)8793     public @NetworkTypeBitMask long getAllowedNetworkTypesForReason(
8794             @AllowedNetworkTypesReason int reason) {
8795         if (!isValidAllowedNetworkTypesReason(reason)) {
8796             throw new IllegalArgumentException("invalid AllowedNetworkTypesReason.");
8797         }
8798 
8799         try {
8800             ITelephony telephony = getITelephony();
8801             if (telephony != null) {
8802                 return telephony.getAllowedNetworkTypesForReason(getSubId(), reason);
8803             } else {
8804                 throw new IllegalStateException("telephony service is null.");
8805             }
8806         } catch (RemoteException ex) {
8807             Rlog.e(TAG, "getAllowedNetworkTypesForReason RemoteException", ex);
8808             ex.rethrowFromSystemServer();
8809         }
8810         return -1;
8811     }
8812     /**
8813      * Verifies that the reason provided is valid.
8814      * @hide
8815      */
isValidAllowedNetworkTypesReason(@llowedNetworkTypesReason int reason)8816     public static boolean isValidAllowedNetworkTypesReason(@AllowedNetworkTypesReason int reason) {
8817         switch (reason) {
8818             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER:
8819             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER:
8820             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER:
8821             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G:
8822                 return true;
8823         }
8824         return false;
8825     }
8826     /**
8827      * Get bit mask of all network types.
8828      *
8829      * @return bit mask of all network types
8830      * @hide
8831      */
getAllNetworkTypesBitmask()8832     public static @NetworkTypeBitMask long getAllNetworkTypesBitmask() {
8833         return NETWORK_STANDARDS_FAMILY_BITMASK_3GPP | NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2;
8834     }
8835 
8836     /**
8837      * Returns a string representation of the allowed network types{@link NetworkTypeBitMask}.
8838      *
8839      * @param networkTypeBitmask The bitmask of allowed network types.
8840      * @return the name of the allowed network types
8841      * @hide
8842      */
convertNetworkTypeBitmaskToString( @etworkTypeBitMask long networkTypeBitmask)8843     public static String convertNetworkTypeBitmaskToString(
8844             @NetworkTypeBitMask long networkTypeBitmask) {
8845         String networkTypeName = IntStream.rangeClosed(NETWORK_TYPE_GPRS, NETWORK_TYPE_NR)
8846                 .filter(x -> {
8847                     return (networkTypeBitmask & getBitMaskForNetworkType(x))
8848                             == getBitMaskForNetworkType(x);
8849                 })
8850                 .mapToObj(x -> getNetworkTypeName(x))
8851                 .collect(Collectors.joining("|"));
8852         return TextUtils.isEmpty(networkTypeName) ? "UNKNOWN" : networkTypeName;
8853     }
8854 
8855     /**
8856      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8857      *
8858      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8859      *
8860      * @return true on success; false on any failure.
8861      */
setPreferredNetworkTypeToGlobal()8862     public boolean setPreferredNetworkTypeToGlobal() {
8863         return setPreferredNetworkTypeToGlobal(getSubId());
8864     }
8865 
8866     /**
8867      * Set the preferred network type to global mode which includes LTE, CDMA, EvDo and GSM/WCDMA.
8868      *
8869      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8870      *
8871      * @return true on success; false on any failure.
8872      * @hide
8873      */
setPreferredNetworkTypeToGlobal(int subId)8874     public boolean setPreferredNetworkTypeToGlobal(int subId) {
8875         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
8876     }
8877 
8878     /**
8879      * Check whether DUN APN is required for tethering.
8880      * <p>
8881      * Requires Permission: MODIFY_PHONE_STATE.
8882      *
8883      * @return {@code true} if DUN APN is required for tethering.
8884      * @hide
8885      */
8886     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
8887     @SystemApi
isTetheringApnRequired()8888     public boolean isTetheringApnRequired() {
8889         return isTetheringApnRequired(getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
8890     }
8891 
8892     /**
8893      * Check whether DUN APN is required for tethering with subId.
8894      *
8895      * @param subId the id of the subscription to require tethering.
8896      * @return {@code true} if DUN APN is required for tethering.
8897      * @hide
8898      */
isTetheringApnRequired(int subId)8899     public boolean isTetheringApnRequired(int subId) {
8900         try {
8901             ITelephony telephony = getITelephony();
8902             if (telephony != null)
8903                 return telephony.isTetheringApnRequiredForSubscriber(subId);
8904         } catch (RemoteException ex) {
8905             Rlog.e(TAG, "hasMatchedTetherApnSetting RemoteException", ex);
8906         } catch (NullPointerException ex) {
8907             Rlog.e(TAG, "hasMatchedTetherApnSetting NPE", ex);
8908         }
8909         return false;
8910     }
8911 
8912 
8913     /**
8914      * Values used to return status for hasCarrierPrivileges call.
8915      */
8916     /** @hide */ @SystemApi
8917     public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1;
8918     /** @hide */ @SystemApi
8919     public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0;
8920     /** @hide */ @SystemApi
8921     public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1;
8922     /** @hide */ @SystemApi
8923     public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2;
8924 
8925     /**
8926      * Has the calling application been granted carrier privileges by the carrier.
8927      *
8928      * If any of the packages in the calling UID has carrier privileges, the
8929      * call will return true. This access is granted by the owner of the UICC
8930      * card and does not depend on the registered carrier.
8931      *
8932      * Note that this API applies to both physical and embedded subscriptions and
8933      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
8934      *
8935      * @return true if the app has carrier privileges.
8936      */
hasCarrierPrivileges()8937     public boolean hasCarrierPrivileges() {
8938         return hasCarrierPrivileges(getSubId());
8939     }
8940 
8941     /**
8942      * Has the calling application been granted carrier privileges by the carrier.
8943      *
8944      * If any of the packages in the calling UID has carrier privileges, the
8945      * call will return true. This access is granted by the owner of the UICC
8946      * card and does not depend on the registered carrier.
8947      *
8948      * Note that this API applies to both physical and embedded subscriptions and
8949      * is a superset of the checks done in SubscriptionManager#canManageSubscription.
8950      *
8951      * @param subId The subscription to use.
8952      * @return true if the app has carrier privileges.
8953      * @hide
8954      */
hasCarrierPrivileges(int subId)8955     public boolean hasCarrierPrivileges(int subId) {
8956         try {
8957             ITelephony telephony = getITelephony();
8958             if (telephony != null) {
8959                 return telephony.getCarrierPrivilegeStatus(subId)
8960                         == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
8961             }
8962         } catch (RemoteException ex) {
8963             Rlog.e(TAG, "hasCarrierPrivileges RemoteException", ex);
8964         } catch (NullPointerException ex) {
8965             Rlog.e(TAG, "hasCarrierPrivileges NPE", ex);
8966         }
8967         return false;
8968     }
8969 
8970     /**
8971      * Override the branding for the current ICCID.
8972      *
8973      * Once set, whenever the SIM is present in the device, the service
8974      * provider name (SPN) and the operator name will both be replaced by the
8975      * brand value input. To unset the value, the same function should be
8976      * called with a null brand value.
8977      *
8978      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8979      *
8980      * @param brand The brand name to display/set.
8981      * @return true if the operation was executed correctly.
8982      */
setOperatorBrandOverride(String brand)8983     public boolean setOperatorBrandOverride(String brand) {
8984         return setOperatorBrandOverride(getSubId(), brand);
8985     }
8986 
8987     /**
8988      * Override the branding for the current ICCID.
8989      *
8990      * Once set, whenever the SIM is present in the device, the service
8991      * provider name (SPN) and the operator name will both be replaced by the
8992      * brand value input. To unset the value, the same function should be
8993      * called with a null brand value.
8994      *
8995      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
8996      *
8997      * @param subId The subscription to use.
8998      * @param brand The brand name to display/set.
8999      * @return true if the operation was executed correctly.
9000      * @hide
9001      */
setOperatorBrandOverride(int subId, String brand)9002     public boolean setOperatorBrandOverride(int subId, String brand) {
9003         try {
9004             ITelephony telephony = getITelephony();
9005             if (telephony != null)
9006                 return telephony.setOperatorBrandOverride(subId, brand);
9007         } catch (RemoteException ex) {
9008             Rlog.e(TAG, "setOperatorBrandOverride RemoteException", ex);
9009         } catch (NullPointerException ex) {
9010             Rlog.e(TAG, "setOperatorBrandOverride NPE", ex);
9011         }
9012         return false;
9013     }
9014 
9015     /**
9016      * Override the roaming preference for the current ICCID.
9017      *
9018      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
9019      * the platform's notion of a network operator being considered roaming or not.
9020      * The change only affects the ICCID that was active when this call was made.
9021      *
9022      * If null is passed as any of the input, the corresponding value is deleted.
9023      *
9024      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
9025      *
9026      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
9027      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
9028      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
9029      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
9030      * @return true if the operation was executed correctly.
9031      *
9032      * @hide
9033      */
9034     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)9035     public boolean setRoamingOverride(List<String> gsmRoamingList,
9036             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
9037             List<String> cdmaNonRoamingList) {
9038         return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
9039                 cdmaRoamingList, cdmaNonRoamingList);
9040     }
9041 
9042     /**
9043      * Override the roaming preference for the current ICCID.
9044      *
9045      * Using this call, the carrier app (see #hasCarrierPrivileges) can override
9046      * the platform's notion of a network operator being considered roaming or not.
9047      * The change only affects the ICCID that was active when this call was made.
9048      *
9049      * If null is passed as any of the input, the corresponding value is deleted.
9050      *
9051      * <p>Requires that the caller have carrier privilege. See #hasCarrierPrivileges.
9052      *
9053      * @param subId for which the roaming overrides apply.
9054      * @param gsmRoamingList - List of MCCMNCs to be considered roaming for 3GPP RATs.
9055      * @param gsmNonRoamingList - List of MCCMNCs to be considered not roaming for 3GPP RATs.
9056      * @param cdmaRoamingList - List of SIDs to be considered roaming for 3GPP2 RATs.
9057      * @param cdmaNonRoamingList - List of SIDs to be considered not roaming for 3GPP2 RATs.
9058      * @return true if the operation was executed correctly.
9059      *
9060      * @hide
9061      */
setRoamingOverride(int subId, List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)9062     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
9063             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
9064             List<String> cdmaNonRoamingList) {
9065         try {
9066             ITelephony telephony = getITelephony();
9067             if (telephony != null)
9068                 return telephony.setRoamingOverride(subId, gsmRoamingList, gsmNonRoamingList,
9069                         cdmaRoamingList, cdmaNonRoamingList);
9070         } catch (RemoteException ex) {
9071             Rlog.e(TAG, "setRoamingOverride RemoteException", ex);
9072         } catch (NullPointerException ex) {
9073             Rlog.e(TAG, "setRoamingOverride NPE", ex);
9074         }
9075         return false;
9076     }
9077 
9078     /**
9079      * Expose the rest of ITelephony to @SystemApi
9080      */
9081 
9082     /** @hide */
9083     @SystemApi
9084     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn()9085     public String getCdmaMdn() {
9086         return getCdmaMdn(getSubId());
9087     }
9088 
9089     /** @hide */
9090     @SystemApi
9091     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMdn(int subId)9092     public String getCdmaMdn(int subId) {
9093         try {
9094             ITelephony telephony = getITelephony();
9095             if (telephony == null)
9096                 return null;
9097             return telephony.getCdmaMdn(subId);
9098         } catch (RemoteException ex) {
9099             return null;
9100         } catch (NullPointerException ex) {
9101             return null;
9102         }
9103     }
9104 
9105     /** @hide */
9106     @SystemApi
9107     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin()9108     public String getCdmaMin() {
9109         return getCdmaMin(getSubId());
9110     }
9111 
9112     /** @hide */
9113     @SystemApi
9114     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getCdmaMin(int subId)9115     public String getCdmaMin(int subId) {
9116         try {
9117             ITelephony telephony = getITelephony();
9118             if (telephony == null)
9119                 return null;
9120             return telephony.getCdmaMin(subId);
9121         } catch (RemoteException ex) {
9122             return null;
9123         } catch (NullPointerException ex) {
9124             return null;
9125         }
9126     }
9127 
9128     /** @hide */
9129     @SystemApi
9130     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
checkCarrierPrivilegesForPackage(String pkgName)9131     public int checkCarrierPrivilegesForPackage(String pkgName) {
9132         try {
9133             ITelephony telephony = getITelephony();
9134             if (telephony != null)
9135                 return telephony.checkCarrierPrivilegesForPackage(getSubId(), pkgName);
9136         } catch (RemoteException ex) {
9137             Rlog.e(TAG, "checkCarrierPrivilegesForPackage RemoteException", ex);
9138         } catch (NullPointerException ex) {
9139             Rlog.e(TAG, "checkCarrierPrivilegesForPackage NPE", ex);
9140         }
9141         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
9142     }
9143 
9144     /** @hide */
9145     @SystemApi
9146     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
checkCarrierPrivilegesForPackageAnyPhone(String pkgName)9147     public int checkCarrierPrivilegesForPackageAnyPhone(String pkgName) {
9148         try {
9149             ITelephony telephony = getITelephony();
9150             if (telephony != null)
9151                 return telephony.checkCarrierPrivilegesForPackageAnyPhone(pkgName);
9152         } catch (RemoteException ex) {
9153             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone RemoteException", ex);
9154         } catch (NullPointerException ex) {
9155             Rlog.e(TAG, "checkCarrierPrivilegesForPackageAnyPhone NPE", ex);
9156         }
9157         return CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
9158     }
9159 
9160     /** @hide */
9161     @SystemApi
getCarrierPackageNamesForIntent(Intent intent)9162     public List<String> getCarrierPackageNamesForIntent(Intent intent) {
9163         return getCarrierPackageNamesForIntentAndPhone(intent, getPhoneId());
9164     }
9165 
9166     /** @hide */
9167     @SystemApi
9168     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId)9169     public List<String> getCarrierPackageNamesForIntentAndPhone(Intent intent, int phoneId) {
9170         try {
9171             ITelephony telephony = getITelephony();
9172             if (telephony != null)
9173                 return telephony.getCarrierPackageNamesForIntentAndPhone(intent, phoneId);
9174         } catch (RemoteException ex) {
9175             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone RemoteException", ex);
9176         } catch (NullPointerException ex) {
9177             Rlog.e(TAG, "getCarrierPackageNamesForIntentAndPhone NPE", ex);
9178         }
9179         return null;
9180     }
9181 
9182     /** @hide */
9183     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPackagesWithCarrierPrivileges()9184     public List<String> getPackagesWithCarrierPrivileges() {
9185         try {
9186             ITelephony telephony = getITelephony();
9187             if (telephony != null) {
9188                 return telephony.getPackagesWithCarrierPrivileges(getPhoneId());
9189             }
9190         } catch (RemoteException ex) {
9191             Rlog.e(TAG, "getPackagesWithCarrierPrivileges RemoteException", ex);
9192         } catch (NullPointerException ex) {
9193             Rlog.e(TAG, "getPackagesWithCarrierPrivileges NPE", ex);
9194         }
9195         return Collections.EMPTY_LIST;
9196     }
9197 
9198     /**
9199      * Get the names of packages with carrier privileges for all the active subscriptions.
9200      *
9201      * @hide
9202      */
9203     @SystemApi
9204     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
9205     @NonNull
getCarrierPrivilegedPackagesForAllActiveSubscriptions()9206     public List<String> getCarrierPrivilegedPackagesForAllActiveSubscriptions() {
9207         try {
9208             ITelephony telephony = getITelephony();
9209             if (telephony != null) {
9210                 return telephony.getPackagesWithCarrierPrivilegesForAllPhones();
9211             }
9212         } catch (RemoteException ex) {
9213             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions RemoteException",
9214                     ex);
9215         } catch (NullPointerException ex) {
9216             Rlog.e(TAG, "getCarrierPrivilegedPackagesForAllActiveSubscriptions NPE", ex);
9217         }
9218         return Collections.EMPTY_LIST;
9219     }
9220 
9221     /**
9222      * Call composer status OFF from user setting.
9223      */
9224     public static final int CALL_COMPOSER_STATUS_OFF = 0;
9225 
9226     /**
9227      * Call composer status ON from user setting.
9228      */
9229     public static final int CALL_COMPOSER_STATUS_ON = 1;
9230 
9231     /** @hide */
9232     @IntDef(prefix = {"CALL_COMPOSER_STATUS_"},
9233             value = {
9234                 CALL_COMPOSER_STATUS_ON,
9235                 CALL_COMPOSER_STATUS_OFF,
9236             })
9237     public @interface CallComposerStatus {}
9238 
9239     /**
9240      * Set the user-set status for enriched calling with call composer.
9241      *
9242      * @param status user-set status for enriched calling with call composer.
9243      *
9244      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9245      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9246      *
9247      * @throws IllegalArgumentException if requested state is invalid.
9248      * @throws SecurityException if the caller does not have the permission.
9249      */
9250     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallComposerStatus(@allComposerStatus int status)9251     public void setCallComposerStatus(@CallComposerStatus int status) {
9252         if (status > CALL_COMPOSER_STATUS_ON
9253                 || status < CALL_COMPOSER_STATUS_OFF) {
9254             throw new IllegalArgumentException("requested status is invalid");
9255         }
9256         try {
9257             ITelephony telephony = getITelephony();
9258             if (telephony != null) {
9259                 telephony.setCallComposerStatus(getSubId(), status);
9260             }
9261         } catch (RemoteException ex) {
9262             Log.e(TAG, "Error calling ITelephony#setCallComposerStatus", ex);
9263             ex.rethrowFromSystemServer();
9264         }
9265     }
9266 
9267     /**
9268      * Get the user-set status for enriched calling with call composer.
9269      *
9270      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9271      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
9272      *
9273      * @throws SecurityException if the caller does not have the permission.
9274      *
9275      * @return the user-set status for enriched calling with call composer, either of
9276      * {@link #CALL_COMPOSER_STATUS_ON} or {@link #CALL_COMPOSER_STATUS_OFF}.
9277      */
9278     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCallComposerStatus()9279     public @CallComposerStatus int getCallComposerStatus() {
9280         try {
9281             ITelephony telephony = getITelephony();
9282             if (telephony != null) {
9283                 return telephony.getCallComposerStatus(getSubId());
9284             }
9285         } catch (RemoteException ex) {
9286             Log.e(TAG, "Error calling ITelephony#getCallComposerStatus", ex);
9287             ex.rethrowFromSystemServer();
9288         }
9289         return CALL_COMPOSER_STATUS_OFF;
9290     }
9291 
9292     /** @hide */
9293     @SystemApi
9294     @SuppressLint("RequiresPermission")
dial(String number)9295     public void dial(String number) {
9296         try {
9297             ITelephony telephony = getITelephony();
9298             if (telephony != null)
9299                 telephony.dial(number);
9300         } catch (RemoteException e) {
9301             Log.e(TAG, "Error calling ITelephony#dial", e);
9302         }
9303     }
9304 
9305     /**
9306      * @deprecated Use  {@link android.telecom.TelecomManager#placeCall(Uri address,
9307      * Bundle extras)} instead.
9308      * @hide
9309      */
9310     @Deprecated
9311     @SystemApi
9312     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
call(String callingPackage, String number)9313     public void call(String callingPackage, String number) {
9314         try {
9315             ITelephony telephony = getITelephony();
9316             if (telephony != null)
9317                 telephony.call(callingPackage, number);
9318         } catch (RemoteException e) {
9319             Log.e(TAG, "Error calling ITelephony#call", e);
9320         }
9321     }
9322 
9323     /**
9324      * @removed Use {@link android.telecom.TelecomManager#endCall()} instead.
9325      * @hide
9326      * @removed
9327      */
9328     @Deprecated
9329     @SystemApi
9330     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
endCall()9331     public boolean endCall() {
9332         return false;
9333     }
9334 
9335     /**
9336      * @removed Use {@link android.telecom.TelecomManager#acceptRingingCall} instead
9337      * @hide
9338      * @removed
9339      */
9340     @Deprecated
9341     @SystemApi
9342     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
answerRingingCall()9343     public void answerRingingCall() {
9344         // No-op
9345     }
9346 
9347     /**
9348      * @removed Use {@link android.telecom.TelecomManager#silenceRinger} instead
9349      * @hide
9350      */
9351     @Deprecated
9352     @SystemApi
9353     @SuppressLint("RequiresPermission")
silenceRinger()9354     public void silenceRinger() {
9355         // No-op
9356     }
9357 
9358     /**
9359      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
9360      * @hide
9361      */
9362     @Deprecated
9363     @SystemApi
9364     @RequiresPermission(anyOf = {
9365             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9366             android.Manifest.permission.READ_PHONE_STATE
9367     })
isOffhook()9368     public boolean isOffhook() {
9369         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
9370         return tm.isInCall();
9371     }
9372 
9373     /**
9374      * @deprecated Use {@link android.telecom.TelecomManager#isRinging} instead
9375      * @hide
9376      */
9377     @Deprecated
9378     @SystemApi
9379     @RequiresPermission(anyOf = {
9380             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9381             android.Manifest.permission.READ_PHONE_STATE
9382     })
isRinging()9383     public boolean isRinging() {
9384         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
9385         return tm.isRinging();
9386     }
9387 
9388     /**
9389      * @deprecated Use {@link android.telecom.TelecomManager#isInCall} instead
9390      * @hide
9391      */
9392     @Deprecated
9393     @SystemApi
9394     @RequiresPermission(anyOf = {
9395             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9396             android.Manifest.permission.READ_PHONE_STATE
9397     })
isIdle()9398     public boolean isIdle() {
9399         TelecomManager tm = (TelecomManager) mContext.getSystemService(TELECOM_SERVICE);
9400         return !tm.isInCall();
9401     }
9402 
9403     /**
9404      * @deprecated Use {@link android.telephony.TelephonyManager#getServiceState} instead
9405      * @hide
9406      */
9407     @Deprecated
9408     @SystemApi
9409     @RequiresPermission(anyOf = {
9410             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9411             android.Manifest.permission.READ_PHONE_STATE
9412     })
isRadioOn()9413     public boolean isRadioOn() {
9414         try {
9415             ITelephony telephony = getITelephony();
9416             if (telephony != null)
9417                 return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
9418         } catch (RemoteException e) {
9419             Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
9420         }
9421         return false;
9422     }
9423 
9424     /** @hide */
9425     @SystemApi
9426     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPin(String pin)9427     public boolean supplyPin(String pin) {
9428         try {
9429             ITelephony telephony = getITelephony();
9430             if (telephony != null)
9431                 return telephony.supplyPinForSubscriber(getSubId(), pin);
9432         } catch (RemoteException e) {
9433             Log.e(TAG, "Error calling ITelephony#supplyPinForSubscriber", e);
9434         }
9435         return false;
9436     }
9437 
9438     /** @hide */
9439     @SystemApi
9440     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyPuk(String puk, String pin)9441     public boolean supplyPuk(String puk, String pin) {
9442         try {
9443             ITelephony telephony = getITelephony();
9444             if (telephony != null)
9445                 return telephony.supplyPukForSubscriber(getSubId(), puk, pin);
9446         } catch (RemoteException e) {
9447             Log.e(TAG, "Error calling ITelephony#supplyPukForSubscriber", e);
9448         }
9449         return false;
9450     }
9451 
9452     /**
9453      * @deprecated use {@link #supplyIccLockPin(String)} instead.
9454      * @hide
9455      */
9456     @SystemApi
9457     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9458     @Deprecated
supplyPinReportResult(String pin)9459     public int[] supplyPinReportResult(String pin) {
9460         try {
9461             ITelephony telephony = getITelephony();
9462             if (telephony != null)
9463                 return telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
9464         } catch (RemoteException e) {
9465             Log.e(TAG, "Error calling ITelephony#supplyPinReportResultForSubscriber", e);
9466         }
9467         return new int[0];
9468     }
9469 
9470     /**
9471      * @deprecated use {@link #supplyIccLockPuk(String, String)} instead.
9472      * @hide
9473      */
9474     @SystemApi
9475     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
9476     @Deprecated
supplyPukReportResult(String puk, String pin)9477     public int[] supplyPukReportResult(String puk, String pin) {
9478         try {
9479             ITelephony telephony = getITelephony();
9480             if (telephony != null)
9481                 return telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
9482         } catch (RemoteException e) {
9483             Log.e(TAG, "Error calling ITelephony#supplyPukReportResultForSubscriber", e);
9484         }
9485         return new int[0];
9486     }
9487 
9488     /**
9489      * Supplies a PIN to unlock the ICC and returns the corresponding {@link PinResult}.
9490      * Used when the user enters their ICC unlock PIN to attempt an unlock.
9491      *
9492      * @param pin The user entered PIN.
9493      * @return The result of the PIN.
9494      * @throws SecurityException if the caller doesn't have the permission.
9495      * @throws IllegalStateException if the Telephony process is not currently available.
9496      *
9497      * <p>Requires Permission:
9498      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9499      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9500      *
9501      * @hide
9502      */
9503     @SystemApi
9504     @NonNull
9505     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyIccLockPin(@onNull String pin)9506     public PinResult supplyIccLockPin(@NonNull String pin) {
9507         try {
9508             ITelephony telephony = getITelephony();
9509             if (telephony != null) {
9510                 int[] result = telephony.supplyPinReportResultForSubscriber(getSubId(), pin);
9511                 return new PinResult(result[0], result[1]);
9512             } else {
9513                 throw new IllegalStateException("telephony service is null.");
9514             }
9515         } catch (RemoteException e) {
9516             Log.e(TAG, "Error calling ITelephony#supplyIccLockPin", e);
9517             e.rethrowFromSystemServer();
9518         }
9519         return PinResult.getDefaultFailedResult();
9520     }
9521 
9522     /**
9523      * Supplies a PUK and PIN to unlock the ICC and returns the corresponding {@link PinResult}.
9524      * Used when the user enters their ICC unlock PUK and PIN to attempt an unlock.
9525      *
9526      * @param puk The product unlocking key.
9527      * @param pin The user entered PIN.
9528      * @return The result of the PUK and PIN.
9529      * @throws SecurityException if the caller doesn't have the permission.
9530      * @throws IllegalStateException if the Telephony process is not currently available.
9531      *
9532      * <p>Requires Permission:
9533      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9534      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9535      *
9536      * @hide
9537      */
9538     @SystemApi
9539     @NonNull
9540     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
supplyIccLockPuk(@onNull String puk, @NonNull String pin)9541     public PinResult supplyIccLockPuk(@NonNull String puk, @NonNull String pin) {
9542         try {
9543             ITelephony telephony = getITelephony();
9544             if (telephony != null) {
9545                 int[] result = telephony.supplyPukReportResultForSubscriber(getSubId(), puk, pin);
9546                 return new PinResult(result[0], result[1]);
9547             } else {
9548                 throw new IllegalStateException("telephony service is null.");
9549             }
9550         } catch (RemoteException e) {
9551             Log.e(TAG, "Error calling ITelephony#supplyIccLockPuk", e);
9552             e.rethrowFromSystemServer();
9553         }
9554         return PinResult.getDefaultFailedResult();
9555     }
9556 
9557     /**
9558      * Used to notify callers of
9559      * {@link TelephonyManager#sendUssdRequest(String, UssdResponseCallback, Handler)} when the
9560      * network either successfully executes a USSD request, or if there was a failure while
9561      * executing the request.
9562      * <p>
9563      * {@link #onReceiveUssdResponse(TelephonyManager, String, CharSequence)} will be called if the
9564      * USSD request has succeeded.
9565      * {@link #onReceiveUssdResponseFailed(TelephonyManager, String, int)} will be called if the
9566      * USSD request has failed.
9567      */
9568     public static abstract class UssdResponseCallback {
9569        /**
9570         * Called when a USSD request has succeeded.  The {@code response} contains the USSD
9571         * response received from the network.  The calling app can choose to either display the
9572         * response to the user or perform some operation based on the response.
9573         * <p>
9574         * USSD responses are unstructured text and their content is determined by the mobile network
9575         * operator.
9576         *
9577         * @param telephonyManager the TelephonyManager the callback is registered to.
9578         * @param request the USSD request sent to the mobile network.
9579         * @param response the response to the USSD request provided by the mobile network.
9580         **/
onReceiveUssdResponse(final TelephonyManager telephonyManager, String request, CharSequence response)9581        public void onReceiveUssdResponse(final TelephonyManager telephonyManager,
9582                                          String request, CharSequence response) {};
9583 
9584        /**
9585         * Called when a USSD request has failed to complete.
9586         *
9587         * @param telephonyManager the TelephonyManager the callback is registered to.
9588         * @param request the USSD request sent to the mobile network.
9589         * @param failureCode failure code indicating why the request failed.  Will be either
9590         *        {@link TelephonyManager#USSD_RETURN_FAILURE} or
9591         *        {@link TelephonyManager#USSD_ERROR_SERVICE_UNAVAIL}.
9592         **/
onReceiveUssdResponseFailed(final TelephonyManager telephonyManager, String request, int failureCode)9593        public void onReceiveUssdResponseFailed(final TelephonyManager telephonyManager,
9594                                                String request, int failureCode) {};
9595     }
9596 
9597     /**
9598      * Sends an Unstructured Supplementary Service Data (USSD) request to the mobile network and
9599      * informs the caller of the response via the supplied {@code callback}.
9600      * <p>Carriers define USSD codes which can be sent by the user to request information such as
9601      * the user's current data balance or minutes balance.
9602      * <p>Requires permission:
9603      * {@link android.Manifest.permission#CALL_PHONE}
9604      * @param ussdRequest the USSD command to be executed.
9605      * @param callback called by the framework to inform the caller of the result of executing the
9606      *                 USSD request (see {@link UssdResponseCallback}).
9607      * @param handler the {@link Handler} to run the request on.
9608      */
9609     @RequiresPermission(android.Manifest.permission.CALL_PHONE)
sendUssdRequest(String ussdRequest, final UssdResponseCallback callback, Handler handler)9610     public void sendUssdRequest(String ussdRequest,
9611                                 final UssdResponseCallback callback, Handler handler) {
9612         checkNotNull(callback, "UssdResponseCallback cannot be null.");
9613         final TelephonyManager telephonyManager = this;
9614 
9615         ResultReceiver wrappedCallback = new ResultReceiver(handler) {
9616             @Override
9617             protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
9618                 Rlog.d(TAG, "USSD:" + resultCode);
9619                 checkNotNull(ussdResponse, "ussdResponse cannot be null.");
9620                 UssdResponse response = ussdResponse.getParcelable(USSD_RESPONSE);
9621 
9622                 if (resultCode == USSD_RETURN_SUCCESS) {
9623                     callback.onReceiveUssdResponse(telephonyManager, response.getUssdRequest(),
9624                             response.getReturnMessage());
9625                 } else {
9626                     callback.onReceiveUssdResponseFailed(telephonyManager,
9627                             response.getUssdRequest(), resultCode);
9628                 }
9629             }
9630         };
9631 
9632         try {
9633             ITelephony telephony = getITelephony();
9634             if (telephony != null) {
9635                 telephony.handleUssdRequest(getSubId(), ussdRequest, wrappedCallback);
9636             }
9637         } catch (RemoteException e) {
9638             Log.e(TAG, "Error calling ITelephony#sendUSSDCode", e);
9639             UssdResponse response = new UssdResponse(ussdRequest, "");
9640             Bundle returnData = new Bundle();
9641             returnData.putParcelable(USSD_RESPONSE, response);
9642             wrappedCallback.send(USSD_ERROR_SERVICE_UNAVAIL, returnData);
9643         }
9644     }
9645 
9646     /**
9647      * Whether the device is currently on a technology (e.g. UMTS or LTE) which can support
9648      * voice and data simultaneously. This can change based on location or network condition.
9649      *
9650      * @return {@code true} if simultaneous voice and data supported, and {@code false} otherwise.
9651      */
isConcurrentVoiceAndDataSupported()9652     public boolean isConcurrentVoiceAndDataSupported() {
9653         try {
9654             ITelephony telephony = getITelephony();
9655             return (telephony == null ? false : telephony.isConcurrentVoiceAndDataAllowed(
9656                     getSubId()));
9657         } catch (RemoteException e) {
9658             Log.e(TAG, "Error calling ITelephony#isConcurrentVoiceAndDataAllowed", e);
9659         }
9660         return false;
9661     }
9662 
9663     /** @hide */
9664     @SystemApi
9665     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmi(String dialString)9666     public boolean handlePinMmi(String dialString) {
9667         try {
9668             ITelephony telephony = getITelephony();
9669             if (telephony != null)
9670                 return telephony.handlePinMmi(dialString);
9671         } catch (RemoteException e) {
9672             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
9673         }
9674         return false;
9675     }
9676 
9677     /** @hide */
9678     @SystemApi
9679     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
handlePinMmiForSubscriber(int subId, String dialString)9680     public boolean handlePinMmiForSubscriber(int subId, String dialString) {
9681         try {
9682             ITelephony telephony = getITelephony();
9683             if (telephony != null)
9684                 return telephony.handlePinMmiForSubscriber(subId, dialString);
9685         } catch (RemoteException e) {
9686             Log.e(TAG, "Error calling ITelephony#handlePinMmi", e);
9687         }
9688         return false;
9689     }
9690 
9691     /** @hide */
9692     @SystemApi
9693     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
toggleRadioOnOff()9694     public void toggleRadioOnOff() {
9695         try {
9696             ITelephony telephony = getITelephony();
9697             if (telephony != null)
9698                 telephony.toggleRadioOnOff();
9699         } catch (RemoteException e) {
9700             Log.e(TAG, "Error calling ITelephony#toggleRadioOnOff", e);
9701         }
9702     }
9703 
9704     /** @hide */
9705     @SystemApi
9706     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadio(boolean turnOn)9707     public boolean setRadio(boolean turnOn) {
9708         try {
9709             ITelephony telephony = getITelephony();
9710             if (telephony != null)
9711                 return telephony.setRadio(turnOn);
9712         } catch (RemoteException e) {
9713             Log.e(TAG, "Error calling ITelephony#setRadio", e);
9714         }
9715         return false;
9716     }
9717 
9718     /** @hide */
9719     @SystemApi
9720     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioPower(boolean turnOn)9721     public boolean setRadioPower(boolean turnOn) {
9722         try {
9723             ITelephony telephony = getITelephony();
9724             if (telephony != null)
9725                 return telephony.setRadioPower(turnOn);
9726         } catch (RemoteException e) {
9727             Log.e(TAG, "Error calling ITelephony#setRadioPower", e);
9728         }
9729         return false;
9730     }
9731 
9732     /**
9733      * Shut down all the live radios over all the slot indexes.
9734      *
9735      * <p>To know when the radio has completed powering off, use
9736      * {@link PhoneStateListener#LISTEN_SERVICE_STATE LISTEN_SERVICE_STATE}.
9737      *
9738      * @hide
9739      */
9740     @SystemApi
9741     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
shutdownAllRadios()9742     public void shutdownAllRadios() {
9743         try {
9744             ITelephony telephony = getITelephony();
9745             if (telephony != null) {
9746                 telephony.shutdownMobileRadios();
9747             }
9748         } catch (RemoteException e) {
9749             Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
9750             e.rethrowAsRuntimeException();
9751         }
9752     }
9753 
9754     /**
9755      * Check if any radio is on over all the slot indexes.
9756      *
9757      * @return {@code true} if any radio is on over any slot index.
9758      * @hide
9759      */
9760     @SystemApi
9761     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isAnyRadioPoweredOn()9762     public boolean isAnyRadioPoweredOn() {
9763         try {
9764             ITelephony telephony = getITelephony();
9765             if (telephony != null) {
9766                 return telephony.needMobileRadioShutdown();
9767             }
9768         } catch (RemoteException e) {
9769             Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
9770             e.rethrowAsRuntimeException();
9771         }
9772         return false;
9773     }
9774 
9775     /**
9776      * Radio explicitly powered off (e.g, airplane mode).
9777      * @hide
9778      */
9779     @SystemApi
9780     public static final int RADIO_POWER_OFF = 0;
9781 
9782     /**
9783      * Radio power is on.
9784      * @hide
9785      */
9786     @SystemApi
9787     public static final int RADIO_POWER_ON = 1;
9788 
9789     /**
9790      * Radio power unavailable (eg, modem resetting or not booted).
9791      * @hide
9792      */
9793     @SystemApi
9794     public static final int RADIO_POWER_UNAVAILABLE = 2;
9795 
9796     /**
9797      * @return current modem radio state.
9798      *
9799      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
9800      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
9801      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9802      *
9803      * @hide
9804      */
9805     @SystemApi
9806     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
9807             android.Manifest.permission.READ_PHONE_STATE})
getRadioPowerState()9808     public @RadioPowerState int getRadioPowerState() {
9809         try {
9810             ITelephony telephony = getITelephony();
9811             if (telephony != null) {
9812                 return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
9813                         mContext.getAttributionTag());
9814             }
9815         } catch (RemoteException ex) {
9816             // This could happen if binder process crashes.
9817         }
9818         return RADIO_POWER_UNAVAILABLE;
9819     }
9820 
9821     /**
9822      * This method should not be used due to privacy and stability concerns.
9823      *
9824      * @hide
9825      */
9826     @SystemApi
updateServiceLocation()9827     public void updateServiceLocation() {
9828         Log.e(TAG, "Do not call TelephonyManager#updateServiceLocation()");
9829     }
9830 
9831     /** @hide */
9832     @SystemApi
9833     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableDataConnectivity()9834     public boolean enableDataConnectivity() {
9835         try {
9836             ITelephony telephony = getITelephony();
9837             if (telephony != null)
9838                 return telephony.enableDataConnectivity();
9839         } catch (RemoteException e) {
9840             Log.e(TAG, "Error calling ITelephony#enableDataConnectivity", e);
9841         }
9842         return false;
9843     }
9844 
9845     /** @hide */
9846     @SystemApi
9847     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
disableDataConnectivity()9848     public boolean disableDataConnectivity() {
9849         try {
9850             ITelephony telephony = getITelephony();
9851             if (telephony != null)
9852                 return telephony.disableDataConnectivity();
9853         } catch (RemoteException e) {
9854             Log.e(TAG, "Error calling ITelephony#disableDataConnectivity", e);
9855         }
9856         return false;
9857     }
9858 
9859     /** @hide */
9860     @SystemApi
isDataConnectivityPossible()9861     public boolean isDataConnectivityPossible() {
9862         try {
9863             ITelephony telephony = getITelephony();
9864             if (telephony != null)
9865                 return telephony.isDataConnectivityPossible(getSubId(SubscriptionManager
9866                         .getActiveDataSubscriptionId()));
9867         } catch (RemoteException e) {
9868             Log.e(TAG, "Error calling ITelephony#isDataAllowed", e);
9869         }
9870         return false;
9871     }
9872 
9873     /** @hide */
9874     @SystemApi
needsOtaServiceProvisioning()9875     public boolean needsOtaServiceProvisioning() {
9876         try {
9877             ITelephony telephony = getITelephony();
9878             if (telephony != null)
9879                 return telephony.needsOtaServiceProvisioning();
9880         } catch (RemoteException e) {
9881             Log.e(TAG, "Error calling ITelephony#needsOtaServiceProvisioning", e);
9882         }
9883         return false;
9884     }
9885 
9886     /**
9887      * Get the mobile provisioning url that is used to launch a browser to allow users to manage
9888      * their mobile plan.
9889      *
9890      * <p>Requires Permission:
9891      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}.
9892      *
9893      * TODO: The legacy design only supports single sim design. Ideally, this should support
9894      * multi-sim design in current world.
9895      *
9896      * {@hide}
9897      */
9898     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getMobileProvisioningUrl()9899     public @Nullable String getMobileProvisioningUrl() {
9900         try {
9901             final ITelephony service = getITelephony();
9902             if (service != null) {
9903                 return service.getMobileProvisioningUrl();
9904             } else {
9905                 throw new IllegalStateException("telephony service is null.");
9906             }
9907         } catch (RemoteException ex) {
9908             Rlog.e(TAG, "Telephony#getMobileProvisioningUrl RemoteException" + ex);
9909         }
9910         return null;
9911     }
9912 
9913     /**
9914      * Turns mobile data on or off.
9915      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9916      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9917      *
9918      * <p>Requires Permission:
9919      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
9920      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
9921      *
9922      * @param enable Whether to enable mobile data.
9923      * @deprecated use setDataEnabledForReason with reason DATA_ENABLED_REASON_USER instead.
9924      *
9925      */
9926     @Deprecated
9927     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
9928     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(boolean enable)9929     public void setDataEnabled(boolean enable) {
9930         setDataEnabled(getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enable);
9931     }
9932 
9933     /**
9934      * @hide
9935      * @deprecated use {@link #setDataEnabledForReason(int, boolean)} instead.
9936     */
9937     @SystemApi
9938     @Deprecated
9939     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabled(int subId, boolean enable)9940     public void setDataEnabled(int subId, boolean enable) {
9941         try {
9942             setDataEnabledForReason(subId, DATA_ENABLED_REASON_USER, enable);
9943         } catch (RuntimeException e) {
9944             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
9945         }
9946     }
9947 
9948     /**
9949      * @deprecated use {@link #isDataEnabled()} instead.
9950      * @hide
9951      */
9952     @SystemApi
9953     @Deprecated
getDataEnabled()9954     public boolean getDataEnabled() {
9955         return isDataEnabled();
9956     }
9957 
9958     /**
9959      * Returns whether mobile data is enabled or not per user setting. There are other factors
9960      * that could disable mobile data, but they are not considered here.
9961      *
9962      * If this object has been created with {@link #createForSubscriptionId}, applies to the given
9963      * subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9964      *
9965      * <p>Requires one of the following permissions:
9966      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9967      * {@link android.Manifest.permission#MODIFY_PHONE_STATE}, or that the calling app has carrier
9968      * privileges (see {@link #hasCarrierPrivileges}).
9969      *
9970      * <p>Note that this does not take into account any data restrictions that may be present on the
9971      * calling app. Such restrictions may be inspected with
9972      * {@link ConnectivityManager#getRestrictBackgroundStatus}.
9973      *
9974      * @return true if mobile data is enabled.
9975      */
9976     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
9977             android.Manifest.permission.MODIFY_PHONE_STATE,
9978             android.Manifest.permission.READ_PHONE_STATE})
isDataEnabled()9979     public boolean isDataEnabled() {
9980         try {
9981             return isDataEnabledForReason(DATA_ENABLED_REASON_USER);
9982         } catch (IllegalStateException ise) {
9983             // TODO(b/176163590): Remove this catch once TelephonyManager is booting safely.
9984             Log.e(TAG, "Error calling #isDataEnabled, returning default (false).", ise);
9985             return false;
9986         }
9987     }
9988 
9989     /**
9990      * Returns whether mobile data roaming is enabled on the subscription.
9991      *
9992      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
9993      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
9994      *
9995      * <p>Requires one of the following permissions:
9996      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE},
9997      * {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling app
9998      * has carrier privileges (see {@link #hasCarrierPrivileges}).
9999      *
10000      * @return {@code true} if the data roaming is enabled on the subscription, otherwise return
10001      * {@code false}.
10002      */
10003     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
10004             android.Manifest.permission.READ_PHONE_STATE})
isDataRoamingEnabled()10005     public boolean isDataRoamingEnabled() {
10006         boolean isDataRoamingEnabled = false;
10007         try {
10008             ITelephony telephony = getITelephony();
10009             if (telephony != null) {
10010                 isDataRoamingEnabled = telephony.isDataRoamingEnabled(
10011                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
10012             }
10013         } catch (RemoteException e) {
10014             Log.e(TAG, "Error calling ITelephony#isDataRoamingEnabled", e);
10015         }
10016         return isDataRoamingEnabled;
10017     }
10018 
10019     /**
10020      * Gets the roaming mode for CDMA phone.
10021      *
10022      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10023      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10024      *
10025      * @return the CDMA roaming mode.
10026      * @throws SecurityException if the caller does not have the permission.
10027      * @throws IllegalStateException if the Telephony process is not currently available.
10028      *
10029      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
10030      * @see #CDMA_ROAMING_MODE_HOME
10031      * @see #CDMA_ROAMING_MODE_AFFILIATED
10032      * @see #CDMA_ROAMING_MODE_ANY
10033      *
10034      * <p>Requires permission:
10035      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
10036      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10037      *
10038      * @hide
10039      */
10040     @SystemApi
10041     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaRoamingMode()10042     public @CdmaRoamingMode int getCdmaRoamingMode() {
10043         int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
10044         try {
10045             ITelephony telephony = getITelephony();
10046             if (telephony != null) {
10047                 mode = telephony.getCdmaRoamingMode(getSubId());
10048             } else {
10049                 throw new IllegalStateException("telephony service is null.");
10050             }
10051         } catch (RemoteException ex) {
10052             Log.e(TAG, "Error calling ITelephony#getCdmaRoamingMode", ex);
10053             ex.rethrowFromSystemServer();
10054         }
10055         return mode;
10056     }
10057 
10058     /**
10059      * Sets the roaming mode for CDMA phone to the given mode {@code mode}. If the phone is not
10060      * CDMA capable, this method throws an IllegalStateException.
10061      *
10062      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10063      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
10064      *
10065      * @param mode CDMA roaming mode.
10066      * @throws SecurityException if the caller does not have the permission.
10067      * @throws IllegalStateException if the Telephony process or radio is not currently available,
10068      *         the device is not CDMA capable, or the request fails.
10069      *
10070      * @see #CDMA_ROAMING_MODE_RADIO_DEFAULT
10071      * @see #CDMA_ROAMING_MODE_HOME
10072      * @see #CDMA_ROAMING_MODE_AFFILIATED
10073      * @see #CDMA_ROAMING_MODE_ANY
10074      *
10075      * <p>Requires Permission:
10076      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10077      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10078      *
10079      * @hide
10080      */
10081     @SystemApi
10082     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaRoamingMode(@dmaRoamingMode int mode)10083     public void setCdmaRoamingMode(@CdmaRoamingMode int mode) {
10084         if (getPhoneType() != PHONE_TYPE_CDMA) {
10085             throw new IllegalStateException("Phone does not support CDMA.");
10086         }
10087         try {
10088             ITelephony telephony = getITelephony();
10089             if (telephony != null) {
10090                 boolean result = telephony.setCdmaRoamingMode(getSubId(), mode);
10091                 if (!result) throw new IllegalStateException("radio is unavailable.");
10092             } else {
10093                 throw new IllegalStateException("telephony service is null.");
10094             }
10095         } catch (RemoteException ex) {
10096             Log.e(TAG, "Error calling ITelephony#setCdmaRoamingMode", ex);
10097             ex.rethrowFromSystemServer();
10098         }
10099     }
10100 
10101     /** @hide */
10102     @IntDef(prefix = { "CDMA_SUBSCRIPTION_" }, value = {
10103             CDMA_SUBSCRIPTION_UNKNOWN,
10104             CDMA_SUBSCRIPTION_RUIM_SIM,
10105             CDMA_SUBSCRIPTION_NV
10106     })
10107     @Retention(RetentionPolicy.SOURCE)
10108     public @interface CdmaSubscription{}
10109 
10110     /**
10111      * Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
10112      * @hide
10113      */
10114     @SystemApi
10115     public static final int CDMA_SUBSCRIPTION_UNKNOWN  = -1;
10116 
10117     /**
10118      * Used for CDMA subscription mode: RUIM/SIM (default)
10119      * @hide
10120      */
10121     @SystemApi
10122     public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
10123 
10124     /**
10125      * Used for CDMA subscription mode: NV -> non-volatile memory
10126      * @hide
10127      */
10128     @SystemApi
10129     public static final int CDMA_SUBSCRIPTION_NV       = 1;
10130 
10131     /**
10132      * Gets the subscription mode for CDMA phone.
10133      *
10134      * @return the CDMA subscription mode.
10135      * @throws SecurityException if the caller does not have the permission.
10136      * @throws IllegalStateException if the Telephony process or radio is not currently available.
10137      *
10138      * @see #CDMA_SUBSCRIPTION_UNKNOWN
10139      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
10140      * @see #CDMA_SUBSCRIPTION_NV
10141      *
10142      * <p>Requires Permission:
10143      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
10144      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
10145      *
10146      * @hide
10147      */
10148     @SystemApi
10149     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCdmaSubscriptionMode()10150     public @CdmaSubscription int getCdmaSubscriptionMode() {
10151         int mode = CDMA_SUBSCRIPTION_RUIM_SIM;
10152         try {
10153             ITelephony telephony = getITelephony();
10154             if (telephony != null) {
10155                 mode = telephony.getCdmaSubscriptionMode(getSubId());
10156             } else {
10157                 throw new IllegalStateException("telephony service is null.");
10158             }
10159         } catch (RemoteException ex) {
10160             Log.e(TAG, "Error calling ITelephony#getCdmaSubscriptionMode", ex);
10161             ex.rethrowFromSystemServer();
10162         }
10163         return mode;
10164     }
10165 
10166     /**
10167      * Sets the subscription mode for CDMA phone to the given mode {@code mode}. If the phone is not
10168      * CDMA capable, this method throws an IllegalStateException.
10169      *
10170      * @param mode CDMA subscription mode.
10171      * @throws SecurityException if the caller does not have the permission.
10172      * @throws IllegalStateException if the Telephony process or radio is not currently available,
10173      *         the device is not CDMA capable, or the request fails.
10174      *
10175      * @see #CDMA_SUBSCRIPTION_UNKNOWN
10176      * @see #CDMA_SUBSCRIPTION_RUIM_SIM
10177      * @see #CDMA_SUBSCRIPTION_NV
10178      *
10179      * <p>Requires Permission:
10180      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
10181      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
10182      *
10183      * @hide
10184      */
10185     @SystemApi
10186     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCdmaSubscriptionMode(@dmaSubscription int mode)10187     public void setCdmaSubscriptionMode(@CdmaSubscription int mode) {
10188         if (getPhoneType() != PHONE_TYPE_CDMA) {
10189             throw new IllegalStateException("Phone does not support CDMA.");
10190         }
10191         try {
10192             ITelephony telephony = getITelephony();
10193             if (telephony != null) {
10194                 boolean result = telephony.setCdmaSubscriptionMode(getSubId(), mode);
10195                 if (!result) throw new IllegalStateException("radio is unavailable.");
10196             } else {
10197                 throw new IllegalStateException("telephony service is null.");
10198             }
10199         } catch (RemoteException ex) {
10200             Log.e(TAG, "Error calling ITelephony#setCdmaSubscriptionMode", ex);
10201             ex.rethrowFromSystemServer();
10202         }
10203     }
10204 
10205     /**
10206      * Enables/Disables the data roaming on the subscription.
10207      *
10208      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
10209      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
10210      *
10211      * <p> Requires permission:
10212      * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
10213      * privileges (see {@link #hasCarrierPrivileges}).
10214      *
10215      * @param isEnabled {@code true} to enable mobile data roaming, otherwise disable it.
10216      *
10217      * @hide
10218      */
10219     @SystemApi
10220     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setDataRoamingEnabled(boolean isEnabled)10221     public void setDataRoamingEnabled(boolean isEnabled) {
10222         try {
10223             ITelephony telephony = getITelephony();
10224             if (telephony != null) {
10225                 telephony.setDataRoamingEnabled(
10226                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), isEnabled);
10227             }
10228         } catch (RemoteException e) {
10229             Log.e(TAG, "Error calling ITelephony#setDataRoamingEnabled", e);
10230         }
10231     }
10232 
10233     /**
10234      * @deprecated use {@link #isDataEnabled()} instead.
10235      * @hide
10236      */
10237     @Deprecated
10238     @SystemApi
getDataEnabled(int subId)10239     public boolean getDataEnabled(int subId) {
10240         try {
10241             return isDataEnabledForReason(subId, DATA_ENABLED_REASON_USER);
10242         } catch (RuntimeException e) {
10243             Log.e(TAG, "Error calling isDataEnabledForReason e:" + e);
10244         }
10245         return false;
10246     }
10247 
10248     /**
10249      * Returns the result and response from RIL for oem request
10250      *
10251      * @param oemReq the data is sent to ril.
10252      * @param oemResp the respose data from RIL.
10253      * @return negative value request was not handled or get error
10254      *         0 request was handled succesfully, but no response data
10255      *         positive value success, data length of response
10256      * @hide
10257      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
10258      */
10259     @Deprecated
invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp)10260     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
10261         try {
10262             ITelephony telephony = getITelephony();
10263             if (telephony != null)
10264                 return telephony.invokeOemRilRequestRaw(oemReq, oemResp);
10265         } catch (RemoteException ex) {
10266         } catch (NullPointerException ex) {
10267         }
10268         return -1;
10269     }
10270 
10271     /**
10272      * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
10273      * instead.
10274      * @hide
10275      */
10276     @Deprecated
10277     @SystemApi
10278     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableVideoCalling(boolean enable)10279     public void enableVideoCalling(boolean enable) {
10280         try {
10281             ITelephony telephony = getITelephony();
10282             if (telephony != null)
10283                 telephony.enableVideoCalling(enable);
10284         } catch (RemoteException e) {
10285             Log.e(TAG, "Error calling ITelephony#enableVideoCalling", e);
10286         }
10287     }
10288 
10289     /**
10290      * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
10291      * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
10292      * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
10293      * determine if video calling is capable.
10294      * @hide
10295      */
10296     @Deprecated
10297     @SystemApi
10298     @RequiresPermission(anyOf = {
10299             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
10300             android.Manifest.permission.READ_PHONE_STATE
10301     })
isVideoCallingEnabled()10302     public boolean isVideoCallingEnabled() {
10303         try {
10304             ITelephony telephony = getITelephony();
10305             if (telephony != null)
10306                 return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
10307         } catch (RemoteException e) {
10308             Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
10309         }
10310         return false;
10311     }
10312 
10313     /**
10314      * Whether the device supports configuring the DTMF tone length.
10315      *
10316      * @return {@code true} if the DTMF tone length can be changed, and {@code false} otherwise.
10317      */
canChangeDtmfToneLength()10318     public boolean canChangeDtmfToneLength() {
10319         try {
10320             ITelephony telephony = getITelephony();
10321             if (telephony != null) {
10322                 return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
10323                         getAttributionTag());
10324             }
10325         } catch (RemoteException e) {
10326             Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
10327         } catch (SecurityException e) {
10328             Log.e(TAG, "Permission error calling ITelephony#canChangeDtmfToneLength", e);
10329         }
10330         return false;
10331     }
10332 
10333     /**
10334      * Whether the device is a world phone.
10335      *
10336      * @return {@code true} if the device is a world phone, and {@code false} otherwise.
10337      */
isWorldPhone()10338     public boolean isWorldPhone() {
10339         try {
10340             ITelephony telephony = getITelephony();
10341             if (telephony != null) {
10342                 return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
10343             }
10344         } catch (RemoteException e) {
10345             Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
10346         } catch (SecurityException e) {
10347             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
10348         }
10349         return false;
10350     }
10351 
10352     /**
10353      * @deprecated Use {@link TelecomManager#isTtySupported()} instead
10354      * Whether the phone supports TTY mode.
10355      *
10356      * @return {@code true} if the device supports TTY mode, and {@code false} otherwise.
10357      *
10358      */
10359     @Deprecated
isTtyModeSupported()10360     public boolean isTtyModeSupported() {
10361         try {
10362             TelecomManager telecomManager = null;
10363             if (mContext != null) {
10364                 telecomManager = mContext.getSystemService(TelecomManager.class);
10365             }
10366             if (telecomManager != null) {
10367                 return telecomManager.isTtySupported();
10368             }
10369         } catch (SecurityException e) {
10370             Log.e(TAG, "Permission error calling TelecomManager#isTtySupported", e);
10371         }
10372         return false;
10373     }
10374 
10375     /**
10376      * Determines whether the device currently supports RTT (Real-time text). Based both on carrier
10377      * support for the feature and device firmware support.
10378      *
10379      * @return {@code true} if the device and carrier both support RTT, {@code false} otherwise.
10380      */
isRttSupported()10381     public boolean isRttSupported() {
10382         try {
10383             ITelephony telephony = getITelephony();
10384             if (telephony != null) {
10385                 return telephony.isRttSupported(mSubId);
10386             }
10387         } catch (RemoteException e) {
10388             Log.e(TAG, "Error calling ITelephony#isRttSupported", e);
10389         } catch (SecurityException e) {
10390             Log.e(TAG, "Permission error calling ITelephony#isWorldPhone", e);
10391         }
10392         return false;
10393     }
10394     /**
10395      * Whether the phone supports hearing aid compatibility.
10396      *
10397      * @return {@code true} if the device supports hearing aid compatibility, and {@code false}
10398      * otherwise.
10399      */
isHearingAidCompatibilitySupported()10400     public boolean isHearingAidCompatibilitySupported() {
10401         try {
10402             ITelephony telephony = getITelephony();
10403             if (telephony != null) {
10404                 return telephony.isHearingAidCompatibilitySupported();
10405             }
10406         } catch (RemoteException e) {
10407             Log.e(TAG, "Error calling ITelephony#isHearingAidCompatibilitySupported", e);
10408         } catch (SecurityException e) {
10409             Log.e(TAG, "Permission error calling ITelephony#isHearingAidCompatibilitySupported", e);
10410         }
10411         return false;
10412     }
10413 
10414     /**
10415      * Returns the IMS Registration Status for a particular Subscription ID.
10416      *
10417      * @param subId Subscription ID
10418      * @return true if IMS status is registered, false if the IMS status is not registered or a
10419      * RemoteException occurred.
10420      * Use {@link ImsMmTelManager.RegistrationCallback} instead.
10421      * @hide
10422      */
isImsRegistered(int subId)10423     public boolean isImsRegistered(int subId) {
10424         try {
10425             return getITelephony().isImsRegistered(subId);
10426         } catch (RemoteException | NullPointerException ex) {
10427             return false;
10428         }
10429     }
10430 
10431     /**
10432      * Returns the IMS Registration Status for a particular Subscription ID, which is determined
10433      * when the TelephonyManager is created using {@link #createForSubscriptionId(int)}. If an
10434      * invalid subscription ID is used during creation, will the default subscription ID will be
10435      * used.
10436      *
10437      * @return true if IMS status is registered, false if the IMS status is not registered or a
10438      * RemoteException occurred.
10439      * @see SubscriptionManager#getDefaultSubscriptionId()
10440      * @hide
10441      */
10442     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
isImsRegistered()10443     public boolean isImsRegistered() {
10444        try {
10445            return getITelephony().isImsRegistered(getSubId());
10446        } catch (RemoteException | NullPointerException ex) {
10447            return false;
10448        }
10449     }
10450 
10451     /**
10452      * The current status of Voice over LTE for the subscription associated with this instance when
10453      * it was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
10454      * used during creation, the default subscription ID will be used.
10455      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
10456      * @see SubscriptionManager#getDefaultSubscriptionId()
10457      * <p>
10458      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
10459      * @hide
10460      */
10461     @UnsupportedAppUsage
isVolteAvailable()10462     public boolean isVolteAvailable() {
10463         try {
10464             return getITelephony().isAvailable(getSubId(),
10465                     MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
10466                     ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
10467         } catch (RemoteException | NullPointerException ex) {
10468             return false;
10469         }
10470     }
10471 
10472     /**
10473      * The availability of Video Telephony (VT) for the subscription ID specified when this instance
10474      * was created using {@link #createForSubscriptionId(int)}. If an invalid subscription ID was
10475      * used during creation, the default subscription ID will be used. To query the
10476      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
10477      * @return true if VT is available, or false if it is unavailable or unknown.
10478      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
10479      * @hide
10480      */
10481     @UnsupportedAppUsage
isVideoTelephonyAvailable()10482     public boolean isVideoTelephonyAvailable() {
10483         try {
10484             return getITelephony().isVideoTelephonyAvailable(getSubId());
10485         } catch (RemoteException | NullPointerException ex) {
10486             return false;
10487         }
10488     }
10489 
10490     /**
10491      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
10492      * @param subId the subscription ID.
10493      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
10494      * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
10495      * @hide
10496      */
10497     @UnsupportedAppUsage
isWifiCallingAvailable()10498     public boolean isWifiCallingAvailable() {
10499        try {
10500            return getITelephony().isWifiCallingAvailable(getSubId());
10501        } catch (RemoteException | NullPointerException ex) {
10502            return false;
10503        }
10504    }
10505 
10506     /**
10507      * The technology that IMS is registered for for the MMTEL feature.
10508      * @param subId subscription ID to get IMS registration technology for.
10509      * @return The IMS registration technology that IMS is registered to for the MMTEL feature.
10510      * Valid return results are:
10511      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} for LTE registration,
10512      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
10513      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_CROSS_SIM} for registration over
10514      *  other sim's internet, or
10515      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
10516      *  result is unavailable.
10517      *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
10518      *  @hide
10519      */
getImsRegTechnologyForMmTel()10520     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
10521         try {
10522             return getITelephony().getImsRegTechnologyForMmTel(getSubId());
10523         } catch (RemoteException ex) {
10524             return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
10525         }
10526     }
10527 
10528    /**
10529     * Set TelephonyProperties.icc_operator_numeric for the default phone.
10530     *
10531     * @hide
10532     */
setSimOperatorNumeric(String numeric)10533     public void setSimOperatorNumeric(String numeric) {
10534         int phoneId = getPhoneId();
10535         setSimOperatorNumericForPhone(phoneId, numeric);
10536     }
10537 
10538    /**
10539     * Set TelephonyProperties.icc_operator_numeric for the given phone.
10540     *
10541     * @hide
10542     */
10543     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setSimOperatorNumericForPhone(int phoneId, String numeric)10544     public void setSimOperatorNumericForPhone(int phoneId, String numeric) {
10545         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10546             List<String> newList = updateTelephonyProperty(
10547                     TelephonyProperties.icc_operator_numeric(), phoneId, numeric);
10548             TelephonyProperties.icc_operator_numeric(newList);
10549         }
10550     }
10551 
10552     /**
10553      * Set TelephonyProperties.icc_operator_alpha for the default phone.
10554      *
10555      * @hide
10556      */
setSimOperatorName(String name)10557     public void setSimOperatorName(String name) {
10558         int phoneId = getPhoneId();
10559         setSimOperatorNameForPhone(phoneId, name);
10560     }
10561 
10562     /**
10563      * Set TelephonyProperties.icc_operator_alpha for the given phone.
10564      *
10565      * @hide
10566      */
10567     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimOperatorNameForPhone(int phoneId, String name)10568     public void setSimOperatorNameForPhone(int phoneId, String name) {
10569         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10570             List<String> newList = updateTelephonyProperty(
10571                     TelephonyProperties.icc_operator_alpha(), phoneId, name);
10572             TelephonyProperties.icc_operator_alpha(newList);
10573         }
10574     }
10575 
10576    /**
10577     * Set TelephonyProperties.icc_operator_iso_country for the default phone.
10578     *
10579     * @hide
10580     */
setSimCountryIso(String iso)10581     public void setSimCountryIso(String iso) {
10582         int phoneId = getPhoneId();
10583         setSimCountryIsoForPhone(phoneId, iso);
10584     }
10585 
10586    /**
10587     * Set TelephonyProperties.icc_operator_iso_country for the given phone.
10588     *
10589     * @hide
10590     */
10591     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimCountryIsoForPhone(int phoneId, String iso)10592     public void setSimCountryIsoForPhone(int phoneId, String iso) {
10593         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10594             List<String> newList = updateTelephonyProperty(
10595                     TelephonyProperties.icc_operator_iso_country(), phoneId, iso);
10596             TelephonyProperties.icc_operator_iso_country(newList);
10597         }
10598     }
10599 
10600     /**
10601      * Set TelephonyProperties.sim_state for the default phone.
10602      *
10603      * @hide
10604      */
setSimState(String state)10605     public void setSimState(String state) {
10606         int phoneId = getPhoneId();
10607         setSimStateForPhone(phoneId, state);
10608     }
10609 
10610     /**
10611      * Set TelephonyProperties.sim_state for the given phone.
10612      *
10613      * @hide
10614      */
10615     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setSimStateForPhone(int phoneId, String state)10616     public void setSimStateForPhone(int phoneId, String state) {
10617         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10618             List<String> newList = updateTelephonyProperty(
10619                     TelephonyProperties.sim_state(), phoneId, state);
10620             TelephonyProperties.sim_state(newList);
10621         }
10622     }
10623 
10624     /**
10625      * Powers down the SIM. SIM must be up prior.
10626      * @hide
10627      */
10628     public static final int CARD_POWER_DOWN = 0;
10629 
10630     /**
10631      * Powers up the SIM normally. SIM must be down prior.
10632      * @hide
10633      */
10634     public static final int CARD_POWER_UP = 1;
10635 
10636     /**
10637      * Powers up the SIM in PASS_THROUGH mode. SIM must be down prior.
10638      * When SIM is powered up in PASS_THOUGH mode, the modem does not send
10639      * any command to it (for example SELECT of MF, or TERMINAL CAPABILITY),
10640      * and the SIM card is controlled completely by Telephony sending APDUs
10641      * directly. The SIM card state will be RIL_CARDSTATE_PRESENT and the
10642      * number of card apps will be 0.
10643      * No new error code is generated. Emergency calls are supported in the
10644      * same way as if the SIM card is absent.
10645      * The PASS_THROUGH mode is valid only for the specific card session where it
10646      * is activated, and normal behavior occurs at the next SIM initialization,
10647      * unless PASS_THROUGH mode is requested again. Hence, the last power-up mode
10648      * is NOT persistent across boots. On reboot, SIM will power up normally.
10649      * @hide
10650      */
10651     public static final int CARD_POWER_UP_PASS_THROUGH = 2;
10652 
10653     /** @hide */
10654     @Retention(RetentionPolicy.SOURCE)
10655     @IntDef(prefix = {"CARD_POWER"},
10656             value = {
10657                     CARD_POWER_DOWN,
10658                     CARD_POWER_UP,
10659                     CARD_POWER_UP_PASS_THROUGH,
10660             })
10661     public @interface SimPowerState {}
10662 
10663     /**
10664      * Set SIM card power state.
10665      *
10666      * @param state  State of SIM (power down, power up, pass through)
10667      * @see #CARD_POWER_DOWN
10668      * @see #CARD_POWER_UP
10669      * @see #CARD_POWER_UP_PASS_THROUGH
10670      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
10671      * broadcasts to determine success or failure and timeout if needed.
10672      *
10673      * @deprecated prefer {@link setSimPowerState(int, Executor, Consumer<Integer>)}.
10674      * There is no guarantee that SIM power changes will trigger ACTION_SIM_STATE_CHANGED on new
10675      * devices.
10676      *
10677      * <p>Requires Permission:
10678      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10679      *
10680      * {@hide}
10681      **/
10682     @SystemApi
10683     @Deprecated
10684     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerState(int state)10685     public void setSimPowerState(int state) {
10686         setSimPowerStateForSlot(getSlotIndex(), state);
10687     }
10688 
10689     /**
10690      * Set SIM card power state.
10691      *
10692      * @param slotIndex SIM slot id
10693      * @param state  State of SIM (power down, power up, pass through)
10694      * @see #CARD_POWER_DOWN
10695      * @see #CARD_POWER_UP
10696      * @see #CARD_POWER_UP_PASS_THROUGH
10697      * Callers should monitor for {@link TelephonyIntents#ACTION_SIM_STATE_CHANGED}
10698      * broadcasts to determine success or failure and timeout if needed.
10699      *
10700      * @deprecated prefer {@link setSimPowerStateForSlot(int, int, Executor, Consumer<Integer>)}.
10701      * changes will trigger ACTION_SIM_STATE_CHANGED on new devices.
10702      *
10703      * <p>Requires Permission:
10704      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10705      *
10706      * {@hide}
10707      **/
10708     @SystemApi
10709     @Deprecated
10710     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerStateForSlot(int slotIndex, int state)10711     public void setSimPowerStateForSlot(int slotIndex, int state) {
10712         try {
10713             ITelephony telephony = getITelephony();
10714             if (telephony != null) {
10715                 telephony.setSimPowerStateForSlot(slotIndex, state);
10716             }
10717         } catch (RemoteException e) {
10718             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
10719         } catch (SecurityException e) {
10720             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot", e);
10721         }
10722     }
10723 
10724     /**
10725      * Set SIM card power state.
10726      *
10727      * @param state  State of SIM (power down, power up, pass through)
10728      * @see #CARD_POWER_DOWN
10729      * @see #CARD_POWER_UP
10730      * @see #CARD_POWER_UP_PASS_THROUGH
10731      * @param executor The executor of where the callback will execute.
10732      * @param callback Callback will be triggered once it succeeds or failed.
10733      * @see #SET_SIM_POWER_STATE_SUCCESS
10734      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
10735      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
10736      * @see #SET_SIM_POWER_STATE_SIM_ERROR
10737      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
10738      * @throws IllegalArgumentException if requested SIM state is invalid
10739      *
10740      * <p>Requires Permission:
10741      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10742      *
10743      * {@hide}
10744      **/
10745     @SystemApi
10746     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerState(@imPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)10747     public void setSimPowerState(@SimPowerState int state, @NonNull Executor executor,
10748             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
10749         setSimPowerStateForSlot(getSlotIndex(), state, executor, callback);
10750     }
10751 
10752     /**
10753      * Set SIM card power state.
10754      *
10755      * @param slotIndex SIM slot id
10756      * @param state  State of SIM (power down, power up, pass through)
10757      * @see #CARD_POWER_DOWN
10758      * @see #CARD_POWER_UP
10759      * @see #CARD_POWER_UP_PASS_THROUGH
10760      * @param executor The executor of where the callback will execute.
10761      * @param callback Callback will be triggered once it succeeds or failed.
10762      * @see #SET_SIM_POWER_STATE_SUCCESS
10763      * @see #SET_SIM_POWER_STATE_ALREADY_IN_STATE
10764      * @see #SET_SIM_POWER_STATE_MODEM_ERROR
10765      * @see #SET_SIM_POWER_STATE_SIM_ERROR
10766      * @see #SET_SIM_POWER_STATE_NOT_SUPPORTED
10767      * @throws IllegalArgumentException if requested SIM state is invalid
10768      *
10769      * <p>Requires Permission:
10770      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
10771      *
10772      * {@hide}
10773      **/
10774     @SystemApi
10775     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSimPowerStateForSlot(int slotIndex, @SimPowerState int state, @NonNull Executor executor, @NonNull @SetSimPowerStateResult Consumer<Integer> callback)10776     public void setSimPowerStateForSlot(int slotIndex, @SimPowerState int state,
10777             @NonNull Executor executor,
10778             @NonNull @SetSimPowerStateResult Consumer<Integer> callback) {
10779         if (state != CARD_POWER_DOWN && state != CARD_POWER_UP
10780                 && state != CARD_POWER_UP_PASS_THROUGH) {
10781             throw new IllegalArgumentException("requested SIM state is invalid");
10782         }
10783         try {
10784             ITelephony telephony = getITelephony();
10785             if (telephony == null) throw new IllegalStateException("Telephony is null.");
10786 
10787             IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
10788                 @Override
10789                 public void accept(int result) {
10790                     executor.execute(() ->
10791                             Binder.withCleanCallingIdentity(() -> callback.accept(result)));
10792                 }
10793             };
10794             if (telephony == null) {
10795                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
10796                     throw new IllegalStateException("Telephony is null");
10797                 } else {
10798                     return;
10799                 }
10800             }
10801             telephony.setSimPowerStateForSlotWithCallback(slotIndex, state, internalCallback);
10802         } catch (RemoteException e) {
10803             Log.e(TAG, "Error calling ITelephony#setSimPowerStateForSlot", e);
10804             runOnBackgroundThread(() -> executor.execute(
10805                     () -> callback.accept(SET_SIM_POWER_STATE_MODEM_ERROR)));
10806         } catch (SecurityException e) {
10807             Log.e(TAG, "Permission error calling ITelephony#setSimPowerStateForSlot",
10808                     e);
10809         }
10810     }
10811 
10812     /**
10813      * Set baseband version for the default phone.
10814      *
10815      * @param version baseband version
10816      * @hide
10817      */
setBasebandVersion(String version)10818     public void setBasebandVersion(String version) {
10819         int phoneId = getPhoneId();
10820         setBasebandVersionForPhone(phoneId, version);
10821     }
10822 
10823     /**
10824      * Set baseband version by phone id.
10825      *
10826      * @param phoneId for which baseband version is set
10827      * @param version baseband version
10828      * @hide
10829      */
10830     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setBasebandVersionForPhone(int phoneId, String version)10831     public void setBasebandVersionForPhone(int phoneId, String version) {
10832         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10833             List<String> newList = updateTelephonyProperty(
10834                     TelephonyProperties.baseband_version(), phoneId, version);
10835             TelephonyProperties.baseband_version(newList);
10836         }
10837     }
10838 
10839     /**
10840      * Get baseband version for the default phone.
10841      *
10842      * @return baseband version.
10843      * @hide
10844      */
getBasebandVersion()10845     public String getBasebandVersion() {
10846         int phoneId = getPhoneId();
10847         return getBasebandVersionForPhone(phoneId);
10848     }
10849 
10850     /**
10851      * Get baseband version by phone id.
10852      *
10853      * @return baseband version.
10854      * @hide
10855      */
getBasebandVersionForPhone(int phoneId)10856     public String getBasebandVersionForPhone(int phoneId) {
10857         return getTelephonyProperty(phoneId, TelephonyProperties.baseband_version(), "");
10858     }
10859 
10860     /**
10861      * Set phone type for the default phone.
10862      *
10863      * @param type phone type
10864      *
10865      * @hide
10866      */
setPhoneType(int type)10867     public void setPhoneType(int type) {
10868         int phoneId = getPhoneId();
10869         setPhoneType(phoneId, type);
10870     }
10871 
10872     /**
10873      * Set phone type by phone id.
10874      *
10875      * @param phoneId for which phone type is set
10876      * @param type phone type
10877      *
10878      * @hide
10879      */
10880     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setPhoneType(int phoneId, int type)10881     public void setPhoneType(int phoneId, int type) {
10882         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10883             List<Integer> newList = updateTelephonyProperty(
10884                     TelephonyProperties.current_active_phone(), phoneId, type);
10885             TelephonyProperties.current_active_phone(newList);
10886         }
10887     }
10888 
10889     /**
10890      * Get OTASP number schema for the default phone.
10891      *
10892      * @param defaultValue default value
10893      * @return OTA SP number schema
10894      *
10895      * @hide
10896      */
getOtaSpNumberSchema(String defaultValue)10897     public String getOtaSpNumberSchema(String defaultValue) {
10898         int phoneId = getPhoneId();
10899         return getOtaSpNumberSchemaForPhone(phoneId, defaultValue);
10900     }
10901 
10902     /**
10903      * Get OTASP number schema by phone id.
10904      *
10905      * @param phoneId for which OTA SP number schema is get
10906      * @param defaultValue default value
10907      * @return OTA SP number schema
10908      *
10909      * @hide
10910      */
10911     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue)10912     public String getOtaSpNumberSchemaForPhone(int phoneId, String defaultValue) {
10913         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10914             return getTelephonyProperty(
10915                     phoneId, TelephonyProperties.otasp_num_schema(), defaultValue);
10916         }
10917 
10918         return defaultValue;
10919     }
10920 
10921     /**
10922      * Get SMS receive capable from system property for the default phone.
10923      *
10924      * @param defaultValue default value
10925      * @return SMS receive capable
10926      *
10927      * @hide
10928      */
getSmsReceiveCapable(boolean defaultValue)10929     public boolean getSmsReceiveCapable(boolean defaultValue) {
10930         int phoneId = getPhoneId();
10931         return getSmsReceiveCapableForPhone(phoneId, defaultValue);
10932     }
10933 
10934     /**
10935      * Get SMS receive capable from system property by phone id.
10936      *
10937      * @param phoneId for which SMS receive capable is get
10938      * @param defaultValue default value
10939      * @return SMS receive capable
10940      *
10941      * @hide
10942      */
getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue)10943     public boolean getSmsReceiveCapableForPhone(int phoneId, boolean defaultValue) {
10944         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10945             return getTelephonyProperty(phoneId, TelephonyProperties.sms_receive(), defaultValue);
10946         }
10947 
10948         return defaultValue;
10949     }
10950 
10951     /**
10952      * Get SMS send capable from system property for the default phone.
10953      *
10954      * @param defaultValue default value
10955      * @return SMS send capable
10956      *
10957      * @hide
10958      */
getSmsSendCapable(boolean defaultValue)10959     public boolean getSmsSendCapable(boolean defaultValue) {
10960         int phoneId = getPhoneId();
10961         return getSmsSendCapableForPhone(phoneId, defaultValue);
10962     }
10963 
10964     /**
10965      * Get SMS send capable from system property by phone id.
10966      *
10967      * @param phoneId for which SMS send capable is get
10968      * @param defaultValue default value
10969      * @return SMS send capable
10970      *
10971      * @hide
10972      */
getSmsSendCapableForPhone(int phoneId, boolean defaultValue)10973     public boolean getSmsSendCapableForPhone(int phoneId, boolean defaultValue) {
10974         if (SubscriptionManager.isValidPhoneId(phoneId)) {
10975             return getTelephonyProperty(phoneId, TelephonyProperties.sms_send(), defaultValue);
10976         }
10977 
10978         return defaultValue;
10979     }
10980 
10981     /**
10982      * Gets the default Respond Via Message application, updating the cache if there is no
10983      * respond-via-message application currently configured.
10984      * @return component name of the app and class to direct Respond Via Message intent to, or
10985      * {@code null} if the functionality is not supported.
10986      * @hide
10987      */
10988     @SystemApi
10989     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
getAndUpdateDefaultRespondViaMessageApplication()10990     public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
10991         return SmsApplication.getDefaultRespondViaMessageApplication(mContext, true);
10992     }
10993 
10994     /**
10995      * Gets the default Respond Via Message application.
10996      * @return component name of the app and class to direct Respond Via Message intent to, or
10997      * {@code null} if the functionality is not supported.
10998      * @hide
10999      */
11000     @SystemApi
11001     @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
getDefaultRespondViaMessageApplication()11002     public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
11003         return SmsApplication.getDefaultRespondViaMessageApplication(mContext, false);
11004     }
11005 
11006     /**
11007      * Set the alphabetic name of current registered operator.
11008      * @param name the alphabetic name of current registered operator.
11009      * @hide
11010      */
setNetworkOperatorName(String name)11011     public void setNetworkOperatorName(String name) {
11012         int phoneId = getPhoneId();
11013         setNetworkOperatorNameForPhone(phoneId, name);
11014     }
11015 
11016     /**
11017      * Set the alphabetic name of current registered operator.
11018      * @param phoneId which phone you want to set
11019      * @param name the alphabetic name of current registered operator.
11020      * @hide
11021      */
11022     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNameForPhone(int phoneId, String name)11023     public void setNetworkOperatorNameForPhone(int phoneId, String name) {
11024         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11025             List<String> newList = updateTelephonyProperty(
11026                     TelephonyProperties.operator_alpha(), phoneId, name);
11027             TelephonyProperties.operator_alpha(newList);
11028         }
11029     }
11030 
11031     /**
11032      * Set the numeric name (MCC+MNC) of current registered operator.
11033      * @param operator the numeric name (MCC+MNC) of current registered operator
11034      * @hide
11035      */
setNetworkOperatorNumeric(String numeric)11036     public void setNetworkOperatorNumeric(String numeric) {
11037         int phoneId = getPhoneId();
11038         setNetworkOperatorNumericForPhone(phoneId, numeric);
11039     }
11040 
11041     /**
11042      * Set the numeric name (MCC+MNC) of current registered operator.
11043      * @param phoneId for which phone type is set
11044      * @param operator the numeric name (MCC+MNC) of current registered operator
11045      * @hide
11046      */
11047     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkOperatorNumericForPhone(int phoneId, String numeric)11048     public void setNetworkOperatorNumericForPhone(int phoneId, String numeric) {
11049         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11050             List<String> newList = updateTelephonyProperty(
11051                     TelephonyProperties.operator_numeric(), phoneId, numeric);
11052             TelephonyProperties.operator_numeric(newList);
11053         }
11054     }
11055 
11056     /**
11057      * Set roaming state of the current network, for GSM purposes.
11058      * @param isRoaming is network in romaing state or not
11059      * @hide
11060      */
setNetworkRoaming(boolean isRoaming)11061     public void setNetworkRoaming(boolean isRoaming) {
11062         int phoneId = getPhoneId();
11063         setNetworkRoamingForPhone(phoneId, isRoaming);
11064     }
11065 
11066     /**
11067      * Set roaming state of the current network, for GSM purposes.
11068      * @param phoneId which phone you want to set
11069      * @param isRoaming is network in romaing state or not
11070      * @hide
11071      */
11072     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setNetworkRoamingForPhone(int phoneId, boolean isRoaming)11073     public void setNetworkRoamingForPhone(int phoneId, boolean isRoaming) {
11074         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11075             List<Boolean> newList = updateTelephonyProperty(
11076                     TelephonyProperties.operator_is_roaming(), phoneId, isRoaming);
11077             TelephonyProperties.operator_is_roaming(newList);
11078         }
11079     }
11080 
11081     /**
11082      * Set the network type currently in use on the device for data transmission.
11083      *
11084      * If this object has been created with {@link #createForSubscriptionId}, applies to the
11085      * phoneId associated with the given subId. Otherwise, applies to the phoneId associated with
11086      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
11087      * @param type the network type currently in use on the device for data transmission
11088      * @hide
11089      */
setDataNetworkType(int type)11090     public void setDataNetworkType(int type) {
11091         int phoneId = getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
11092         setDataNetworkTypeForPhone(phoneId, type);
11093     }
11094 
11095     /**
11096      * Set the network type currently in use on the device for data transmission.
11097      * @param phoneId which phone you want to set
11098      * @param type the network type currently in use on the device for data transmission
11099      * @hide
11100      */
11101     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setDataNetworkTypeForPhone(int phoneId, int type)11102     public void setDataNetworkTypeForPhone(int phoneId, int type) {
11103         if (SubscriptionManager.isValidPhoneId(phoneId)) {
11104             List<String> newList = updateTelephonyProperty(
11105                     TelephonyProperties.data_network_type(), phoneId,
11106                     ServiceState.rilRadioTechnologyToString(type));
11107             TelephonyProperties.data_network_type(newList);
11108         }
11109     }
11110 
11111     /**
11112      * Returns the subscription ID for the given phone account.
11113      * @hide
11114      */
11115     @UnsupportedAppUsage
getSubIdForPhoneAccount(@ullable PhoneAccount phoneAccount)11116     public int getSubIdForPhoneAccount(@Nullable PhoneAccount phoneAccount) {
11117         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
11118         try {
11119             ITelephony service = getITelephony();
11120             if (service != null) {
11121                 retval = service.getSubIdForPhoneAccount(phoneAccount);
11122             }
11123         } catch (RemoteException e) {
11124         }
11125 
11126         return retval;
11127     }
11128 
11129     /**
11130      * Determines the {@link PhoneAccountHandle} associated with this TelephonyManager.
11131      *
11132      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11133      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11134      *
11135      * <p>Requires Permission android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE or that the
11136      * calling app has carrier privileges (see {@link #hasCarrierPrivileges})
11137      *
11138      * @return The {@link PhoneAccountHandle} associated with the TelphonyManager, or {@code null}
11139      * if there is no associated {@link PhoneAccountHandle}; this can happen if the subscription is
11140      * data-only or an opportunistic subscription.
11141      */
11142     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
11143     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPhoneAccountHandle()11144     public @Nullable PhoneAccountHandle getPhoneAccountHandle() {
11145         return getPhoneAccountHandleForSubscriptionId(getSubId());
11146     }
11147 
11148     /**
11149      * Determines the {@link PhoneAccountHandle} associated with a subscription Id.
11150      *
11151      * @param subscriptionId The subscription Id to check.
11152      * @return The {@link PhoneAccountHandle} associated with a subscription Id, or {@code null} if
11153      * there is no associated {@link PhoneAccountHandle}.
11154      * @hide
11155      */
getPhoneAccountHandleForSubscriptionId(int subscriptionId)11156     public @Nullable PhoneAccountHandle getPhoneAccountHandleForSubscriptionId(int subscriptionId) {
11157         PhoneAccountHandle returnValue = null;
11158         try {
11159             ITelephony service = getITelephony();
11160             if (service != null) {
11161                 returnValue = service.getPhoneAccountHandleForSubscriptionId(subscriptionId);
11162             }
11163         } catch (RemoteException e) {
11164         }
11165 
11166         return returnValue;
11167     }
11168 
11169     /**
11170      * Returns the subscription ID for the given phone account handle.
11171      *
11172      * @param phoneAccountHandle the phone account handle for outgoing calls
11173      * @return subscription ID for the given phone account handle; or
11174      *         {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID}
11175      *         if not available; or throw a SecurityException if the caller doesn't have the
11176      *         permission.
11177      */
11178     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getSubscriptionId(@onNull PhoneAccountHandle phoneAccountHandle)11179     public int getSubscriptionId(@NonNull PhoneAccountHandle phoneAccountHandle) {
11180         int retval = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
11181         try {
11182             ITelephony service = getITelephony();
11183             if (service != null) {
11184                 retval = service.getSubIdForPhoneAccountHandle(
11185                         phoneAccountHandle, mContext.getOpPackageName(),
11186                         mContext.getAttributionTag());
11187             }
11188         } catch (RemoteException ex) {
11189             Log.e(TAG, "getSubscriptionId RemoteException", ex);
11190             ex.rethrowAsRuntimeException();
11191         }
11192         return retval;
11193     }
11194 
11195     /**
11196      * Resets telephony manager settings back to factory defaults.
11197      *
11198      * @hide
11199      */
factoryReset(int subId)11200     public void factoryReset(int subId) {
11201         try {
11202             Log.d(TAG, "factoryReset: subId=" + subId);
11203             ITelephony telephony = getITelephony();
11204             if (telephony != null) {
11205                 telephony.factoryReset(subId);
11206             }
11207         } catch (RemoteException e) {
11208         }
11209     }
11210 
11211 
11212     /**
11213      * Resets Telephony and IMS settings back to factory defaults only for the subscription
11214      * associated with this instance.
11215      * @see #createForSubscriptionId(int)
11216      * @hide
11217      */
11218     @SystemApi
11219     @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL)
resetSettings()11220     public void resetSettings() {
11221         try {
11222             Log.d(TAG, "resetSettings: subId=" + getSubId());
11223             ITelephony telephony = getITelephony();
11224             if (telephony != null) {
11225                 telephony.factoryReset(getSubId());
11226             }
11227         } catch (RemoteException e) {
11228         }
11229     }
11230 
11231 
11232     /**
11233      * Returns a locale based on the country and language from the SIM. Returns {@code null} if
11234      * no locale could be derived from subscriptions.
11235      *
11236      * <p>Requires Permission:
11237      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
11238      *
11239      * @see Locale#toLanguageTag()
11240      *
11241      * @hide
11242      */
11243     @SystemApi
11244     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSimLocale()11245     @Nullable public Locale getSimLocale() {
11246         try {
11247             final ITelephony telephony = getITelephony();
11248             if (telephony != null) {
11249                 String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
11250                 if (!TextUtils.isEmpty(languageTag)) {
11251                     return Locale.forLanguageTag(languageTag);
11252                 }
11253             }
11254         } catch (RemoteException ex) {
11255         }
11256         return null;
11257     }
11258 
11259     /**
11260      * TODO delete after SuW migrates to new API.
11261      * @hide
11262      */
getLocaleFromDefaultSim()11263     public String getLocaleFromDefaultSim() {
11264         try {
11265             final ITelephony telephony = getITelephony();
11266             if (telephony != null) {
11267                 return telephony.getSimLocaleForSubscriber(getSubId());
11268             }
11269         } catch (RemoteException ex) {
11270         }
11271         return null;
11272     }
11273 
11274     /**
11275      * Exception that may be supplied to the callback provided in {@link #requestModemActivityInfo}.
11276      * @hide
11277      */
11278     @SystemApi
11279     public static class ModemActivityInfoException extends Exception {
11280         /** Indicates that an unknown error occurred */
11281         public static final int ERROR_UNKNOWN = 0;
11282 
11283         /**
11284          * Indicates that the modem or phone processes are not available (such as when the device
11285          * is in airplane mode).
11286          */
11287         public static final int ERROR_PHONE_NOT_AVAILABLE = 1;
11288 
11289         /**
11290          * Indicates that the modem supplied an invalid instance of {@link ModemActivityInfo}
11291          */
11292         public static final int ERROR_INVALID_INFO_RECEIVED = 2;
11293 
11294         /**
11295          * Indicates that the modem encountered an internal failure when processing the request
11296          * for activity info.
11297          */
11298         public static final int ERROR_MODEM_RESPONSE_ERROR = 3;
11299 
11300         /** @hide */
11301         @Retention(RetentionPolicy.SOURCE)
11302         @IntDef(prefix = {"ERROR_"},
11303                 value = {
11304                         ERROR_UNKNOWN,
11305                         ERROR_PHONE_NOT_AVAILABLE,
11306                         ERROR_INVALID_INFO_RECEIVED,
11307                         ERROR_MODEM_RESPONSE_ERROR,
11308                 })
11309         public @interface ModemActivityInfoError {}
11310 
11311         private final int mErrorCode;
11312 
11313         /** @hide */
ModemActivityInfoException(@odemActivityInfoError int errorCode)11314         public ModemActivityInfoException(@ModemActivityInfoError int errorCode) {
11315             mErrorCode = errorCode;
11316         }
11317 
getErrorCode()11318         public @ModemActivityInfoError int getErrorCode() {
11319             return mErrorCode;
11320         }
11321 
11322         @Override
toString()11323         public String toString() {
11324             switch (mErrorCode) {
11325                 case ERROR_UNKNOWN: return "ERROR_UNKNOWN";
11326                 case ERROR_PHONE_NOT_AVAILABLE: return "ERROR_PHONE_NOT_AVAILABLE";
11327                 case ERROR_INVALID_INFO_RECEIVED: return "ERROR_INVALID_INFO_RECEIVED";
11328                 case ERROR_MODEM_RESPONSE_ERROR: return "ERROR_MODEM_RESPONSE_ERROR";
11329                 default: return "UNDEFINED";
11330             }
11331         }
11332     }
11333 
11334     /**
11335      * Requests the current modem activity info.
11336      *
11337      * The provided instance of {@link ModemActivityInfo} represents the cumulative activity since
11338      * the last restart of the phone process.
11339      *
11340      * @param callback A callback object to which the result will be delivered. If there was an
11341      *                 error processing the request, {@link OutcomeReceiver#onError} will be called
11342      *                 with more details about the error.
11343      * @hide
11344      */
11345     @SystemApi
11346     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
requestModemActivityInfo(@onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback)11347     public void requestModemActivityInfo(@NonNull @CallbackExecutor Executor executor,
11348             @NonNull OutcomeReceiver<ModemActivityInfo, ModemActivityInfoException> callback) {
11349         Objects.requireNonNull(executor);
11350         Objects.requireNonNull(callback);
11351 
11352         // Pass no handler into the receiver, since we're going to be trampolining the call to the
11353         // listener onto the provided executor.
11354         ResultReceiver wrapperResultReceiver = new ResultReceiver(null) {
11355             @Override
11356             protected void onReceiveResult(int resultCode, Bundle data) {
11357                 if (data == null) {
11358                     Log.w(TAG, "requestModemActivityInfo: received null bundle");
11359                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
11360                     return;
11361                 }
11362                 data.setDefusable(true);
11363                 if (data.containsKey(EXCEPTION_RESULT_KEY)) {
11364                     int receivedErrorCode = data.getInt(EXCEPTION_RESULT_KEY);
11365                     sendErrorToListener(receivedErrorCode);
11366                     return;
11367                 }
11368 
11369                 if (!data.containsKey(MODEM_ACTIVITY_RESULT_KEY)) {
11370                     Log.w(TAG, "requestModemActivityInfo: Bundle did not contain expected key");
11371                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
11372                     return;
11373                 }
11374                 Parcelable receivedResult = data.getParcelable(MODEM_ACTIVITY_RESULT_KEY);
11375                 if (!(receivedResult instanceof ModemActivityInfo)) {
11376                     Log.w(TAG, "requestModemActivityInfo: Bundle contained something that wasn't "
11377                             + "a ModemActivityInfo.");
11378                     sendErrorToListener(ModemActivityInfoException.ERROR_UNKNOWN);
11379                     return;
11380                 }
11381                 ModemActivityInfo modemActivityInfo = (ModemActivityInfo) receivedResult;
11382                 if (!modemActivityInfo.isValid()) {
11383                     Log.w(TAG, "requestModemActivityInfo: Received an invalid ModemActivityInfo");
11384                     sendErrorToListener(ModemActivityInfoException.ERROR_INVALID_INFO_RECEIVED);
11385                     return;
11386                 }
11387                 Log.d(TAG, "requestModemActivityInfo: Sending result to app: " + modemActivityInfo);
11388                 sendResultToListener(modemActivityInfo);
11389             }
11390 
11391             private void sendResultToListener(ModemActivityInfo info) {
11392                 Binder.withCleanCallingIdentity(() ->
11393                         executor.execute(() ->
11394                                 callback.onResult(info)));
11395             }
11396 
11397             private void sendErrorToListener(int code) {
11398                 ModemActivityInfoException e = new ModemActivityInfoException(code);
11399                 Binder.withCleanCallingIdentity(() ->
11400                         executor.execute(() ->
11401                                 callback.onError(e)));
11402             }
11403         };
11404 
11405         try {
11406             ITelephony service = getITelephony();
11407             if (service != null) {
11408                 service.requestModemActivityInfo(wrapperResultReceiver);
11409                 return;
11410             }
11411         } catch (RemoteException e) {
11412             Log.e(TAG, "Error calling ITelephony#getModemActivityInfo", e);
11413         }
11414         executor.execute(() -> callback.onError(
11415                 new ModemActivityInfoException(
11416                         ModemActivityInfoException.ERROR_PHONE_NOT_AVAILABLE)));
11417     }
11418 
11419     /**
11420      * Returns the current {@link ServiceState} information.
11421      *
11422      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
11423      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
11424      *
11425      * If you want continuous updates of service state info, register a {@link PhoneStateListener}
11426      * via {@link #listen} with the {@link PhoneStateListener#LISTEN_SERVICE_STATE} event.
11427      *
11428      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
11429      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
11430      * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
11431      *
11432      * May return {@code null} when the subscription is inactive or when there was an error
11433      * communicating with the phone process.
11434      */
11435     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
11436     @RequiresPermission(allOf = {
11437             Manifest.permission.READ_PHONE_STATE,
11438             Manifest.permission.ACCESS_COARSE_LOCATION
11439     })
getServiceState()11440     public @Nullable ServiceState getServiceState() {
11441         return getServiceStateForSubscriber(getSubId());
11442     }
11443 
11444     /**
11445      * Returns the service state information on specified subscription. Callers require
11446      * either READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE to retrieve the information.
11447      *
11448      * May return {@code null} when the subscription is inactive or when there was an error
11449      * communicating with the phone process.
11450      * @hide
11451      */
11452     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
getServiceStateForSubscriber(int subId)11453     public ServiceState getServiceStateForSubscriber(int subId) {
11454         try {
11455             ITelephony service = getITelephony();
11456             if (service != null) {
11457                 return service.getServiceStateForSubscriber(subId, getOpPackageName(),
11458                         getAttributionTag());
11459             }
11460         } catch (RemoteException e) {
11461             Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
11462         } catch (NullPointerException e) {
11463             AnomalyReporter.reportAnomaly(
11464                     UUID.fromString("a3ab0b9d-f2aa-4baf-911d-7096c0d4645a"),
11465                     "getServiceStateForSubscriber " + subId + " NPE");
11466         }
11467         return null;
11468     }
11469 
11470     /**
11471      * Returns the URI for the per-account voicemail ringtone set in Phone settings.
11472      *
11473      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
11474      * voicemail ringtone.
11475      * @return The URI for the ringtone to play when receiving a voicemail from a specific
11476      * PhoneAccount. May be {@code null} if no ringtone is set.
11477      */
getVoicemailRingtoneUri(PhoneAccountHandle accountHandle)11478     public @Nullable Uri getVoicemailRingtoneUri(PhoneAccountHandle accountHandle) {
11479         try {
11480             ITelephony service = getITelephony();
11481             if (service != null) {
11482                 return service.getVoicemailRingtoneUri(accountHandle);
11483             }
11484         } catch (RemoteException e) {
11485             Log.e(TAG, "Error calling ITelephony#getVoicemailRingtoneUri", e);
11486         }
11487         return null;
11488     }
11489 
11490     /**
11491      * Sets the per-account voicemail ringtone.
11492      *
11493      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
11494      * {@link #hasCarrierPrivileges}, or has permission
11495      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11496      *
11497      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
11498      * voicemail ringtone.
11499      * @param uri The URI for the ringtone to play when receiving a voicemail from a specific
11500      * PhoneAccount.
11501      *
11502      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
11503      * instead.
11504      */
setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri)11505     public void setVoicemailRingtoneUri(PhoneAccountHandle phoneAccountHandle, Uri uri) {
11506         try {
11507             ITelephony service = getITelephony();
11508             if (service != null) {
11509                 service.setVoicemailRingtoneUri(getOpPackageName(), phoneAccountHandle, uri);
11510             }
11511         } catch (RemoteException e) {
11512             Log.e(TAG, "Error calling ITelephony#setVoicemailRingtoneUri", e);
11513         }
11514     }
11515 
11516     /**
11517      * Returns whether vibration is set for voicemail notification in Phone settings.
11518      *
11519      * @param accountHandle The handle for the {@link PhoneAccount} for which to retrieve the
11520      * voicemail vibration setting.
11521      * @return {@code true} if the vibration is set for this PhoneAccount, {@code false} otherwise.
11522      */
isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle)11523     public boolean isVoicemailVibrationEnabled(PhoneAccountHandle accountHandle) {
11524         try {
11525             ITelephony service = getITelephony();
11526             if (service != null) {
11527                 return service.isVoicemailVibrationEnabled(accountHandle);
11528             }
11529         } catch (RemoteException e) {
11530             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
11531         }
11532         return false;
11533     }
11534 
11535     /**
11536      * Sets the per-account preference whether vibration is enabled for voicemail notifications.
11537      *
11538      * <p>Requires that the calling app is the default dialer, or has carrier privileges (see
11539      * {@link #hasCarrierPrivileges}, or has permission
11540      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
11541      *
11542      * @param phoneAccountHandle The handle for the {@link PhoneAccount} for which to set the
11543      * voicemail vibration setting.
11544      * @param enabled Whether to enable or disable vibration for voicemail notifications from a
11545      * specific PhoneAccount.
11546      *
11547      * @deprecated Use {@link android.provider.Settings#ACTION_CHANNEL_NOTIFICATION_SETTINGS}
11548      * instead.
11549      */
setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle, boolean enabled)11550     public void setVoicemailVibrationEnabled(PhoneAccountHandle phoneAccountHandle,
11551             boolean enabled) {
11552         try {
11553             ITelephony service = getITelephony();
11554             if (service != null) {
11555                 service.setVoicemailVibrationEnabled(getOpPackageName(), phoneAccountHandle,
11556                         enabled);
11557             }
11558         } catch (RemoteException e) {
11559             Log.e(TAG, "Error calling ITelephony#isVoicemailVibrationEnabled", e);
11560         }
11561     }
11562 
11563     /**
11564      * Returns carrier id of the current subscription.
11565      * <p>To recognize a carrier (including MVNO) as a first-class identity, Android assigns each
11566      * carrier with a canonical integer a.k.a. carrier id. The carrier ID is an Android
11567      * platform-wide identifier for a carrier. AOSP maintains carrier ID assignments in
11568      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
11569      *
11570      * <p>Apps which have carrier-specific configurations or business logic can use the carrier id
11571      * as an Android platform-wide identifier for carriers.
11572      *
11573      * @return Carrier id of the current subscription. Return {@link #UNKNOWN_CARRIER_ID} if the
11574      * subscription is unavailable or the carrier cannot be identified.
11575      */
getSimCarrierId()11576     public int getSimCarrierId() {
11577         try {
11578             ITelephony service = getITelephony();
11579             if (service != null) {
11580                 return service.getSubscriptionCarrierId(getSubId());
11581             }
11582         } catch (RemoteException ex) {
11583             // This could happen if binder process crashes.
11584         }
11585         return UNKNOWN_CARRIER_ID;
11586     }
11587 
11588     /**
11589      * Returns carrier id name of the current subscription.
11590      * <p>Carrier id name is a user-facing name of carrier id returned by
11591      * {@link #getSimCarrierId()}, usually the brand name of the subsidiary
11592      * (e.g. T-Mobile). Each carrier could configure multiple {@link #getSimOperatorName() SPN} but
11593      * should have a single carrier name. Carrier name is not a canonical identity,
11594      * use {@link #getSimCarrierId()} instead.
11595      * <p>The returned carrier name is unlocalized.
11596      *
11597      * @return Carrier name of the current subscription. Return {@code null} if the subscription is
11598      * unavailable or the carrier cannot be identified.
11599      */
getSimCarrierIdName()11600     public @Nullable CharSequence getSimCarrierIdName() {
11601         try {
11602             ITelephony service = getITelephony();
11603             if (service != null) {
11604                 return service.getSubscriptionCarrierName(getSubId());
11605             }
11606         } catch (RemoteException ex) {
11607             // This could happen if binder process crashes.
11608         }
11609         return null;
11610     }
11611 
11612     /**
11613      * Returns fine-grained carrier ID of the current subscription.
11614      *
11615      * A specific carrier ID can represent the fact that a carrier may be in effect an aggregation
11616      * of other carriers (ie in an MVNO type scenario) where each of these specific carriers which
11617      * are used to make up the actual carrier service may have different carrier configurations.
11618      * A specific carrier ID could also be used, for example, in a scenario where a carrier requires
11619      * different carrier configuration for different service offering such as a prepaid plan.
11620      *
11621      * the specific carrier ID would be used for configuration purposes, but apps wishing to know
11622      * about the carrier itself should use the regular carrier ID returned by
11623      * {@link #getSimCarrierId()}.
11624      *
11625      * e.g, Tracfone SIMs could return different specific carrier ID based on IMSI from current
11626      * subscription while carrier ID remains the same.
11627      *
11628      * <p>For carriers without fine-grained specific carrier ids, return {@link #getSimCarrierId()}
11629      * <p>Specific carrier ids are defined in the same way as carrier id
11630      * <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
11631      * except each with a "parent" id linking to its top-level carrier id.
11632      *
11633      * @return Returns fine-grained carrier id of the current subscription.
11634      * Return {@link #UNKNOWN_CARRIER_ID} if the subscription is unavailable or the carrier cannot
11635      * be identified.
11636      */
getSimSpecificCarrierId()11637     public int getSimSpecificCarrierId() {
11638         try {
11639             ITelephony service = getITelephony();
11640             if (service != null) {
11641                 return service.getSubscriptionSpecificCarrierId(getSubId());
11642             }
11643         } catch (RemoteException ex) {
11644             // This could happen if binder process crashes.
11645         }
11646         return UNKNOWN_CARRIER_ID;
11647     }
11648 
11649     /**
11650      * Similar like {@link #getSimCarrierIdName()}, returns user-facing name of the
11651      * specific carrier id returned by {@link #getSimSpecificCarrierId()}.
11652      *
11653      * The specific carrier ID would be used for configuration purposes, but apps wishing to know
11654      * about the carrier itself should use the regular carrier ID returned by
11655      * {@link #getSimCarrierIdName()}.
11656      *
11657      * <p>The returned name is unlocalized.
11658      *
11659      * @return user-facing name of the subscription specific carrier id. Return {@code null} if the
11660      * subscription is unavailable or the carrier cannot be identified.
11661      */
getSimSpecificCarrierIdName()11662     public @Nullable CharSequence getSimSpecificCarrierIdName() {
11663         try {
11664             ITelephony service = getITelephony();
11665             if (service != null) {
11666                 return service.getSubscriptionSpecificCarrierName(getSubId());
11667             }
11668         } catch (RemoteException ex) {
11669             // This could happen if binder process crashes.
11670         }
11671         return null;
11672     }
11673 
11674     /**
11675      * Returns carrier id based on sim MCCMNC (returned by {@link #getSimOperator()}) only.
11676      * This is used for fallback when configurations/logic for exact carrier id
11677      * {@link #getSimCarrierId()} are not found.
11678      *
11679      * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
11680      * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
11681      * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
11682      * by default. After carrier id table update, a new carrier id was assigned. If apps don't
11683      * take the update with the new id, it might be helpful to always fallback by using carrier
11684      * id based on MCCMNC if there is no match.
11685      *
11686      * @return matching carrier id from sim MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
11687      * subscription is unavailable or the carrier cannot be identified.
11688      */
getCarrierIdFromSimMccMnc()11689     public int getCarrierIdFromSimMccMnc() {
11690         try {
11691             ITelephony service = getITelephony();
11692             if (service != null) {
11693                 return service.getCarrierIdFromMccMnc(getSlotIndex(), getSimOperator(), true);
11694             }
11695         } catch (RemoteException ex) {
11696             // This could happen if binder process crashes.
11697         }
11698         return UNKNOWN_CARRIER_ID;
11699     }
11700 
11701      /**
11702       * Returns carrier id based on MCCMNC (returned by {@link #getSimOperator()}) only. This is
11703       * used for fallback when configurations/logic for exact carrier id {@link #getSimCarrierId()}
11704       * are not found.
11705       *
11706       * Android carrier id table <a href="https://android.googlesource.com/platform/packages/providers/TelephonyProvider/+/master/assets/latest_carrier_id/carrier_list.textpb">here</a>
11707       * can be updated out-of-band, its possible a MVNO (Mobile Virtual Network Operator) carrier
11708       * was not fully recognized and assigned to its MNO (Mobile Network Operator) carrier id
11709       * by default. After carrier id table update, a new carrier id was assigned. If apps don't
11710       * take the update with the new id, it might be helpful to always fallback by using carrier
11711       * id based on MCCMNC if there is no match.
11712       *
11713       * @return matching carrier id from passing MCCMNC. Return {@link #UNKNOWN_CARRIER_ID} if the
11714       * subscription is unavailable or the carrier cannot be identified.
11715       * @hide
11716       */
11717      @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierIdFromMccMnc(String mccmnc)11718      public int getCarrierIdFromMccMnc(String mccmnc) {
11719         try {
11720             ITelephony service = getITelephony();
11721             if (service != null) {
11722                 return service.getCarrierIdFromMccMnc(getSlotIndex(), mccmnc, false);
11723             }
11724         } catch (RemoteException ex) {
11725             // This could happen if binder process crashes.
11726         }
11727         return UNKNOWN_CARRIER_ID;
11728     }
11729 
11730     /**
11731      * Return a list of certs as hex strings from loaded carrier privileges access rules.
11732      *
11733      * @return a list of certificates as hex strings, or an empty list if there are no certs or
11734      *     privilege rules are not loaded yet.
11735      * @hide
11736      */
11737     @TestApi
11738     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
11739     @NonNull
getCertsFromCarrierPrivilegeAccessRules()11740     public List<String> getCertsFromCarrierPrivilegeAccessRules() {
11741         List<String> certs = null;
11742         try {
11743             ITelephony service = getITelephony();
11744             if (service != null) {
11745                 certs = service.getCertsFromCarrierPrivilegeAccessRules(getSubId());
11746             }
11747         } catch (RemoteException ex) {
11748             // This could happen if binder process crashes.
11749         }
11750         return certs == null ? Collections.emptyList() : certs;
11751     }
11752 
11753     /**
11754      * Return the application ID for the uicc application type like {@link #APPTYPE_CSIM}.
11755      * All uicc applications are uniquely identified by application ID, represented by the hex
11756      * string. e.g, A00000015141434C00. See ETSI 102.221 and 101.220
11757      * <p>Requires Permission:
11758      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
11759      *
11760      * @param appType the uicc app type.
11761      * @return Application ID for specified app type or {@code null} if no uicc or error.
11762      * @hide
11763      */
11764     @Nullable
11765     @SystemApi
11766     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAidForAppType(@iccAppType int appType)11767     public String getAidForAppType(@UiccAppType int appType) {
11768         return getAidForAppType(getSubId(), appType);
11769     }
11770 
11771     /**
11772      * same as {@link #getAidForAppType(int)}
11773      * @hide
11774      */
getAidForAppType(int subId, int appType)11775     public String getAidForAppType(int subId, int appType) {
11776         try {
11777             ITelephony service = getITelephony();
11778             if (service != null) {
11779                 return service.getAidForAppType(subId, appType);
11780             }
11781         } catch (RemoteException e) {
11782             Log.e(TAG, "Error calling ITelephony#getAidForAppType", e);
11783         }
11784         return null;
11785     }
11786 
11787     /**
11788      * Return the Electronic Serial Number.
11789      *
11790      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
11791      *
11792      * @return ESN or null if error.
11793      * @hide
11794      */
getEsn()11795     public String getEsn() {
11796         return getEsn(getSubId());
11797     }
11798 
11799     /**
11800      * Return the Electronic Serial Number.
11801      *
11802      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
11803      *
11804      * @param subId the subscription ID that this request applies to.
11805      * @return ESN or null if error.
11806      * @hide
11807      */
getEsn(int subId)11808     public String getEsn(int subId) {
11809         try {
11810             ITelephony service = getITelephony();
11811             if (service != null) {
11812                 return service.getEsn(subId);
11813             }
11814         } catch (RemoteException e) {
11815             Log.e(TAG, "Error calling ITelephony#getEsn", e);
11816         }
11817         return null;
11818     }
11819 
11820     /**
11821      * Return the Preferred Roaming List Version
11822      *
11823      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
11824      *
11825      * @return PRLVersion or null if error.
11826      * @hide
11827      */
11828     @SystemApi
getCdmaPrlVersion()11829     public String getCdmaPrlVersion() {
11830         return getCdmaPrlVersion(getSubId());
11831     }
11832 
11833     /**
11834      * Return the Preferred Roaming List Version
11835      *
11836      * Requires that the calling app has READ_PRIVILEGED_PHONE_STATE permission
11837      *
11838      * @param subId the subscription ID that this request applies to.
11839      * @return PRLVersion or null if error.
11840      * @hide
11841      */
getCdmaPrlVersion(int subId)11842     public String getCdmaPrlVersion(int subId) {
11843         try {
11844             ITelephony service = getITelephony();
11845             if (service != null) {
11846                 return service.getCdmaPrlVersion(subId);
11847             }
11848         } catch (RemoteException e) {
11849             Log.e(TAG, "Error calling ITelephony#getCdmaPrlVersion", e);
11850         }
11851         return null;
11852     }
11853 
11854     /**
11855      * Get snapshot of Telephony histograms
11856      * @return List of Telephony histograms
11857      * Requires Permission:
11858      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
11859      * Or the calling app has carrier privileges.
11860      * @hide
11861      */
11862     @SystemApi
11863     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
getTelephonyHistograms()11864     public List<TelephonyHistogram> getTelephonyHistograms() {
11865         try {
11866             ITelephony service = getITelephony();
11867             if (service != null) {
11868                 return service.getTelephonyHistograms();
11869             }
11870         } catch (RemoteException e) {
11871             Log.e(TAG, "Error calling ITelephony#getTelephonyHistograms", e);
11872         }
11873         return null;
11874     }
11875 
11876     /**
11877      * Set the allowed carrier list for slotIndex
11878      * Require system privileges. In the future we may add this to carrier APIs.
11879      *
11880      * <p>Requires Permission:
11881      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
11882      *
11883      * <p>This method works only on devices with {@link
11884      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
11885      *
11886      * @deprecated use setCarrierRestrictionRules instead
11887      *
11888      * @return The number of carriers set successfully. Should be length of
11889      * carrierList on success; -1 if carrierList null or on error.
11890      * @hide
11891      */
11892     @SystemApi
11893     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers)11894     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
11895         if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
11896             return -1;
11897         }
11898         // Execute the method setCarrierRestrictionRules with an empty excluded list and
11899         // indicating priority for the allowed list.
11900         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
11901                 .setAllowedCarriers(carriers)
11902                 .setDefaultCarrierRestriction(
11903                     CarrierRestrictionRules.CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED)
11904                 .build();
11905 
11906         int result = setCarrierRestrictionRules(carrierRestrictionRules);
11907 
11908         // Convert result into int, as required by this method.
11909         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
11910             return carriers.size();
11911         } else {
11912             return -1;
11913         }
11914     }
11915 
11916     /**
11917      * The carrier restrictions were successfully set.
11918      * @hide
11919      */
11920     @SystemApi
11921     public static final int SET_CARRIER_RESTRICTION_SUCCESS = 0;
11922 
11923     /**
11924      * The carrier restrictions were not set due to lack of support in the modem. This can happen
11925      * if the modem does not support setting the carrier restrictions or if the configuration
11926      * passed in the {@code setCarrierRestrictionRules} is not supported by the modem.
11927      * @hide
11928      */
11929     @SystemApi
11930     public static final int SET_CARRIER_RESTRICTION_NOT_SUPPORTED = 1;
11931 
11932     /**
11933      * The setting of carrier restrictions failed.
11934      * @hide
11935      */
11936     @SystemApi
11937     public static final int SET_CARRIER_RESTRICTION_ERROR = 2;
11938 
11939     /** @hide */
11940     @Retention(RetentionPolicy.SOURCE)
11941     @IntDef(prefix = {"SET_CARRIER_RESTRICTION_"},
11942             value = {
11943                     SET_CARRIER_RESTRICTION_SUCCESS,
11944                     SET_CARRIER_RESTRICTION_NOT_SUPPORTED,
11945                     SET_CARRIER_RESTRICTION_ERROR
11946             })
11947     public @interface SetCarrierRestrictionResult {}
11948 
11949     /**
11950      * The SIM power state was successfully set.
11951      * @hide
11952      */
11953     @SystemApi
11954     public static final int SET_SIM_POWER_STATE_SUCCESS = 0;
11955 
11956     /**
11957      * The SIM is already in the requested power state.
11958      * @hide
11959      */
11960     @SystemApi
11961     public static final int SET_SIM_POWER_STATE_ALREADY_IN_STATE = 1;
11962 
11963     /**
11964      * Failed to connect to the modem to make the power state request. This may happen if the
11965      * modem has an error. The user may want to make the request again later.
11966      * @hide
11967      */
11968     @SystemApi
11969     public static final int SET_SIM_POWER_STATE_MODEM_ERROR = 2;
11970 
11971     /**
11972      * Failed to connect to the SIM to make the power state request. This may happen if the
11973      * SIM has been removed. The user may want to make the request again later.
11974      * @hide
11975      */
11976     @SystemApi
11977     public static final int SET_SIM_POWER_STATE_SIM_ERROR = 3;
11978 
11979     /**
11980      * The modem version does not support synchronous power.
11981      * @hide
11982      */
11983     @SystemApi
11984     public static final int SET_SIM_POWER_STATE_NOT_SUPPORTED = 4;
11985 
11986     /** @hide */
11987     @Retention(RetentionPolicy.SOURCE)
11988     @IntDef(prefix = {"SET_SIM_POWER_STATE_"},
11989             value = {
11990                     SET_SIM_POWER_STATE_SUCCESS,
11991                     SET_SIM_POWER_STATE_ALREADY_IN_STATE,
11992                     SET_SIM_POWER_STATE_MODEM_ERROR,
11993                     SET_SIM_POWER_STATE_SIM_ERROR,
11994                     SET_SIM_POWER_STATE_NOT_SUPPORTED
11995             })
11996     public @interface SetSimPowerStateResult {}
11997 
11998     /**
11999      * Set the allowed carrier list and the excluded carrier list indicating the priority between
12000      * the two lists.
12001      * Requires system privileges.
12002      *
12003      * <p>Requires Permission:
12004      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE}
12005      *
12006      * <p>This method works only on devices with {@link
12007      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
12008      *
12009      * @return {@link #SET_CARRIER_RESTRICTION_SUCCESS} in case of success.
12010      * {@link #SET_CARRIER_RESTRICTION_NOT_SUPPORTED} if the modem does not support the
12011      * configuration. {@link #SET_CARRIER_RESTRICTION_ERROR} in all other error cases.
12012      * @hide
12013      */
12014     @SystemApi
12015     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12016     @SetCarrierRestrictionResult
setCarrierRestrictionRules(@onNull CarrierRestrictionRules rules)12017     public int setCarrierRestrictionRules(@NonNull CarrierRestrictionRules rules) {
12018         try {
12019             ITelephony service = getITelephony();
12020             if (service != null) {
12021                 return service.setAllowedCarriers(rules);
12022             }
12023         } catch (RemoteException e) {
12024             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
12025         } catch (NullPointerException e) {
12026             Log.e(TAG, "Error calling ITelephony#setAllowedCarriers", e);
12027         }
12028         return SET_CARRIER_RESTRICTION_ERROR;
12029     }
12030 
12031     /**
12032      * Get the allowed carrier list for slotIndex.
12033      * Requires system privileges.
12034      *
12035      * <p>This method returns valid data on devices with {@link
12036      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
12037      *
12038      * @deprecated Apps should use {@link getCarriersRestrictionRules} to retrieve the list of
12039      * allowed and excliuded carriers, as the result of this API is valid only when the excluded
12040      * list is empty. This API could return an empty list, even if some restrictions are present.
12041      *
12042      * @return List of {@link android.telephony.CarrierIdentifier}; empty list
12043      * means all carriers are allowed.
12044      * @hide
12045      */
12046     @Deprecated
12047     @SystemApi
12048     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getAllowedCarriers(int slotIndex)12049     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
12050         if (SubscriptionManager.isValidPhoneId(slotIndex)) {
12051             CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
12052             if (carrierRestrictionRule != null) {
12053                 return carrierRestrictionRule.getAllowedCarriers();
12054             }
12055         }
12056         return new ArrayList<CarrierIdentifier>(0);
12057     }
12058 
12059     /**
12060      * Get the allowed carrier list and the excluded carrier list indicating the priority between
12061      * the two lists.
12062      * Require system privileges. In the future we may add this to carrier APIs.
12063      *
12064      * <p>This method returns valid data on devices with {@link
12065      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
12066      *
12067      * @return {@link CarrierRestrictionRules} which contains the allowed carrier list and the
12068      * excluded carrier list with the priority between the two lists. Returns {@code null}
12069      * in case of error.
12070      * @hide
12071      */
12072     @SystemApi
12073     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12074     @Nullable
getCarrierRestrictionRules()12075     public CarrierRestrictionRules getCarrierRestrictionRules() {
12076         try {
12077             ITelephony service = getITelephony();
12078             if (service != null) {
12079                 return service.getAllowedCarriers();
12080             }
12081         } catch (RemoteException e) {
12082             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
12083         } catch (NullPointerException e) {
12084             Log.e(TAG, "Error calling ITelephony#getAllowedCarriers", e);
12085         }
12086         return null;
12087     }
12088 
12089     /**
12090      * Used to enable or disable carrier data by the system based on carrier signalling or
12091      * carrier privileged apps. Different from {@link #setDataEnabled(boolean)} which is linked to
12092      * user settings, carrier data on/off won't affect user settings but will bypass the
12093      * settings and turns off data internally if set to {@code false}.
12094      *
12095      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12096      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12097      *
12098      * <p>Requires Permission:
12099      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12100      *
12101      * @param enabled control enable or disable carrier data.
12102      * @see #resetAllCarrierActions()
12103      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
12104      * reason {@link #DATA_ENABLED_REASON_CARRIER}} instead.
12105      * @hide
12106      */
12107     @Deprecated
12108     @SystemApi
12109     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCarrierDataEnabled(boolean enabled)12110     public void setCarrierDataEnabled(boolean enabled) {
12111         try {
12112             setDataEnabledForReason(DATA_ENABLED_REASON_CARRIER, enabled);
12113         } catch (RuntimeException e) {
12114             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
12115         }
12116     }
12117 
12118     /**
12119      * Carrier action to enable or disable the radio.
12120      *
12121      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12122      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12123      *
12124      * <p>Requires Permission:
12125      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12126      *
12127      * @param enabled control enable or disable radio.
12128      * @see #resetAllCarrierActions()
12129      * @hide
12130      */
12131     @SystemApi
12132     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setRadioEnabled(boolean enabled)12133     public void setRadioEnabled(boolean enabled) {
12134         try {
12135             ITelephony service = getITelephony();
12136             if (service != null) {
12137                 service.carrierActionSetRadioEnabled(
12138                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
12139             }
12140         } catch (RemoteException e) {
12141             Log.e(TAG, "Error calling ITelephony#carrierActionSetRadioEnabled", e);
12142         }
12143     }
12144 
12145     /**
12146      * Carrier action to start or stop reporting default network available events.
12147      *
12148      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12149      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12150      *
12151      * <p>Requires Permission:
12152      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12153      *
12154      * @param report control start/stop reporting network status.
12155      * @see #resetAllCarrierActions()
12156      * @hide
12157      */
12158     @SystemApi
12159     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
reportDefaultNetworkStatus(boolean report)12160     public void reportDefaultNetworkStatus(boolean report) {
12161         try {
12162             ITelephony service = getITelephony();
12163             if (service != null) {
12164                 service.carrierActionReportDefaultNetworkStatus(
12165                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
12166             }
12167         } catch (RemoteException e) {
12168             Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
12169         }
12170     }
12171 
12172     /**
12173      * Reset all carrier actions previously set by {@link #setRadioEnabled},
12174      * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
12175      *
12176      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12177      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12178      *
12179      * <p>Requires Permission:
12180      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
12181      * @hide
12182      */
12183     @SystemApi
12184     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
resetAllCarrierActions()12185     public void resetAllCarrierActions() {
12186         try {
12187             ITelephony service = getITelephony();
12188             if (service != null) {
12189                 service.carrierActionResetAll(
12190                         getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
12191             }
12192         } catch (RemoteException e) {
12193             Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
12194         }
12195     }
12196 
12197     /**
12198      * Policy control of data connection. Usually used when data limit is passed.
12199      * @param enabled True if enabling the data, otherwise disabling.
12200      * @deprecated use {@link #setDataEnabledForReason(int, boolean) with
12201      * reason {@link #DATA_ENABLED_REASON_POLICY}} instead.
12202      * @hide
12203      */
12204     @Deprecated
12205     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setPolicyDataEnabled(boolean enabled)12206     public void setPolicyDataEnabled(boolean enabled) {
12207         try {
12208             setDataEnabledForReason(DATA_ENABLED_REASON_POLICY, enabled);
12209         } catch (RuntimeException e) {
12210             Log.e(TAG, "Error calling setDataEnabledForReason e:" + e);
12211         }
12212     }
12213 
12214     /** @hide */
12215     @IntDef({
12216             DATA_ENABLED_REASON_USER,
12217             DATA_ENABLED_REASON_POLICY,
12218             DATA_ENABLED_REASON_CARRIER,
12219             DATA_ENABLED_REASON_THERMAL
12220     })
12221     @Retention(RetentionPolicy.SOURCE)
12222     public @interface DataEnabledReason{}
12223 
12224     /**
12225      * To indicate that user enabled or disabled data.
12226      */
12227     public static final int DATA_ENABLED_REASON_USER = 0;
12228 
12229     /**
12230      * To indicate that data control due to policy. Usually used when data limit is passed.
12231      * Policy data on/off won't affect user settings but will bypass the
12232      * settings and turns off data internally if set to {@code false}.
12233      */
12234     public static final int DATA_ENABLED_REASON_POLICY = 1;
12235 
12236     /**
12237      * To indicate enable or disable carrier data by the system based on carrier signalling or
12238      * carrier privileged apps. Carrier data on/off won't affect user settings but will bypass the
12239      * settings and turns off data internally if set to {@code false}.
12240      */
12241     public static final int DATA_ENABLED_REASON_CARRIER = 2;
12242 
12243     /**
12244      * To indicate enable or disable data by thermal service.
12245      * Thermal data on/off won't affect user settings but will bypass the
12246      * settings and turns off data internally if set to {@code false}.
12247      */
12248     public static final int DATA_ENABLED_REASON_THERMAL = 3;
12249 
12250     /**
12251      * Control of data connection and provide the reason triggering the data connection control.
12252      * This can be called for following reasons
12253      * <ol>
12254      * <li>data limit is passed {@link #DATA_ENABLED_REASON_POLICY}
12255      * <li>data disabled by carrier {@link #DATA_ENABLED_REASON_CARRIER}
12256      * <li>data disabled by user {@link #DATA_ENABLED_REASON_USER}
12257      * <li>data disabled due to thermal {@link #DATA_ENABLED_REASON_THERMAL}
12258      * </ol>
12259      * If any of the reason is off, then it will result in
12260      * bypassing user preference and result in data to be turned off.
12261      *
12262      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
12263      *      to the given subId. Otherwise, applies to
12264      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12265      *
12266      *
12267      * @param reason the reason the data enable change is taking place
12268      * @param enabled True if enabling the data, otherwise disabling.
12269      *
12270      * <p>Requires Permission:
12271      * The calling app has carrier privileges (see {@link #hasCarrierPrivileges}) if the reason is
12272      * {@link #DATA_ENABLED_REASON_USER} or {@link #DATA_ENABLED_REASON_CARRIER} or the call app
12273      * has {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} irrespective of
12274      * the reason.
12275      * @throws IllegalStateException if the Telephony process is not currently available.
12276      */
12277     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
setDataEnabledForReason(@ataEnabledReason int reason, boolean enabled)12278     public void setDataEnabledForReason(@DataEnabledReason int reason, boolean enabled) {
12279         setDataEnabledForReason(getSubId(), reason, enabled);
12280     }
12281 
setDataEnabledForReason(int subId, @DataEnabledReason int reason, boolean enabled)12282     private void setDataEnabledForReason(int subId, @DataEnabledReason int reason,
12283             boolean enabled) {
12284         try {
12285             ITelephony service = getITelephony();
12286             if (service != null) {
12287                 service.setDataEnabledForReason(subId, reason, enabled);
12288             } else {
12289                 throw new IllegalStateException("telephony service is null.");
12290             }
12291         } catch (RemoteException ex) {
12292             Log.e(TAG, "Telephony#setDataEnabledForReason RemoteException", ex);
12293             ex.rethrowFromSystemServer();
12294         }
12295     }
12296 
12297     /**
12298      * Return whether data is enabled for certain reason .
12299      *
12300      * If {@link #isDataEnabledForReason} returns false, it means in data enablement for a
12301      * specific reason is turned off. If any of the reason is off, then it will result in
12302      * bypassing user preference and result in data to be turned off. Call
12303      * {@link #isDataConnectionAllowed} in order to know whether
12304      * data connection is allowed on the device.
12305      *
12306      * <p>If this object has been created with {@link #createForSubscriptionId}, applies
12307      *      to the given subId. Otherwise, applies to
12308      * {@link SubscriptionManager#getDefaultDataSubscriptionId()}
12309      *
12310      * @param reason the reason the data enable change is taking place
12311      * @return whether data is enabled for a reason.
12312      * <p>Requires Permission:
12313      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or
12314      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}
12315      * @throws IllegalStateException if the Telephony process is not currently available.
12316      */
12317     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
12318             android.Manifest.permission.READ_PHONE_STATE})
isDataEnabledForReason(@ataEnabledReason int reason)12319     public boolean isDataEnabledForReason(@DataEnabledReason int reason) {
12320         return isDataEnabledForReason(getSubId(), reason);
12321     }
12322 
isDataEnabledForReason(int subId, @DataEnabledReason int reason)12323     private boolean isDataEnabledForReason(int subId, @DataEnabledReason int reason) {
12324         try {
12325             ITelephony service = getITelephony();
12326             if (service != null) {
12327                 return service.isDataEnabledForReason(subId, reason);
12328             } else {
12329                 throw new IllegalStateException("telephony service is null.");
12330             }
12331         } catch (RemoteException ex) {
12332             Log.e(TAG, "Telephony#isDataEnabledForReason RemoteException", ex);
12333             ex.rethrowFromSystemServer();
12334         }
12335         return false;
12336     }
12337 
12338     /**
12339      * Get Client request stats which will contain statistical information
12340      * on each request made by client.
12341      * Callers require either READ_PRIVILEGED_PHONE_STATE or
12342      * READ_PHONE_STATE to retrieve the information.
12343      * @param subId sub id
12344      * @return List of Client Request Stats
12345      * @hide
12346      */
getClientRequestStats(int subId)12347     public List<ClientRequestStats> getClientRequestStats(int subId) {
12348         try {
12349             ITelephony service = getITelephony();
12350             if (service != null) {
12351                 return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
12352                         subId);
12353             }
12354         } catch (RemoteException e) {
12355             Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
12356         }
12357 
12358         return null;
12359     }
12360 
12361     /**
12362      * Checks if phone is in emergency callback mode.
12363      *
12364      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12365      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
12366      *
12367      * @return true if phone is in emergency callback mode.
12368      * @hide
12369      */
12370     @SystemApi
12371     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyCallbackMode()12372     public boolean getEmergencyCallbackMode() {
12373         return getEmergencyCallbackMode(getSubId());
12374     }
12375 
12376     /**
12377      * Check if phone is in emergency callback mode
12378      * @return true if phone is in emergency callback mode
12379      * @param subId the subscription ID that this action applies to.
12380      * @hide
12381      */
getEmergencyCallbackMode(int subId)12382     public boolean getEmergencyCallbackMode(int subId) {
12383         try {
12384             ITelephony telephony = getITelephony();
12385             if (telephony == null) {
12386                 return false;
12387             }
12388             return telephony.getEmergencyCallbackMode(subId);
12389         } catch (RemoteException e) {
12390             Log.e(TAG, "Error calling ITelephony#getEmergencyCallbackMode", e);
12391         }
12392         return false;
12393     }
12394 
12395     /**
12396      * Checks if manual network selection is allowed.
12397      *
12398      * <p>Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
12399      * READ_PRECISE_PHONE_STATE} or that the calling app has carrier privileges
12400      * (see {@link #hasCarrierPrivileges})
12401      *
12402      * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
12403      * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}.
12404      *
12405      * @return {@code true} if manual network selection is allowed, otherwise return {@code false}.
12406      */
12407     @SuppressAutoDoc // No support carrier privileges (b/72967236).
12408     @RequiresPermission(anyOf = {android.Manifest.permission.READ_PRECISE_PHONE_STATE,
12409             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
isManualNetworkSelectionAllowed()12410     public boolean isManualNetworkSelectionAllowed() {
12411         try {
12412             ITelephony telephony = getITelephony();
12413             if (telephony != null) {
12414                 return telephony.isManualNetworkSelectionAllowed(getSubId());
12415             }
12416         } catch (RemoteException e) {
12417             Log.e(TAG, "Error calling ITelephony#isManualNetworkSelectionAllowed", e);
12418         }
12419         return true;
12420     }
12421 
12422     /**
12423      * Enable or disable signal strength changes from radio will always be reported in any
12424      * condition (e.g. screen is off). This is only allowed for System caller.
12425      *
12426      * @param isEnabled {@code true} for enabling; {@code false} for disabling.
12427      * @hide
12428      */
12429     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setAlwaysReportSignalStrength(boolean isEnabled)12430     public void setAlwaysReportSignalStrength(boolean isEnabled) {
12431         try {
12432             ITelephony telephony = getITelephony();
12433             if (telephony != null) {
12434                 telephony.setAlwaysReportSignalStrength(getSubId(), isEnabled);
12435             }
12436         } catch (RemoteException ex) {
12437             Log.e(TAG, "setAlwaysReportSignalStrength RemoteException", ex);
12438             ex.rethrowAsRuntimeException();
12439         }
12440     }
12441 
12442     /**
12443      * Get the most recently available signal strength information.
12444      *
12445      * Get the most recent SignalStrength information reported by the modem. Due
12446      * to power saving this information may not always be current.
12447      * @return the most recent cached signal strength info from the modem
12448      */
12449     @Nullable
getSignalStrength()12450     public SignalStrength getSignalStrength() {
12451         try {
12452             ITelephony service = getITelephony();
12453             if (service != null) {
12454                 return service.getSignalStrength(getSubId());
12455             }
12456         } catch (RemoteException e) {
12457             Log.e(TAG, "Error calling ITelephony#getSignalStrength", e);
12458         }
12459         return null;
12460     }
12461 
12462     /**
12463      * Checks whether cellular data connection is allowed in the device.
12464      *
12465      * <p>Whether cellular data connection is allowed considers all factors below:
12466      * <UL>
12467      *   <LI>User turned on data setting {@link #isDataEnabled}.</LI>
12468      *   <LI>Carrier allows data to be on.</LI>
12469      *   <LI>Network policy.</LI>
12470      *   <LI>And possibly others.</LI>
12471      * </UL>
12472      * @return {@code true} if the overall data connection is allowed; {@code false} if not.
12473      * <p>Requires Permission:
12474      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or
12475      * {@link android.Manifest.permission#ACCESS_NETWORK_STATE} or
12476      * android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE
12477      */
12478     @RequiresPermission(anyOf = {android.Manifest.permission.ACCESS_NETWORK_STATE,
12479             android.Manifest.permission.READ_PHONE_STATE,
12480             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE})
isDataConnectionAllowed()12481     public boolean isDataConnectionAllowed() {
12482         boolean retVal = false;
12483         try {
12484             int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
12485             ITelephony telephony = getITelephony();
12486             if (telephony != null)
12487                 retVal = telephony.isDataEnabled(subId);
12488         } catch (RemoteException e) {
12489             Log.e(TAG, "Error isDataConnectionAllowed", e);
12490         }
12491         return retVal;
12492     }
12493 
12494     /**
12495      * @return true if the current device is "data capable" over a radio on the device.
12496      * <p>
12497      * "Data capable" means that this device supports packet-switched
12498      * data connections over the telephony network.
12499      * <p>
12500      */
isDataCapable()12501     public boolean isDataCapable() {
12502         if (mContext == null) return true;
12503         return mContext.getResources().getBoolean(
12504                 com.android.internal.R.bool.config_mobile_data_capable);
12505     }
12506 
12507     /**
12508      * The indication for signal strength update.
12509      * @hide
12510      */
12511     public static final int INDICATION_FILTER_SIGNAL_STRENGTH               = 0x1;
12512 
12513     /**
12514      * The indication for full network state update.
12515      * @hide
12516      */
12517     public static final int INDICATION_FILTER_FULL_NETWORK_STATE            = 0x2;
12518 
12519     /**
12520      * The indication for data call dormancy changed update.
12521      * @hide
12522      */
12523     public static final int INDICATION_FILTER_DATA_CALL_DORMANCY_CHANGED    = 0x4;
12524 
12525     /**
12526      * The indication for link capacity estimate update.
12527      * @hide
12528      */
12529     public static final int INDICATION_FILTER_LINK_CAPACITY_ESTIMATE        = 0x8;
12530 
12531     /**
12532      * The indication for physical channel config update.
12533      * @hide
12534      */
12535     public static final int INDICATION_FILTER_PHYSICAL_CHANNEL_CONFIG       = 0x10;
12536 
12537     /**
12538      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
12539      * plmn and spn. This would be handy for, eg, forcing a particular carrier id, carrier's config
12540      * (also any country or carrier overlays) to be loaded when using a test SIM with a call box.
12541      *
12542      * <p>Requires Permission:
12543      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12544      *
12545      *
12546      * @deprecated
12547      * @hide
12548      */
12549     @Deprecated
12550     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn)12551     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
12552             String gid2, String plmn, String spn) {
12553         try {
12554             ITelephony telephony = getITelephony();
12555             if (telephony != null) {
12556                 telephony.setCarrierTestOverride(
12557                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
12558                         null, null);
12559             }
12560         } catch (RemoteException ex) {
12561             // This could happen if binder process crashes.
12562         }
12563     }
12564 
12565     /**
12566      * A test API to override carrier information including mccmnc, imsi, iccid, gid1, gid2,
12567      * plmn, spn, apn and carrier priviledge. This would be handy for, eg, forcing a particular
12568      * carrier id, carrier's config (also any country or carrier overlays) to be loaded when using
12569      * a test SIM with a call box.
12570      *
12571      * <p>Requires Permission:
12572      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12573      *
12574      * @hide
12575      */
12576     @TestApi
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String plmn, String spn, String carrierPriviledgeRules, String apn)12577     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
12578                                        String gid2, String plmn, String spn,
12579                                        String carrierPriviledgeRules, String apn) {
12580         try {
12581             ITelephony telephony = getITelephony();
12582             if (telephony != null) {
12583                 telephony.setCarrierTestOverride(
12584                         getSubId(), mccmnc, imsi, iccid, gid1, gid2, plmn, spn,
12585                         carrierPriviledgeRules, apn);
12586             }
12587         } catch (RemoteException ex) {
12588             // This could happen if binder process crashes.
12589         }
12590     }
12591 
12592     /**
12593      * A test API to return installed carrier id list version
12594      *
12595      * <p>Requires Permission:
12596      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12597      *
12598      * @hide
12599      */
12600     @UnsupportedAppUsage
12601     @TestApi
getCarrierIdListVersion()12602     public int getCarrierIdListVersion() {
12603         try {
12604             ITelephony telephony = getITelephony();
12605             if (telephony != null) {
12606                 return telephony.getCarrierIdListVersion(getSubId());
12607             }
12608         } catch (RemoteException ex) {
12609             // This could happen if binder process crashes.
12610         }
12611         return UNKNOWN_CARRIER_ID_LIST_VERSION;
12612     }
12613 
12614     /**
12615      * How many modems can have simultaneous data connections.
12616      * @hide
12617      */
12618     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getNumberOfModemsWithSimultaneousDataConnections()12619     public int getNumberOfModemsWithSimultaneousDataConnections() {
12620         try {
12621             ITelephony telephony = getITelephony();
12622             if (telephony != null) {
12623                 return telephony.getNumberOfModemsWithSimultaneousDataConnections(
12624                         getSubId(), getOpPackageName(), getAttributionTag());
12625             }
12626         } catch (RemoteException ex) {
12627             // This could happen if binder process crashes.
12628         }
12629         return 0;
12630     }
12631 
12632     /**
12633      * Enable or disable OpportunisticNetworkService.
12634      *
12635      * This method should be called to enable or disable
12636      * OpportunisticNetwork service on the device.
12637      *
12638      * <p>
12639      * Requires Permission:
12640      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12641      *
12642      * @param enable enable(True) or disable(False)
12643      * @return returns true if successfully set.
12644      * @hide
12645      */
12646     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12647     @SystemApi
setOpportunisticNetworkState(boolean enable)12648     public boolean setOpportunisticNetworkState(boolean enable) {
12649         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12650         boolean ret = false;
12651         try {
12652             IOns iOpportunisticNetworkService = getIOns();
12653             if (iOpportunisticNetworkService != null) {
12654                 ret = iOpportunisticNetworkService.setEnable(enable, pkgForDebug);
12655             }
12656         } catch (RemoteException ex) {
12657             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
12658         }
12659 
12660         return ret;
12661     }
12662 
12663     /**
12664      * is OpportunisticNetworkService enabled
12665      *
12666      * This method should be called to determine if the OpportunisticNetworkService is
12667      * enabled
12668      *
12669      * <p>
12670      * Requires Permission:
12671      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
12672      * @hide
12673      */
12674     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
12675     @SystemApi
isOpportunisticNetworkEnabled()12676     public boolean isOpportunisticNetworkEnabled() {
12677         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
12678         boolean isEnabled = false;
12679 
12680         try {
12681             IOns iOpportunisticNetworkService = getIOns();
12682             if (iOpportunisticNetworkService != null) {
12683                 isEnabled = iOpportunisticNetworkService.isEnabled(pkgForDebug);
12684             }
12685         } catch (RemoteException ex) {
12686             Rlog.e(TAG, "enableOpportunisticNetwork RemoteException", ex);
12687         }
12688 
12689         return isEnabled;
12690     }
12691 
12692     /** @hide */
12693     @Retention(RetentionPolicy.SOURCE)
12694     @LongDef(flag = true, prefix = {"NETWORK_TYPE_BITMASK_"},
12695             value = {NETWORK_TYPE_BITMASK_UNKNOWN,
12696                     NETWORK_TYPE_BITMASK_GSM,
12697                     NETWORK_TYPE_BITMASK_GPRS,
12698                     NETWORK_TYPE_BITMASK_EDGE,
12699                     NETWORK_TYPE_BITMASK_CDMA,
12700                     NETWORK_TYPE_BITMASK_1xRTT,
12701                     NETWORK_TYPE_BITMASK_EVDO_0,
12702                     NETWORK_TYPE_BITMASK_EVDO_A,
12703                     NETWORK_TYPE_BITMASK_EVDO_B,
12704                     NETWORK_TYPE_BITMASK_EHRPD,
12705                     NETWORK_TYPE_BITMASK_HSUPA,
12706                     NETWORK_TYPE_BITMASK_HSDPA,
12707                     NETWORK_TYPE_BITMASK_HSPA,
12708                     NETWORK_TYPE_BITMASK_HSPAP,
12709                     NETWORK_TYPE_BITMASK_UMTS,
12710                     NETWORK_TYPE_BITMASK_TD_SCDMA,
12711                     NETWORK_TYPE_BITMASK_LTE,
12712                     NETWORK_TYPE_BITMASK_LTE_CA,
12713                     NETWORK_TYPE_BITMASK_NR,
12714                     NETWORK_TYPE_BITMASK_IWLAN
12715             })
12716     public @interface NetworkTypeBitMask {}
12717 
12718     // 2G
12719     /**
12720      * network type bitmask unknown.
12721      * @hide
12722      */
12723     @SystemApi
12724     public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L;
12725     /**
12726      * network type bitmask indicating the support of radio tech GSM.
12727      * @hide
12728      */
12729     @SystemApi
12730     public static final long NETWORK_TYPE_BITMASK_GSM = (1 << (NETWORK_TYPE_GSM -1));
12731     /**
12732      * network type bitmask indicating the support of radio tech GPRS.
12733      * @hide
12734      */
12735     @SystemApi
12736     public static final long NETWORK_TYPE_BITMASK_GPRS = (1 << (NETWORK_TYPE_GPRS -1));
12737     /**
12738      * network type bitmask indicating the support of radio tech EDGE.
12739      * @hide
12740      */
12741     @SystemApi
12742     public static final long NETWORK_TYPE_BITMASK_EDGE = (1 << (NETWORK_TYPE_EDGE -1));
12743     /**
12744      * network type bitmask indicating the support of radio tech CDMA(IS95A/IS95B).
12745      * @hide
12746      */
12747     @SystemApi
12748     public static final long NETWORK_TYPE_BITMASK_CDMA = (1 << (NETWORK_TYPE_CDMA -1));
12749     /**
12750      * network type bitmask indicating the support of radio tech 1xRTT.
12751      * @hide
12752      */
12753     @SystemApi
12754     public static final long NETWORK_TYPE_BITMASK_1xRTT = (1 << (NETWORK_TYPE_1xRTT - 1));
12755     // 3G
12756     /**
12757      * network type bitmask indicating the support of radio tech EVDO 0.
12758      * @hide
12759      */
12760     @SystemApi
12761     public static final long NETWORK_TYPE_BITMASK_EVDO_0 = (1 << (NETWORK_TYPE_EVDO_0 -1));
12762     /**
12763      * network type bitmask indicating the support of radio tech EVDO A.
12764      * @hide
12765      */
12766     @SystemApi
12767     public static final long NETWORK_TYPE_BITMASK_EVDO_A = (1 << (NETWORK_TYPE_EVDO_A - 1));
12768     /**
12769      * network type bitmask indicating the support of radio tech EVDO B.
12770      * @hide
12771      */
12772     @SystemApi
12773     public static final long NETWORK_TYPE_BITMASK_EVDO_B = (1 << (NETWORK_TYPE_EVDO_B -1));
12774     /**
12775      * network type bitmask indicating the support of radio tech EHRPD.
12776      * @hide
12777      */
12778     @SystemApi
12779     public static final long NETWORK_TYPE_BITMASK_EHRPD = (1 << (NETWORK_TYPE_EHRPD -1));
12780     /**
12781      * network type bitmask indicating the support of radio tech HSUPA.
12782      * @hide
12783      */
12784     @SystemApi
12785     public static final long NETWORK_TYPE_BITMASK_HSUPA = (1 << (NETWORK_TYPE_HSUPA -1));
12786     /**
12787      * network type bitmask indicating the support of radio tech HSDPA.
12788      * @hide
12789      */
12790     @SystemApi
12791     public static final long NETWORK_TYPE_BITMASK_HSDPA = (1 << (NETWORK_TYPE_HSDPA -1));
12792     /**
12793      * network type bitmask indicating the support of radio tech HSPA.
12794      * @hide
12795      */
12796     @SystemApi
12797     public static final long NETWORK_TYPE_BITMASK_HSPA = (1 << (NETWORK_TYPE_HSPA -1));
12798     /**
12799      * network type bitmask indicating the support of radio tech HSPAP.
12800      * @hide
12801      */
12802     @SystemApi
12803     public static final long NETWORK_TYPE_BITMASK_HSPAP = (1 << (NETWORK_TYPE_HSPAP -1));
12804     /**
12805      * network type bitmask indicating the support of radio tech UMTS.
12806      * @hide
12807      */
12808     @SystemApi
12809     public static final long NETWORK_TYPE_BITMASK_UMTS = (1 << (NETWORK_TYPE_UMTS -1));
12810     /**
12811      * network type bitmask indicating the support of radio tech TD_SCDMA.
12812      * @hide
12813      */
12814     @SystemApi
12815     public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = (1 << (NETWORK_TYPE_TD_SCDMA -1));
12816     // 4G
12817     /**
12818      * network type bitmask indicating the support of radio tech LTE.
12819      * @hide
12820      */
12821     @SystemApi
12822     public static final long NETWORK_TYPE_BITMASK_LTE = (1 << (NETWORK_TYPE_LTE -1));
12823     /**
12824      * network type bitmask indicating the support of radio tech LTE CA (carrier aggregation).
12825      * @hide
12826      */
12827     @SystemApi
12828     public static final long NETWORK_TYPE_BITMASK_LTE_CA = (1 << (NETWORK_TYPE_LTE_CA -1));
12829 
12830     /**
12831      * network type bitmask indicating the support of radio tech NR(New Radio) 5G.
12832      * @hide
12833      */
12834     @SystemApi
12835     public static final long NETWORK_TYPE_BITMASK_NR = (1 << (NETWORK_TYPE_NR -1));
12836 
12837     /**
12838      * network type bitmask indicating the support of radio tech IWLAN.
12839      * @hide
12840      */
12841     @SystemApi
12842     public static final long NETWORK_TYPE_BITMASK_IWLAN = (1 << (NETWORK_TYPE_IWLAN -1));
12843 
12844     /** @hide */
12845     public static final long NETWORK_CLASS_BITMASK_2G = NETWORK_TYPE_BITMASK_GSM
12846                 | NETWORK_TYPE_BITMASK_GPRS
12847                 | NETWORK_TYPE_BITMASK_EDGE
12848                 | NETWORK_TYPE_BITMASK_CDMA
12849                 | NETWORK_TYPE_BITMASK_1xRTT;
12850 
12851     /** @hide */
12852     public static final long NETWORK_CLASS_BITMASK_3G = NETWORK_TYPE_BITMASK_EVDO_0
12853             | NETWORK_TYPE_BITMASK_EVDO_A
12854             | NETWORK_TYPE_BITMASK_EVDO_B
12855             | NETWORK_TYPE_BITMASK_EHRPD
12856             | NETWORK_TYPE_BITMASK_HSUPA
12857             | NETWORK_TYPE_BITMASK_HSDPA
12858             | NETWORK_TYPE_BITMASK_HSPA
12859             | NETWORK_TYPE_BITMASK_HSPAP
12860             | NETWORK_TYPE_BITMASK_UMTS
12861             | NETWORK_TYPE_BITMASK_TD_SCDMA;
12862 
12863     /** @hide */
12864     public static final long NETWORK_CLASS_BITMASK_4G = NETWORK_TYPE_BITMASK_LTE
12865             | NETWORK_TYPE_BITMASK_LTE_CA
12866             | NETWORK_TYPE_BITMASK_IWLAN;
12867 
12868     /** @hide */
12869     public static final long NETWORK_CLASS_BITMASK_5G = NETWORK_TYPE_BITMASK_NR;
12870 
12871     /** @hide */
12872     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP = NETWORK_TYPE_BITMASK_GSM
12873             | NETWORK_TYPE_BITMASK_GPRS
12874             | NETWORK_TYPE_BITMASK_EDGE
12875             | NETWORK_TYPE_BITMASK_HSUPA
12876             | NETWORK_TYPE_BITMASK_HSDPA
12877             | NETWORK_TYPE_BITMASK_HSPA
12878             | NETWORK_TYPE_BITMASK_HSPAP
12879             | NETWORK_TYPE_BITMASK_UMTS
12880             | NETWORK_TYPE_BITMASK_TD_SCDMA
12881             | NETWORK_TYPE_BITMASK_LTE
12882             | NETWORK_TYPE_BITMASK_LTE_CA
12883             | NETWORK_TYPE_BITMASK_NR;
12884 
12885     /** @hide */
12886     public static final long NETWORK_STANDARDS_FAMILY_BITMASK_3GPP2 = NETWORK_TYPE_BITMASK_CDMA
12887             | NETWORK_TYPE_BITMASK_1xRTT
12888             | NETWORK_TYPE_BITMASK_EVDO_0
12889             | NETWORK_TYPE_BITMASK_EVDO_A
12890             | NETWORK_TYPE_BITMASK_EVDO_B
12891             | NETWORK_TYPE_BITMASK_EHRPD;
12892 
12893     /**
12894      * @return Modem supported radio access family bitmask
12895      *
12896      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
12897      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
12898      * @hide
12899      */
12900     @SystemApi
12901     @TestApi
12902     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSupportedRadioAccessFamily()12903     public @NetworkTypeBitMask long getSupportedRadioAccessFamily() {
12904         try {
12905             ITelephony telephony = getITelephony();
12906             if (telephony != null) {
12907                 return telephony.getRadioAccessFamily(getSlotIndex(), getOpPackageName());
12908             } else {
12909                 // This can happen when the ITelephony interface is not up yet.
12910                 return NETWORK_TYPE_BITMASK_UNKNOWN;
12911             }
12912         } catch (RemoteException ex) {
12913             // This shouldn't happen in the normal case
12914             return NETWORK_TYPE_BITMASK_UNKNOWN;
12915         } catch (NullPointerException ex) {
12916             // This could happen before phone restarts due to crashing
12917             return NETWORK_TYPE_BITMASK_UNKNOWN;
12918         }
12919     }
12920 
12921     /**
12922      * Indicates Emergency number database version is invalid.
12923      *
12924      * @hide
12925      */
12926     @SystemApi
12927     public static final int INVALID_EMERGENCY_NUMBER_DB_VERSION = -1;
12928 
12929     /**
12930      * Notify Telephony for OTA emergency number database installation complete.
12931      *
12932      * <p> Requires permission:
12933      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
12934      *
12935      * @hide
12936      */
12937     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
12938     @SystemApi
notifyOtaEmergencyNumberDbInstalled()12939     public void notifyOtaEmergencyNumberDbInstalled() {
12940         try {
12941             ITelephony telephony = getITelephony();
12942             if (telephony != null) {
12943                 telephony.notifyOtaEmergencyNumberDbInstalled();
12944             } else {
12945                 throw new IllegalStateException("telephony service is null.");
12946             }
12947         } catch (RemoteException ex) {
12948             Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
12949             ex.rethrowAsRuntimeException();
12950         }
12951     }
12952 
12953     /**
12954      * Override the file path for OTA emergency number database in a file partition.
12955      *
12956      * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
12957      *
12958      * <p> Requires permission:
12959      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
12960      *
12961      * @hide
12962      */
12963     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
12964     @SystemApi
updateOtaEmergencyNumberDbFilePath( @onNull ParcelFileDescriptor otaParcelFileDescriptor)12965     public void updateOtaEmergencyNumberDbFilePath(
12966             @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
12967         try {
12968             ITelephony telephony = getITelephony();
12969             if (telephony != null) {
12970                 telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
12971             } else {
12972                 throw new IllegalStateException("telephony service is null.");
12973             }
12974         } catch (RemoteException ex) {
12975             Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
12976             ex.rethrowAsRuntimeException();
12977         }
12978     }
12979 
12980     /**
12981      * Reset the file path to default for OTA emergency number database in a file partition.
12982      *
12983      * <p> Requires permission:
12984      * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
12985      *
12986      * @hide
12987      */
12988     @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
12989     @SystemApi
resetOtaEmergencyNumberDbFilePath()12990     public void resetOtaEmergencyNumberDbFilePath() {
12991         try {
12992             ITelephony telephony = getITelephony();
12993             if (telephony != null) {
12994                 telephony.resetOtaEmergencyNumberDbFilePath();
12995             } else {
12996                 throw new IllegalStateException("telephony service is null.");
12997             }
12998         } catch (RemoteException ex) {
12999             Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
13000             ex.rethrowAsRuntimeException();
13001         }
13002     }
13003 
13004     /**
13005      * Returns whether {@link TelephonyManager#ACTION_EMERGENCY_ASSISTANCE emergency assistance} is
13006      * available on the device.
13007      * <p>
13008      * Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
13009      *
13010      * @return {@code true} if emergency assistance is available, {@code false} otherwise
13011      *
13012      * @hide
13013      */
13014     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
13015     @SuppressWarnings("AndroidFrameworkClientSidePermissionCheck")
13016     @SystemApi
isEmergencyAssistanceEnabled()13017     public boolean isEmergencyAssistanceEnabled() {
13018         mContext.enforceCallingOrSelfPermission(
13019                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
13020                 "isEmergencyAssistanceEnabled");
13021         return EMERGENCY_ASSISTANCE_ENABLED;
13022     }
13023 
13024     /**
13025      * Get the emergency number list based on current locale, sim, default, modem and network.
13026      *
13027      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
13028      * priority sources will be located at the smaller index; the priority order of sources are:
13029      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
13030      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
13031      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
13032      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
13033      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
13034      *
13035      * <p>The subscriptions which the returned list would be based on, are all the active
13036      * subscriptions, no matter which subscription could be used to create TelephonyManager.
13037      *
13038      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
13039      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
13040      *
13041      * @return Map including the keys as the active subscription IDs (Note: if there is no active
13042      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
13043      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
13044      * or throw a SecurityException if the caller does not have the permission.
13045      */
13046     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
13047     @NonNull
getEmergencyNumberList()13048     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList() {
13049         Map<Integer, List<EmergencyNumber>> emergencyNumberList = new HashMap<>();
13050         try {
13051             ITelephony telephony = getITelephony();
13052             if (telephony != null) {
13053                 return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
13054                         mContext.getAttributionTag());
13055             } else {
13056                 throw new IllegalStateException("telephony service is null.");
13057             }
13058         } catch (RemoteException ex) {
13059             Log.e(TAG, "getEmergencyNumberList RemoteException", ex);
13060             ex.rethrowAsRuntimeException();
13061         }
13062         return emergencyNumberList;
13063     }
13064 
13065     /**
13066      * Get the per-category emergency number list based on current locale, sim, default, modem
13067      * and network.
13068      *
13069      * <p>In each returned list, the emergency number {@link EmergencyNumber} coming from higher
13070      * priority sources will be located at the smaller index; the priority order of sources are:
13071      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING} >
13072      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_SIM} >
13073      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DATABASE} >
13074      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_DEFAULT} >
13075      * {@link EmergencyNumber#EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG}
13076      *
13077      * <p>The subscriptions which the returned list would be based on, are all the active
13078      * subscriptions, no matter which subscription could be used to create TelephonyManager.
13079      *
13080      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
13081      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
13082      *
13083      * @param categories the emergency service categories which are the bitwise-OR combination of
13084      * the following constants:
13085      * <ol>
13086      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED} </li>
13087      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_POLICE} </li>
13088      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AMBULANCE} </li>
13089      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_FIRE_BRIGADE} </li>
13090      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MARINE_GUARD} </li>
13091      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MOUNTAIN_RESCUE} </li>
13092      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_MIEC} </li>
13093      * <li>{@link EmergencyNumber#EMERGENCY_SERVICE_CATEGORY_AIEC} </li>
13094      * </ol>
13095      * @return Map including the keys as the active subscription IDs (Note: if there is no active
13096      * subscription, the key is {@link SubscriptionManager#getDefaultSubscriptionId}) and the value
13097      * as the list of {@link EmergencyNumber}; empty Map if this information is not available;
13098      * or throw a SecurityException if the caller does not have the permission.
13099      * @throws IllegalStateException if the Telephony process is not currently available.
13100      */
13101     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
13102     @NonNull
getEmergencyNumberList( @mergencyServiceCategories int categories)13103     public Map<Integer, List<EmergencyNumber>> getEmergencyNumberList(
13104             @EmergencyServiceCategories int categories) {
13105         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
13106         try {
13107             ITelephony telephony = getITelephony();
13108             if (telephony != null) {
13109                 Map<Integer, List<EmergencyNumber>> emergencyNumberList =
13110                         telephony.getEmergencyNumberList(mContext.getOpPackageName(),
13111                                 mContext.getAttributionTag());
13112                 emergencyNumberListForCategories =
13113                         filterEmergencyNumbersByCategories(emergencyNumberList, categories);
13114             } else {
13115                 throw new IllegalStateException("telephony service is null.");
13116             }
13117         } catch (RemoteException ex) {
13118             Log.e(TAG, "getEmergencyNumberList with Categories RemoteException", ex);
13119             ex.rethrowAsRuntimeException();
13120         }
13121         return emergencyNumberListForCategories;
13122     }
13123 
13124     /**
13125      * Filter emergency numbers with categories.
13126      *
13127      * @hide
13128      */
13129     @VisibleForTesting
filterEmergencyNumbersByCategories( Map<Integer, List<EmergencyNumber>> emergencyNumberList, @EmergencyServiceCategories int categories)13130     public Map<Integer, List<EmergencyNumber>> filterEmergencyNumbersByCategories(
13131             Map<Integer, List<EmergencyNumber>> emergencyNumberList,
13132                     @EmergencyServiceCategories int categories) {
13133         Map<Integer, List<EmergencyNumber>> emergencyNumberListForCategories = new HashMap<>();
13134         if (emergencyNumberList != null) {
13135             for (Integer subscriptionId : emergencyNumberList.keySet()) {
13136                 List<EmergencyNumber> allNumbersForSub = emergencyNumberList.get(
13137                         subscriptionId);
13138                 List<EmergencyNumber> numbersForCategoriesPerSub = new ArrayList<>();
13139                 for (EmergencyNumber number : allNumbersForSub) {
13140                     if (number.isInEmergencyServiceCategories(categories)) {
13141                         numbersForCategoriesPerSub.add(number);
13142                     }
13143                 }
13144                 emergencyNumberListForCategories.put(
13145                         subscriptionId, numbersForCategoriesPerSub);
13146             }
13147         }
13148         return emergencyNumberListForCategories;
13149     }
13150 
13151     /**
13152      * Identifies if the supplied phone number is an emergency number that matches a known
13153      * emergency number based on current locale, SIM card(s), Android database, modem, network,
13154      * or defaults.
13155      *
13156      * <p>This method assumes that only dialable phone numbers are passed in; non-dialable
13157      * numbers are not considered emergency numbers. A dialable phone number consists only
13158      * of characters/digits identified by {@link PhoneNumberUtils#isDialable(char)}.
13159      *
13160      * <p>The subscriptions which the identification would be based on, are all the active
13161      * subscriptions, no matter which subscription could be used to create TelephonyManager.
13162      *
13163      * @param number - the number to look up
13164      * @return {@code true} if the given number is an emergency number based on current locale,
13165      * SIM card(s), Android database, modem, network or defaults; {@code false} otherwise.
13166      * @throws IllegalStateException if the Telephony process is not currently available.
13167      */
isEmergencyNumber(@onNull String number)13168     public boolean isEmergencyNumber(@NonNull String number) {
13169         try {
13170             ITelephony telephony = getITelephony();
13171             if (telephony != null) {
13172                 return telephony.isEmergencyNumber(number, true);
13173             } else {
13174                 throw new IllegalStateException("telephony service is null.");
13175             }
13176         } catch (RemoteException ex) {
13177             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
13178             ex.rethrowAsRuntimeException();
13179         }
13180         return false;
13181     }
13182 
13183     /**
13184      * Checks if the supplied number is an emergency number based on current locale, sim, default,
13185      * modem and network.
13186      *
13187      * <p> Specifically, this method will return {@code true} if the specified number is an
13188      * emergency number, *or* if the number simply starts with the same digits as any current
13189      * emergency number.
13190      *
13191      * <p>The subscriptions which the identification would be based on, are all the active
13192      * subscriptions, no matter which subscription could be used to create TelephonyManager.
13193      *
13194      * <p>Requires permission: {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE} or
13195      * that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
13196      *
13197      * @param number - the number to look up
13198      * @return {@code true} if the given number is an emergency number or it simply starts with
13199      * the same digits of any current emergency number based on current locale, sim, modem and
13200      * network; {@code false} if it is not; or throw an SecurityException if the caller does not
13201      * have the required permission/privileges
13202      * @throws IllegalStateException if the Telephony process is not currently available.
13203      * @hide
13204      */
13205     @SystemApi
13206     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isPotentialEmergencyNumber(@onNull String number)13207     public boolean isPotentialEmergencyNumber(@NonNull String number) {
13208         try {
13209             ITelephony telephony = getITelephony();
13210             if (telephony != null) {
13211                 return telephony.isEmergencyNumber(number, false);
13212             } else {
13213                 throw new IllegalStateException("telephony service is null.");
13214             }
13215         } catch (RemoteException ex) {
13216             Log.e(TAG, "isEmergencyNumber RemoteException", ex);
13217             ex.rethrowAsRuntimeException();
13218         }
13219         return false;
13220     }
13221 
13222     /**
13223      * Returns the emergency number database version.
13224      *
13225      * <p>Requires Permission:
13226      *   {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
13227      *
13228      * @hide
13229      */
13230     @SystemApi
13231     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getEmergencyNumberDbVersion()13232     public int getEmergencyNumberDbVersion() {
13233         try {
13234             ITelephony telephony = getITelephony();
13235             if (telephony != null) {
13236                 return telephony.getEmergencyNumberDbVersion(getSubId());
13237             }
13238         } catch (RemoteException ex) {
13239             Log.e(TAG, "getEmergencyNumberDbVersion RemoteException", ex);
13240             ex.rethrowAsRuntimeException();
13241         }
13242         return INVALID_EMERGENCY_NUMBER_DB_VERSION;
13243     }
13244 
13245     /** @hide */
13246     @Retention(RetentionPolicy.SOURCE)
13247     @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
13248             SET_OPPORTUNISTIC_SUB_SUCCESS,
13249             SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
13250             SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION,
13251             SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE,
13252             SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION})
13253     public @interface SetOpportunisticSubscriptionResult {}
13254 
13255     /**
13256      * No error. Operation succeeded.
13257      */
13258     public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
13259 
13260     /**
13261      * Validation failed when trying to switch to preferred subscription.
13262      */
13263     public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
13264 
13265     /**
13266      * The subscription is not valid. It must be an active opportunistic subscription.
13267      */
13268     public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2;
13269 
13270     /**
13271      * The subscription is not valid. It must be an opportunistic subscription.
13272      */
13273     public static final int SET_OPPORTUNISTIC_SUB_NO_OPPORTUNISTIC_SUB_AVAILABLE = 3;
13274 
13275     /**
13276      * Subscription service happened remote exception.
13277      */
13278     public static final int SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION = 4;
13279 
13280 
13281     /** @hide */
13282     @Retention(RetentionPolicy.SOURCE)
13283     @IntDef(prefix = {"UPDATE_AVAILABLE_NETWORKS"}, value = {
13284             UPDATE_AVAILABLE_NETWORKS_SUCCESS,
13285             UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE,
13286             UPDATE_AVAILABLE_NETWORKS_ABORTED,
13287             UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS,
13288             UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE,
13289             UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL,
13290             UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL,
13291             UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED,
13292             UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE,
13293             UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION,
13294             UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED})
13295     public @interface UpdateAvailableNetworksResult {}
13296 
13297     /**
13298      * No error. Operation succeeded.
13299      */
13300     public static final int UPDATE_AVAILABLE_NETWORKS_SUCCESS = 0;
13301 
13302     /**
13303      * There is a unknown failure happened.
13304      */
13305     public static final int UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE = 1;
13306 
13307     /**
13308      * The request is aborted.
13309      */
13310     public static final int UPDATE_AVAILABLE_NETWORKS_ABORTED = 2;
13311 
13312     /**
13313      * The parameter passed in is invalid.
13314      */
13315     public static final int UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS = 3;
13316 
13317     /**
13318      * No carrier privilege.
13319      */
13320     public static final int UPDATE_AVAILABLE_NETWORKS_NO_CARRIER_PRIVILEGE = 4;
13321 
13322     /**
13323      * Disable modem fail.
13324      */
13325     public static final int UPDATE_AVAILABLE_NETWORKS_DISABLE_MODEM_FAIL = 5;
13326 
13327     /**
13328      * Enable modem fail.
13329      */
13330     public static final int UPDATE_AVAILABLE_NETWORKS_ENABLE_MODEM_FAIL = 6;
13331 
13332     /**
13333      * Carrier app does not support multiple available networks.
13334      */
13335     public static final int UPDATE_AVAILABLE_NETWORKS_MULTIPLE_NETWORKS_NOT_SUPPORTED = 7;
13336 
13337     /**
13338      * The subscription is not valid. It must be an opportunistic subscription.
13339      */
13340     public static final int UPDATE_AVAILABLE_NETWORKS_NO_OPPORTUNISTIC_SUB_AVAILABLE = 8;
13341 
13342     /**
13343      * There is no OpportunisticNetworkService.
13344      */
13345     public static final int UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION = 9;
13346 
13347     /**
13348      * OpportunisticNetworkService is disabled.
13349      */
13350     public static final int UPDATE_AVAILABLE_NETWORKS_SERVICE_IS_DISABLED = 10;
13351 
13352     /**
13353      * Set preferred opportunistic data subscription id.
13354      *
13355      * Switch internet data to preferred opportunistic data subscription id. This api
13356      * can result in lose of internet connectivity for short period of time while internet data
13357      * is handed over.
13358      * <p>Requires that the calling app has carrier privileges on both primary and
13359      * secondary subscriptions (see
13360      * {@link #hasCarrierPrivileges}), or has permission
13361      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13362      *
13363      * @param subId which opportunistic subscription
13364      * {@link SubscriptionManager#getOpportunisticSubscriptions} is preferred for cellular data.
13365      * Pass {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} to unset the preference
13366      * @param needValidation whether validation is needed before switch happens.
13367      * @param executor The executor of where the callback will execute.
13368      * @param callback Callback will be triggered once it succeeds or failed.
13369      *                 See {@link TelephonyManager.SetOpportunisticSubscriptionResult}
13370      *                 for more details. Pass null if don't care about the result.
13371      */
setPreferredOpportunisticDataSubscription(int subId, boolean needValidation, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback)13372     public void setPreferredOpportunisticDataSubscription(int subId, boolean needValidation,
13373             @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Integer> callback) {
13374         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
13375         try {
13376             IOns iOpportunisticNetworkService = getIOns();
13377             if (iOpportunisticNetworkService == null) {
13378                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
13379                     throw new IllegalStateException("Opportunistic Network Service is null");
13380                 } else {
13381                     // Let the general remote exception handling catch this.
13382                     throw new RemoteException("Null Opportunistic Network Service!");
13383                 }
13384             }
13385             ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
13386                 @Override
13387                 public void onComplete(int result) {
13388                     if (executor == null || callback == null) {
13389                         return;
13390                     }
13391                     final long identity = Binder.clearCallingIdentity();
13392                     try {
13393                         executor.execute(() -> {
13394                             callback.accept(result);
13395                         });
13396                     } finally {
13397                         Binder.restoreCallingIdentity(identity);
13398                     }
13399                 }
13400             };
13401 
13402             iOpportunisticNetworkService
13403                     .setPreferredDataSubscriptionId(subId, needValidation, callbackStub,
13404                             pkgForDebug);
13405         } catch (RemoteException ex) {
13406             Rlog.e(TAG, "setPreferredOpportunisticDataSubscription RemoteException", ex);
13407             if (executor == null || callback == null) {
13408                 return;
13409             }
13410             runOnBackgroundThread(() -> executor.execute(() -> {
13411                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
13412                     callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
13413                 } else {
13414                     callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
13415                 }
13416             }));
13417         }
13418     }
13419 
13420     /**
13421      * Get preferred opportunistic data subscription Id
13422      *
13423      * <p>Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}),
13424      * or has either READ_PRIVILEGED_PHONE_STATE
13425      * or {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} permission.
13426      * @return subId preferred opportunistic subscription id or
13427      * {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID} if there are no preferred
13428      * subscription id
13429      *
13430      */
13431     @RequiresPermission(anyOf = {
13432             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
13433             android.Manifest.permission.READ_PHONE_STATE
13434     })
getPreferredOpportunisticDataSubscription()13435     public int getPreferredOpportunisticDataSubscription() {
13436         String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
13437         String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
13438         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
13439         try {
13440             IOns iOpportunisticNetworkService = getIOns();
13441             if (iOpportunisticNetworkService != null) {
13442                 subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
13443                         packageName, attributionTag);
13444             }
13445         } catch (RemoteException ex) {
13446             Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
13447         }
13448         return subId;
13449     }
13450 
13451     /**
13452      * Update availability of a list of networks in the current location.
13453      *
13454      * This api should be called to inform OpportunisticNetwork Service about the availability
13455      * of a network at the current location. This information will be used by OpportunisticNetwork
13456      * service to enable modem stack and to attach to the network. If an empty list is passed,
13457      * it is assumed that no network is available and will result in disabling the modem stack
13458      * to save power. This api do not switch internet data once network attach is completed.
13459      * Use {@link TelephonyManager#setPreferredOpportunisticDataSubscription}
13460      * to switch internet data after network attach is complete.
13461      * Requires that the calling app has carrier privileges on both primary and
13462      * secondary subscriptions (see {@link #hasCarrierPrivileges}), or has permission
13463      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13464      * @param availableNetworks is a list of available network information.
13465      * @param executor The executor of where the callback will execute.
13466      * @param callback Callback will be triggered once it succeeds or failed.
13467      *
13468      */
13469     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
updateAvailableNetworks(@onNull List<AvailableNetworkInfo> availableNetworks, @Nullable @CallbackExecutor Executor executor, @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback)13470     public void updateAvailableNetworks(@NonNull List<AvailableNetworkInfo> availableNetworks,
13471             @Nullable @CallbackExecutor Executor executor,
13472             @UpdateAvailableNetworksResult @Nullable Consumer<Integer> callback) {
13473         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
13474         Objects.requireNonNull(availableNetworks, "availableNetworks must not be null.");
13475         try {
13476             IOns iOpportunisticNetworkService = getIOns();
13477             if (iOpportunisticNetworkService == null) {
13478                 if (Compatibility.isChangeEnabled(NULL_TELEPHONY_THROW_NO_CB)) {
13479                     throw new IllegalStateException("Opportunistic Network Service is null");
13480                 } else {
13481                     // Let the general remote exception handling catch this.
13482                     throw new RemoteException("Null Opportunistic Network Service!");
13483                 }
13484             }
13485 
13486             IUpdateAvailableNetworksCallback callbackStub =
13487                     new IUpdateAvailableNetworksCallback.Stub() {
13488                         @Override
13489                         public void onComplete(int result) {
13490                             if (executor == null || callback == null) {
13491                                 return;
13492                             }
13493                             Binder.withCleanCallingIdentity(() -> {
13494                                 executor.execute(() -> callback.accept(result));
13495                             });
13496                         }
13497                     };
13498             iOpportunisticNetworkService
13499                     .updateAvailableNetworks(availableNetworks, callbackStub, pkgForDebug);
13500         } catch (RemoteException ex) {
13501             Rlog.e(TAG, "updateAvailableNetworks RemoteException", ex);
13502             if (executor == null || callback == null) {
13503                 return;
13504             }
13505             runOnBackgroundThread(() -> executor.execute(() -> {
13506                 if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
13507                     callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
13508                 } else {
13509                     callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
13510                 }
13511             }));
13512         }
13513     }
13514 
13515     /**
13516      * Enable or disable a logical modem stack. When a logical modem is disabled, the corresponding
13517      * SIM will still be visible to the user but its mapping modem will not have any radio activity.
13518      * For example, we will disable a modem when user or system believes the corresponding SIM
13519      * is temporarily not needed (e.g. out of coverage), and will enable it back on when needed.
13520      *
13521      * Requires that the calling app has permission
13522      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
13523      * @param slotIndex which corresponding modem will operate on.
13524      * @param enable whether to enable or disable the modem stack.
13525      * @return whether the operation is successful.
13526      *
13527      * @hide
13528      */
13529     @SystemApi
13530     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
enableModemForSlot(int slotIndex, boolean enable)13531     public boolean enableModemForSlot(int slotIndex, boolean enable) {
13532         boolean ret = false;
13533         try {
13534             ITelephony telephony = getITelephony();
13535             if (telephony != null) {
13536                 ret = telephony.enableModemForSlot(slotIndex, enable);
13537             }
13538         } catch (RemoteException ex) {
13539             Log.e(TAG, "enableModem RemoteException", ex);
13540         }
13541         return ret;
13542     }
13543 
13544     /**
13545      * It indicates whether modem is enabled or not per slot.
13546      * It's the corresponding status of TelephonyManager.enableModemForSlot.
13547      *
13548      * <p>Requires Permission:
13549      * READ_PRIVILEGED_PHONE_STATE or
13550      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
13551      * @param slotIndex which slot it's checking.
13552      */
13553     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
isModemEnabledForSlot(int slotIndex)13554     public boolean isModemEnabledForSlot(int slotIndex) {
13555         try {
13556             ITelephony telephony = getITelephony();
13557             if (telephony != null) {
13558                 return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
13559                         mContext.getAttributionTag());
13560             }
13561         } catch (RemoteException ex) {
13562             Log.e(TAG, "enableModem RemoteException", ex);
13563         }
13564         return false;
13565     }
13566 
13567     /**
13568      * Broadcast intent action for network country code changes.
13569      *
13570      * <p>
13571      * The {@link #EXTRA_NETWORK_COUNTRY} extra indicates the country code of the current
13572      * network returned by {@link #getNetworkCountryIso()}.
13573      *
13574      * <p>There may be a delay of several minutes before reporting that no country is detected.
13575      *
13576      * @see #EXTRA_NETWORK_COUNTRY
13577      * @see #getNetworkCountryIso()
13578      */
13579     public static final String ACTION_NETWORK_COUNTRY_CHANGED =
13580             "android.telephony.action.NETWORK_COUNTRY_CHANGED";
13581 
13582     /**
13583      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
13584      * the country code in ISO-3166-1 alpha-2 format.
13585      * <p class="note">
13586      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
13587      */
13588     public static final String EXTRA_NETWORK_COUNTRY =
13589             "android.telephony.extra.NETWORK_COUNTRY";
13590 
13591     /**
13592      * The extra used with an {@link #ACTION_NETWORK_COUNTRY_CHANGED} to specify the
13593      * last known the country code in ISO-3166-1 alpha-2 format.
13594      * <p class="note">
13595      * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
13596      *
13597      * @hide
13598      */
13599     public static final String EXTRA_LAST_KNOWN_NETWORK_COUNTRY =
13600             "android.telephony.extra.LAST_KNOWN_NETWORK_COUNTRY";
13601 
13602     /**
13603      * Indicate if the user is allowed to use multiple SIM cards at the same time to register
13604      * on the network (e.g. Dual Standby or Dual Active) when the device supports it, or if the
13605      * usage is restricted. This API is used to prevent usage of multiple SIM card, based on
13606      * policies of the carrier.
13607      * <p>Note: the API does not prevent access to the SIM cards for operations that don't require
13608      * access to the network.
13609      *
13610      * @param isMultiSimCarrierRestricted true if usage of multiple SIMs is restricted, false
13611      * otherwise.
13612      *
13613      * @hide
13614      */
13615     @SystemApi
13616     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted)13617     public void setMultiSimCarrierRestriction(boolean isMultiSimCarrierRestricted) {
13618         try {
13619             ITelephony service = getITelephony();
13620             if (service != null) {
13621                 service.setMultiSimCarrierRestriction(isMultiSimCarrierRestricted);
13622             }
13623         } catch (RemoteException e) {
13624             Log.e(TAG, "setMultiSimCarrierRestriction RemoteException", e);
13625         }
13626     }
13627 
13628     /**
13629      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
13630      * Standby or Dual Active) is supported.
13631      */
13632     public static final int MULTISIM_ALLOWED = 0;
13633 
13634     /**
13635      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
13636      * Standby or Dual Active) is not supported by the hardware.
13637      */
13638     public static final int MULTISIM_NOT_SUPPORTED_BY_HARDWARE = 1;
13639 
13640     /**
13641      * The usage of multiple SIM cards at the same time to register on the network (e.g. Dual
13642      * Standby or Dual Active) is supported by the hardware, but restricted by the carrier.
13643      */
13644     public static final int MULTISIM_NOT_SUPPORTED_BY_CARRIER = 2;
13645 
13646     /** @hide */
13647     @Retention(RetentionPolicy.SOURCE)
13648     @IntDef(prefix = {"MULTISIM_"},
13649             value = {
13650                     MULTISIM_ALLOWED,
13651                     MULTISIM_NOT_SUPPORTED_BY_HARDWARE,
13652                     MULTISIM_NOT_SUPPORTED_BY_CARRIER
13653             })
13654     public @interface IsMultiSimSupportedResult {}
13655 
13656     /**
13657      * Returns if the usage of multiple SIM cards at the same time to register on the network
13658      * (e.g. Dual Standby or Dual Active) is supported by the device and by the carrier.
13659      *
13660      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
13661      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
13662      *
13663      * @return {@link #MULTISIM_ALLOWED} if the device supports multiple SIMs.
13664      * {@link #MULTISIM_NOT_SUPPORTED_BY_HARDWARE} if the device does not support multiple SIMs.
13665      * {@link #MULTISIM_NOT_SUPPORTED_BY_CARRIER} in the device supports multiple SIMs, but the
13666      * functionality is restricted by the carrier.
13667      */
13668     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13669     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
13670     @IsMultiSimSupportedResult
isMultiSimSupported()13671     public int isMultiSimSupported() {
13672         if (getSupportedModemCount() < 2) {
13673             return TelephonyManager.MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
13674         }
13675         try {
13676             ITelephony service = getITelephony();
13677             if (service != null) {
13678                 return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
13679             }
13680         } catch (RemoteException e) {
13681             Log.e(TAG, "isMultiSimSupported RemoteException", e);
13682         }
13683         return MULTISIM_NOT_SUPPORTED_BY_HARDWARE;
13684     }
13685 
13686     /**
13687      * Switch configs to enable multi-sim or switch back to single-sim
13688      * <p>Requires Permission:
13689      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the
13690      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
13691      *
13692      * Note: with only carrier privileges, it is not allowed to switch from multi-sim
13693      * to single-sim
13694      *
13695      * @param numOfSims number of live SIMs we want to switch to
13696      * @throws android.os.RemoteException
13697      */
13698     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
13699     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
switchMultiSimConfig(int numOfSims)13700     public void switchMultiSimConfig(int numOfSims) {
13701         try {
13702             ITelephony telephony = getITelephony();
13703             if (telephony != null) {
13704                 telephony.switchMultiSimConfig(numOfSims);
13705             }
13706         } catch (RemoteException ex) {
13707             Rlog.e(TAG, "switchMultiSimConfig RemoteException", ex);
13708         }
13709     }
13710 
13711     /**
13712      * Get whether making changes to modem configurations by {@link #switchMultiSimConfig(int)} will
13713      * trigger device reboot.
13714      * The modem configuration change refers to switching from single SIM configuration to DSDS
13715      * or the other way around.
13716      *
13717      *  <p>Requires Permission:
13718      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE} or that the
13719      * calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
13720      *
13721      * @return {@code true} if reboot will be triggered after making changes to modem
13722      * configurations, otherwise return {@code false}.
13723      */
13724     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
doesSwitchMultiSimConfigTriggerReboot()13725     public boolean doesSwitchMultiSimConfigTriggerReboot() {
13726         try {
13727             ITelephony service = getITelephony();
13728             if (service != null) {
13729                 return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
13730                         getOpPackageName(), getAttributionTag());
13731             }
13732         } catch (RemoteException e) {
13733             Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
13734         }
13735         return false;
13736     }
13737 
13738     /**
13739      * Retrieve the Radio HAL Version for this device.
13740      *
13741      * Get the HAL version for the IRadio interface for test purposes.
13742      *
13743      * @return a Pair of (major version, minor version) or (-1,-1) if unknown.
13744      *
13745      * @hide
13746      */
13747     @UnsupportedAppUsage
13748     @TestApi
getRadioHalVersion()13749     public Pair<Integer, Integer> getRadioHalVersion() {
13750         try {
13751             ITelephony service = getITelephony();
13752             if (service != null) {
13753                 int version = service.getRadioHalVersion();
13754                 if (version == -1) return new Pair<Integer, Integer>(-1, -1);
13755                 return new Pair<Integer, Integer>(version / 100, version % 100);
13756             }
13757         } catch (RemoteException e) {
13758             Log.e(TAG, "getRadioHalVersion() RemoteException", e);
13759         }
13760         return new Pair<Integer, Integer>(-1, -1);
13761     }
13762 
13763     /**
13764      * Get the calling application status about carrier privileges for the subscription created
13765      * in TelephonyManager. Used by Telephony Module for permission checking.
13766      *
13767      * @param uid Uid to check.
13768      * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
13769      *         {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
13770      *         {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
13771      *         {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
13772      *
13773      * @hide
13774      */
13775     @SystemApi
13776     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCarrierPrivilegeStatus(int uid)13777     public @CarrierPrivilegeStatus int getCarrierPrivilegeStatus(int uid) {
13778         try {
13779             ITelephony telephony = getITelephony();
13780             if (telephony != null) {
13781                 return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
13782             }
13783         } catch (RemoteException ex) {
13784             Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
13785         }
13786         return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
13787     }
13788 
13789     /**
13790      * Returns a list of APNs set as overrides by the device policy manager via
13791      * {@link #addDevicePolicyOverrideApn}.
13792      * This method must only be called from the system or phone processes.
13793      *
13794      * @param context Context to use.
13795      * @return {@link List} of APNs that have been set as overrides.
13796      * @throws {@link SecurityException} if the caller is not the system or phone process.
13797      * @hide
13798      */
13799     @TestApi
13800     // TODO: add new permission tag indicating that this is system-only.
getDevicePolicyOverrideApns(@onNull Context context)13801     public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
13802         try (Cursor cursor = context.getContentResolver().query(DPC_URI, null, null, null, null)) {
13803             if (cursor == null) {
13804                 return Collections.emptyList();
13805             }
13806             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
13807             cursor.moveToPosition(-1);
13808             while (cursor.moveToNext()) {
13809                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
13810                 apnList.add(apn);
13811             }
13812             return apnList;
13813         }
13814     }
13815 
13816     /**
13817      * Used by the device policy manager to add a new override APN.
13818      * This method must only be called from the system or phone processes.
13819      *
13820      * @param context Context to use.
13821      * @param apnSetting The {@link ApnSetting} describing the new APN.
13822      * @return An integer, corresponding to a primary key in a database, that allows the caller to
13823      *         modify the APN in the future via {@link #modifyDevicePolicyOverrideApn}, or
13824      *         {@link android.provider.Telephony.Carriers.INVALID_APN_ID} if the override operation
13825      *         failed.
13826      * @throws {@link SecurityException} if the caller is not the system or phone process.
13827      * @hide
13828      */
13829     @TestApi
13830     // TODO: add new permission tag indicating that this is system-only.
addDevicePolicyOverrideApn(@onNull Context context, @NonNull ApnSetting apnSetting)13831     public int addDevicePolicyOverrideApn(@NonNull Context context,
13832             @NonNull ApnSetting apnSetting) {
13833         Uri resultUri = context.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
13834 
13835         int resultId = INVALID_APN_ID;
13836         if (resultUri != null) {
13837             try {
13838                 resultId = Integer.parseInt(resultUri.getLastPathSegment());
13839             } catch (NumberFormatException e) {
13840                 Rlog.e(TAG, "Failed to parse inserted override APN id: "
13841                         + resultUri.getLastPathSegment());
13842             }
13843         }
13844         return resultId;
13845     }
13846 
13847     /**
13848      * Used by the device policy manager to modify an override APN.
13849      * This method must only be called from the system or phone processes.
13850      *
13851      * @param context Context to use.
13852      * @param apnId The integer key of the APN to modify, as returned by
13853      *              {@link #addDevicePolicyOverrideApn}
13854      * @param apnSetting The {@link ApnSetting} describing the updated APN.
13855      * @return {@code true} if successful, {@code false} otherwise.
13856      * @throws {@link SecurityException} if the caller is not the system or phone process.
13857      * @hide
13858      */
13859     @TestApi
13860     // TODO: add new permission tag indicating that this is system-only.
modifyDevicePolicyOverrideApn(@onNull Context context, int apnId, @NonNull ApnSetting apnSetting)13861     public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
13862             @NonNull ApnSetting apnSetting) {
13863         return context.getContentResolver().update(
13864                 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
13865                 apnSetting.toContentValues(), null, null) > 0;
13866     }
13867 
13868     /**
13869      * Return whether data is enabled for certain APN type. This will tell if framework will accept
13870      * corresponding network requests on a subId.
13871      *
13872      * {@link #isDataEnabled()} is directly associated with users' Mobile data toggle on / off. If
13873      * {@link #isDataEnabled()} returns false, it means in general all meter-ed data are disabled.
13874      *
13875      * This per APN type API gives a better idea whether data is allowed on a specific APN type.
13876      * It will return true if:
13877      *
13878      *  1) User data is turned on, or
13879      *  2) APN is un-metered for this subscription, or
13880      *  3) APN type is whitelisted. E.g. MMS is whitelisted if
13881      *  {@link #MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED} is enabled.
13882      *
13883      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
13884      * @return whether data is enabled for a apn type.
13885      *
13886      * @hide
13887      */
13888     @SystemApi
13889     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isDataEnabledForApn(@pnType int apnType)13890     public boolean isDataEnabledForApn(@ApnType int apnType) {
13891         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
13892         try {
13893             ITelephony service = getITelephony();
13894             if (service != null) {
13895                 return service.isDataEnabledForApn(apnType, getSubId(), pkgForDebug);
13896             }
13897         } catch (RemoteException ex) {
13898             Rlog.e(TAG, "Telephony#isDataEnabledForApn RemoteException" + ex);
13899         }
13900         return false;
13901     }
13902 
13903     /**
13904      * Whether an APN type is metered or not. It will be evaluated with the subId associated
13905      * with the TelephonyManager instance.
13906      *
13907      * @hide
13908      */
13909     @SystemApi
13910     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isApnMetered(@pnType int apnType)13911     public boolean isApnMetered(@ApnType int apnType) {
13912         try {
13913             ITelephony service = getITelephony();
13914             if (service != null) {
13915                 return service.isApnMetered(apnType, getSubId());
13916             }
13917         } catch (RemoteException ex) {
13918             Rlog.e(TAG, "Telephony#isApnMetered RemoteException" + ex);
13919         }
13920         return true;
13921     }
13922 
13923     /**
13924      * Specify which bands modem's background scan must act on.
13925      * If {@code specifiers} is non-empty, the scan will be restricted to the bands specified.
13926      * Otherwise, it scans all bands.
13927      *
13928      * For example, CBRS is only on LTE band 48. By specifying this band,
13929      * modem saves more power.
13930      *
13931      * @param specifiers which bands to scan.
13932      * @param executor The executor to execute the callback on
13933      * @param callback The callback that gets invoked when the radio responds to the request. Called
13934      *                 with {@code true} if the request succeeded, {@code false} otherwise.
13935      * @hide
13936      */
13937     @SystemApi
13938     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)13939     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers,
13940             @NonNull @CallbackExecutor Executor executor,
13941             @NonNull Consumer<Boolean> callback) {
13942         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
13943         Objects.requireNonNull(executor, "Executor must not be null.");
13944         Objects.requireNonNull(callback, "Callback must not be null.");
13945         setSystemSelectionChannelsInternal(specifiers, executor, callback);
13946     }
13947 
13948     /**
13949      * Same as {@link #setSystemSelectionChannels(List, Executor, Consumer<Boolean>)}, but to be
13950      * used when the caller does not need feedback on the results of the operation.
13951      * @param specifiers which bands to scan.
13952      * @hide
13953      */
13954     @SystemApi
13955     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSystemSelectionChannels(@onNull List<RadioAccessSpecifier> specifiers)13956     public void setSystemSelectionChannels(@NonNull List<RadioAccessSpecifier> specifiers) {
13957         Objects.requireNonNull(specifiers, "Specifiers must not be null.");
13958         setSystemSelectionChannelsInternal(specifiers, null, null);
13959     }
13960 
13961 
setSystemSelectionChannelsInternal(@onNull List<RadioAccessSpecifier> specifiers, @Nullable @CallbackExecutor Executor executor, @Nullable Consumer<Boolean> callback)13962     private void setSystemSelectionChannelsInternal(@NonNull List<RadioAccessSpecifier> specifiers,
13963             @Nullable @CallbackExecutor Executor executor,
13964             @Nullable Consumer<Boolean> callback) {
13965         IBooleanConsumer aidlConsumer = callback == null ? null : new IBooleanConsumer.Stub() {
13966             @Override
13967             public void accept(boolean result) {
13968                 final long identity = Binder.clearCallingIdentity();
13969                 try {
13970                     executor.execute(() -> callback.accept(result));
13971                 } finally {
13972                     Binder.restoreCallingIdentity(identity);
13973                 }
13974             }
13975         };
13976 
13977         try {
13978             ITelephony service = getITelephony();
13979             if (service != null) {
13980                 service.setSystemSelectionChannels(specifiers, getSubId(), aidlConsumer);
13981             }
13982         } catch (RemoteException ex) {
13983             Rlog.e(TAG, "Telephony#setSystemSelectionChannels RemoteException" + ex);
13984         }
13985     }
13986 
13987     /**
13988      * Get which bands the modem's background scan is acting on, specified by
13989      * {@link #setSystemSelectionChannels}.
13990      *
13991      * <p>Requires Permission:
13992      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
13993      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
13994      *
13995      * @return a list of {@link RadioAccessSpecifier}, or an empty list if no bands are specified.
13996      * @throws IllegalStateException if the Telephony process is not currently available.
13997      *
13998      * @hide
13999      */
14000     @SystemApi
14001     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getSystemSelectionChannels()14002     public @NonNull List<RadioAccessSpecifier> getSystemSelectionChannels() {
14003         try {
14004             ITelephony service = getITelephony();
14005             if (service != null) {
14006                 return service.getSystemSelectionChannels(getSubId());
14007             } else {
14008                 throw new IllegalStateException("telephony service is null.");
14009             }
14010         } catch (RemoteException ex) {
14011             Rlog.e(TAG, "Telephony#getSystemSelectionChannels RemoteException" + ex);
14012         }
14013         return new ArrayList<>();
14014     }
14015 
14016     /**
14017      * Verifies whether the input MCC/MNC and MVNO correspond to the current carrier.
14018      *
14019      * @param mccmnc the carrier's mccmnc that you want to match
14020      * @param mvnoType the mvnoType that defined in {@link ApnSetting}
14021      * @param mvnoMatchData the MVNO match data
14022      * @return {@code true} if input mccmnc and mvno matches with data from sim operator.
14023      * {@code false} otherwise.
14024      *
14025      * {@hide}
14026      */
14027     @SystemApi
14028     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
matchesCurrentSimOperator(@onNull String mccmnc, @MvnoType int mvnoType, @Nullable String mvnoMatchData)14029     public boolean matchesCurrentSimOperator(@NonNull String mccmnc, @MvnoType int mvnoType,
14030             @Nullable String mvnoMatchData) {
14031         try {
14032             if (!mccmnc.equals(getSimOperator())) {
14033                 return false;
14034             }
14035             ITelephony service = getITelephony();
14036             if (service != null) {
14037                 return service.isMvnoMatched(getSubId(), mvnoType, mvnoMatchData);
14038             }
14039         } catch (RemoteException ex) {
14040             Rlog.e(TAG, "Telephony#matchesCurrentSimOperator RemoteException" + ex);
14041         }
14042         return false;
14043     }
14044 
14045     /**
14046      * Callback to be used with {@link #getCallForwarding}
14047      * @hide
14048      */
14049     @SystemApi
14050     public interface CallForwardingInfoCallback {
14051         /**
14052          * Indicates that the operation was successful.
14053          */
14054         int RESULT_SUCCESS = 0;
14055 
14056         /**
14057          * Indicates that setting or retrieving the call forwarding info failed with an unknown
14058          * error.
14059          */
14060         int RESULT_ERROR_UNKNOWN = 1;
14061 
14062         /**
14063          * Indicates that call forwarding is not enabled because the recipient is not on a
14064          * Fixed Dialing Number (FDN) list.
14065          */
14066         int RESULT_ERROR_FDN_CHECK_FAILURE = 2;
14067 
14068         /**
14069          * Indicates that call forwarding is not supported on the network at this time.
14070          */
14071         int RESULT_ERROR_NOT_SUPPORTED = 3;
14072 
14073         /**
14074          * Call forwarding errors
14075          * @hide
14076          */
14077         @IntDef(prefix = { "RESULT_ERROR_" }, value = {
14078                 RESULT_ERROR_UNKNOWN,
14079                 RESULT_ERROR_NOT_SUPPORTED,
14080                 RESULT_ERROR_FDN_CHECK_FAILURE
14081         })
14082         @Retention(RetentionPolicy.SOURCE)
14083         @interface CallForwardingError{
14084         }
14085         /**
14086          * Called when the call forwarding info is successfully retrieved from the network.
14087          * @param info information about how calls are forwarded
14088          */
onCallForwardingInfoAvailable(@onNull CallForwardingInfo info)14089         void onCallForwardingInfoAvailable(@NonNull CallForwardingInfo info);
14090 
14091         /**
14092          * Called when there was an error retrieving the call forwarding information.
14093          * @param error
14094          */
onError(@allForwardingError int error)14095         void onError(@CallForwardingError int error);
14096     }
14097 
14098     /**
14099      * Gets the voice call forwarding info for a given call forwarding reason.
14100      *
14101      * This method queries the network for the currently set call forwarding configuration for the
14102      * provided call forwarding reason. When the network has provided its response, the result will
14103      * be supplied via the provided {@link Executor} on the provided
14104      * {@link CallForwardingInfoCallback}.
14105      *
14106      * @param callForwardingReason the call forwarding reason to query.
14107      * @param executor The executor on which to execute the callback once the result is ready.
14108      * @param callback The callback the results should be delivered on.
14109      *
14110      * @throws IllegalArgumentException if callForwardingReason is not any of
14111      * {@link CallForwardingInfo#REASON_UNCONDITIONAL}, {@link CallForwardingInfo#REASON_BUSY},
14112      * {@link CallForwardingInfo#REASON_NO_REPLY}, {@link CallForwardingInfo#REASON_NOT_REACHABLE},
14113      * {@link CallForwardingInfo#REASON_ALL}, or {@link CallForwardingInfo#REASON_ALL_CONDITIONAL}
14114      *
14115      * @hide
14116      */
14117     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14118     @SystemApi
getCallForwarding(@allForwardingReason int callForwardingReason, @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback)14119     public void getCallForwarding(@CallForwardingReason int callForwardingReason,
14120             @NonNull Executor executor, @NonNull CallForwardingInfoCallback callback) {
14121         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
14122                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
14123             throw new IllegalArgumentException("callForwardingReason is out of range");
14124         }
14125 
14126         ICallForwardingInfoCallback internalCallback = new ICallForwardingInfoCallback.Stub() {
14127             @Override
14128             public void onCallForwardingInfoAvailable(CallForwardingInfo info) {
14129                 executor.execute(() ->
14130                         Binder.withCleanCallingIdentity(() ->
14131                                 callback.onCallForwardingInfoAvailable(info)));
14132             }
14133 
14134             @Override
14135             public void onError(int error) {
14136                 executor.execute(() ->
14137                         Binder.withCleanCallingIdentity(() ->
14138                                 callback.onError(error)));
14139             }
14140         };
14141 
14142         try {
14143             ITelephony telephony = getITelephony();
14144             if (telephony != null) {
14145                 telephony.getCallForwarding(getSubId(), callForwardingReason, internalCallback);
14146             }
14147         } catch (RemoteException ex) {
14148             Rlog.e(TAG, "getCallForwarding RemoteException", ex);
14149             ex.rethrowAsRuntimeException();
14150         }
14151     }
14152 
14153     /**
14154      * Sets voice call forwarding behavior as described by the provided {@link CallForwardingInfo}.
14155      *
14156      * This method will enable call forwarding if the provided {@link CallForwardingInfo} returns
14157      * {@code true} from its {@link CallForwardingInfo#isEnabled()} method, and disables call
14158      * forwarding otherwise.
14159      *
14160      * If you wish to be notified about the results of this operation, provide an {@link Executor}
14161      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
14162      *
14163      * @param callForwardingInfo Info about whether calls should be forwarded and where they
14164      *                           should be forwarded to.
14165      * @param executor The executor on which the listener will be called. Must be non-null if
14166      *                 {@code listener} is non-null.
14167      * @param resultListener Asynchronous listener that'll be called when the operation completes.
14168      *                      Called with {@link CallForwardingInfoCallback#RESULT_SUCCESS} if the
14169      *                      operation succeeded and an error code from
14170      *                      {@link CallForwardingInfoCallback} it failed.
14171      *
14172      * @throws IllegalArgumentException if any of the following are true for the parameter
14173      * callForwardingInfo:
14174      * <ul>
14175      * <li>it is {@code null}.</li>
14176      * <li>{@link CallForwardingInfo#getReason()} is not any of:
14177      *     <ul>
14178      *         <li>{@link CallForwardingInfo#REASON_UNCONDITIONAL}</li>
14179      *         <li>{@link CallForwardingInfo#REASON_BUSY}</li>
14180      *         <li>{@link CallForwardingInfo#REASON_NO_REPLY}</li>
14181      *         <li>{@link CallForwardingInfo#REASON_NOT_REACHABLE}</li>
14182      *         <li>{@link CallForwardingInfo#REASON_ALL}</li>
14183      *         <li>{@link CallForwardingInfo#REASON_ALL_CONDITIONAL}</li>
14184      *     </ul>
14185      * <li>{@link CallForwardingInfo#getNumber()} returns {@code null} when enabling call
14186      * forwarding</li>
14187      * <li>{@link CallForwardingInfo#getTimeoutSeconds()} returns a non-positive value when
14188      * enabling call forwarding</li>
14189      * </ul>
14190      * @hide
14191      */
14192     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14193     @SystemApi
setCallForwarding(@onNull CallForwardingInfo callForwardingInfo, @Nullable @CallbackExecutor Executor executor, @Nullable @CallForwardingInfoCallback.CallForwardingError Consumer<Integer> resultListener)14194     public void setCallForwarding(@NonNull CallForwardingInfo callForwardingInfo,
14195             @Nullable @CallbackExecutor Executor executor,
14196             @Nullable @CallForwardingInfoCallback.CallForwardingError
14197                     Consumer<Integer> resultListener) {
14198         if (callForwardingInfo == null) {
14199             throw new IllegalArgumentException("callForwardingInfo is null");
14200         }
14201         int callForwardingReason = callForwardingInfo.getReason();
14202         if (callForwardingReason < CallForwardingInfo.REASON_UNCONDITIONAL
14203                 || callForwardingReason > CallForwardingInfo.REASON_ALL_CONDITIONAL) {
14204             throw new IllegalArgumentException("callForwardingReason is out of range");
14205         }
14206         if (callForwardingInfo.isEnabled()) {
14207             if (callForwardingInfo.getNumber() == null) {
14208                 throw new IllegalArgumentException("callForwarding number is null");
14209             }
14210             if (callForwardingInfo.getTimeoutSeconds() <= 0) {
14211                 throw new IllegalArgumentException("callForwarding timeout isn't positive");
14212             }
14213         }
14214         if (resultListener != null) {
14215             Objects.requireNonNull(executor);
14216         }
14217 
14218         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
14219             @Override
14220             public void accept(int result) {
14221                 executor.execute(() ->
14222                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
14223             }
14224         };
14225 
14226         try {
14227             ITelephony telephony = getITelephony();
14228             if (telephony != null) {
14229                 telephony.setCallForwarding(getSubId(), callForwardingInfo, internalCallback);
14230             }
14231         } catch (RemoteException ex) {
14232             Rlog.e(TAG, "setCallForwarding RemoteException", ex);
14233             ex.rethrowAsRuntimeException();
14234         } catch (NullPointerException ex) {
14235             Rlog.e(TAG, "setCallForwarding NPE", ex);
14236             throw ex;
14237         }
14238     }
14239 
14240     /**
14241      * Indicates that call waiting is enabled.
14242      *
14243      * @hide
14244      */
14245     @SystemApi
14246     public static final int CALL_WAITING_STATUS_ENABLED = 1;
14247 
14248     /**
14249      * Indicates that call waiting is disabled.
14250      *
14251      * @hide
14252      */
14253     @SystemApi
14254     public static final int CALL_WAITING_STATUS_DISABLED = 2;
14255 
14256     /**
14257      * Indicates there was an unknown error retrieving the call waiting status.
14258      *
14259      * @hide
14260      */
14261     @SystemApi
14262     public static final int CALL_WAITING_STATUS_UNKNOWN_ERROR = 3;
14263 
14264     /**
14265      * Indicates the call waiting is not supported on the current network.
14266      *
14267      * @hide
14268      */
14269     @SystemApi
14270     public static final int CALL_WAITING_STATUS_NOT_SUPPORTED = 4;
14271 
14272     /**
14273      * @hide
14274      */
14275     @IntDef(prefix = { "CALL_WAITING_STATUS_" }, value = {
14276             CALL_WAITING_STATUS_ENABLED,
14277             CALL_WAITING_STATUS_DISABLED,
14278             CALL_WAITING_STATUS_UNKNOWN_ERROR,
14279             CALL_WAITING_STATUS_NOT_SUPPORTED,
14280     })
14281     @Retention(RetentionPolicy.SOURCE)
14282     public @interface CallWaitingStatus {
14283     }
14284 
14285     /**
14286      * Retrieves the call waiting status of this device from the network.
14287      *
14288      * When call waiting is enabled, an incoming call that arrives when the user is already on
14289      * an active call will be held in a waiting state while the user is notified instead of being
14290      * rejected with a busy signal.
14291      *
14292      * @param executor The executor on which the result listener will be called.
14293      * @param resultListener A {@link Consumer} that will be called with the result fetched
14294      *                       from the network. The result will be one of:
14295      *                       <ul>
14296      *                          <li>{@link #CALL_WAITING_STATUS_ENABLED}}</li>
14297      *                          <li>{@link #CALL_WAITING_STATUS_DISABLED}}</li>
14298      *                          <li>{@link #CALL_WAITING_STATUS_UNKNOWN_ERROR}}</li>
14299      *                          <li>{@link #CALL_WAITING_STATUS_NOT_SUPPORTED}}</li>
14300      *                       </ul>
14301      * @hide
14302      */
14303     @SystemApi
14304     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getCallWaitingStatus(@onNull Executor executor, @NonNull @CallWaitingStatus Consumer<Integer> resultListener)14305     public void getCallWaitingStatus(@NonNull Executor executor,
14306             @NonNull @CallWaitingStatus Consumer<Integer> resultListener) {
14307         Objects.requireNonNull(executor);
14308         Objects.requireNonNull(resultListener);
14309 
14310         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
14311             @Override
14312             public void accept(int result) {
14313                 executor.execute(() -> Binder.withCleanCallingIdentity(
14314                         () -> resultListener.accept(result)));
14315             }
14316         };
14317 
14318         try {
14319             ITelephony telephony = getITelephony();
14320             if (telephony != null) {
14321                 telephony.getCallWaitingStatus(getSubId(), internalCallback);
14322             }
14323         } catch (RemoteException ex) {
14324             Rlog.e(TAG, "getCallWaitingStatus RemoteException", ex);
14325             ex.rethrowAsRuntimeException();
14326         } catch (NullPointerException ex) {
14327             Rlog.e(TAG, "getCallWaitingStatus NPE", ex);
14328             throw ex;
14329         }
14330     }
14331 
14332     /**
14333      * Sets the call waiting status of this device with the network.
14334      *
14335      * If you wish to be notified about the results of this operation, provide an {@link Executor}
14336      * and {@link Consumer<Integer>} to be notified asynchronously when the operation completes.
14337      *
14338      * @see #getCallWaitingStatus for a description of the call waiting functionality.
14339      *
14340      * @param enabled {@code true} to enable; {@code false} to disable.
14341      * @param executor The executor on which the listener will be called. Must be non-null if
14342      *                 {@code listener} is non-null.
14343      * @param resultListener Asynchronous listener that'll be called when the operation completes.
14344      *                       Called with the new call waiting status (either
14345      *                       {@link #CALL_WAITING_STATUS_ENABLED} or
14346      *                       {@link #CALL_WAITING_STATUS_DISABLED} if the operation succeeded and
14347      *                       {@link #CALL_WAITING_STATUS_NOT_SUPPORTED} or
14348      *                       {@link #CALL_WAITING_STATUS_UNKNOWN_ERROR} if it failed.
14349      * @hide
14350      */
14351     @SystemApi
14352     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setCallWaitingEnabled(boolean enabled, @Nullable Executor executor, @Nullable Consumer<Integer> resultListener)14353     public void setCallWaitingEnabled(boolean enabled, @Nullable Executor executor,
14354             @Nullable Consumer<Integer> resultListener) {
14355         if (resultListener != null) {
14356             Objects.requireNonNull(executor);
14357         }
14358 
14359         IIntegerConsumer internalCallback = new IIntegerConsumer.Stub() {
14360             @Override
14361             public void accept(int result) {
14362                 executor.execute(() ->
14363                         Binder.withCleanCallingIdentity(() -> resultListener.accept(result)));
14364             }
14365         };
14366 
14367         try {
14368             ITelephony telephony = getITelephony();
14369             if (telephony != null) {
14370                 telephony.setCallWaitingStatus(getSubId(), enabled, internalCallback);
14371             }
14372         } catch (RemoteException ex) {
14373             Rlog.e(TAG, "setCallWaitingStatus RemoteException", ex);
14374             ex.rethrowAsRuntimeException();
14375         } catch (NullPointerException ex) {
14376             Rlog.e(TAG, "setCallWaitingStatus NPE", ex);
14377             throw ex;
14378         }
14379     }
14380 
14381     /**
14382      * Controls whether mobile data  on the non-default SIM is allowed during a voice call.
14383      *
14384      * This is used for allowing data on the non-default data SIM when a voice call is placed on
14385      * the non-default data SIM on DSDS devices. If this policy is disabled, users will not be able
14386      * to use mobile data via the non-default data SIM during the call, which may mean no mobile
14387      * data at all since some modem implementations disallow mobile data via the default data SIM
14388      * during voice calls.
14389      * If this policy is enabled, data will be temporarily enabled on the non-default data SIM
14390      * during any voice calls.
14391      *
14392      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
14393      * @hide
14394      */
14395     @SystemApi
14396     public static final int MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL = 1;
14397 
14398     /**
14399      * Controls whether MMS messages bypass the user-specified "mobile data" toggle.
14400      *
14401      * When enabled, requests for connections to the MMS APN will be accepted by telephony even if
14402      * the user has turned "mobile data" off on this specific sim card. {@link #isDataEnabledForApn}
14403      * will also return true for {@link ApnSetting#TYPE_MMS}.
14404      * When disabled, the MMS APN will be governed by the same rules as all other APNs.
14405      *
14406      * This policy can be enabled and disabled via {@link #setMobileDataPolicyEnabled}.
14407      * @hide
14408      */
14409     @SystemApi
14410     public static final int MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED = 2;
14411 
14412     /**
14413      * @hide
14414      */
14415     @IntDef(prefix = { "MOBILE_DATA_POLICY_" }, value = {
14416             MOBILE_DATA_POLICY_DATA_ON_NON_DEFAULT_DURING_VOICE_CALL,
14417             MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED,
14418     })
14419     @Retention(RetentionPolicy.SOURCE)
14420     public @interface MobileDataPolicy { }
14421 
14422     /**
14423      * Enables or disables a piece of mobile data policy.
14424      *
14425      * Enables or disables the mobile data policy specified in {@code policy}. See the detailed
14426      * description of each policy constant for what they do.
14427      *
14428      * @param policy The data policy to enable.
14429      * @param enabled Whether to enable or disable the policy.
14430      * @hide
14431      */
14432     @SystemApi
14433     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setMobileDataPolicyEnabled(@obileDataPolicy int policy, boolean enabled)14434     public void setMobileDataPolicyEnabled(@MobileDataPolicy int policy, boolean enabled) {
14435         try {
14436             ITelephony service = getITelephony();
14437             if (service != null) {
14438                 service.setMobileDataPolicyEnabled(getSubId(), policy, enabled);
14439             }
14440         } catch (RemoteException ex) {
14441             Rlog.e(TAG, "Telephony#setMobileDataPolicyEnabled RemoteException" + ex);
14442         }
14443     }
14444 
14445     /**
14446      * Fetches the status of a piece of mobile data policy.
14447      *
14448      * @param policy The data policy that you want the status for.
14449      * @return {@code true} if enabled, {@code false} otherwise.
14450      * @hide
14451      */
14452     @SystemApi
14453     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
isMobileDataPolicyEnabled(@obileDataPolicy int policy)14454     public boolean isMobileDataPolicyEnabled(@MobileDataPolicy int policy) {
14455         try {
14456             ITelephony service = getITelephony();
14457             if (service != null) {
14458                 return service.isMobileDataPolicyEnabled(getSubId(), policy);
14459             }
14460         } catch (RemoteException ex) {
14461             Rlog.e(TAG, "Telephony#isMobileDataPolicyEnabled RemoteException" + ex);
14462         }
14463         return false;
14464     }
14465 
14466     /**
14467      * Indicates that the ICC PIN lock state or PIN was changed successfully.
14468      * @hide
14469      */
14470     public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
14471 
14472     /**
14473      * Check whether ICC PIN lock is enabled.
14474      * This is a sync call which returns the cached PIN enabled state.
14475      *
14476      * @return {@code true} if ICC PIN lock enabled, {@code false} if disabled.
14477      * @throws SecurityException if the caller doesn't have the permission.
14478      * @throws IllegalStateException if the Telephony process is not currently available.
14479      *
14480      * <p>Requires Permission:
14481      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
14482      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
14483      *
14484      * @hide
14485      */
14486     @WorkerThread
14487     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14488     @SystemApi
isIccLockEnabled()14489     public boolean isIccLockEnabled() {
14490         try {
14491             ITelephony telephony = getITelephony();
14492             if (telephony != null) {
14493                 return telephony.isIccLockEnabled(getSubId());
14494             } else {
14495                 throw new IllegalStateException("telephony service is null.");
14496             }
14497         } catch (RemoteException e) {
14498             Log.e(TAG, "isIccLockEnabled RemoteException", e);
14499             e.rethrowFromSystemServer();
14500         }
14501         return false;
14502     }
14503 
14504     /**
14505      * Enable or disable the ICC PIN lock.
14506      *
14507      * @param enabled "true" for locked, "false" for unlocked.
14508      * @param pin needed to change the ICC PIN lock, aka. Pin1.
14509      * @return the result of enabling or disabling the ICC PIN lock.
14510      * @throws SecurityException if the caller doesn't have the permission.
14511      * @throws IllegalStateException if the Telephony process is not currently available.
14512      *
14513      * <p>Requires Permission:
14514      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
14515      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
14516      *
14517      * @hide
14518      */
14519     @SystemApi
14520     @NonNull
14521     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setIccLockEnabled(boolean enabled, @NonNull String pin)14522     public PinResult setIccLockEnabled(boolean enabled, @NonNull String pin) {
14523         checkNotNull(pin, "setIccLockEnabled pin can't be null.");
14524         try {
14525             ITelephony telephony = getITelephony();
14526             if (telephony != null) {
14527                 int result = telephony.setIccLockEnabled(getSubId(), enabled, pin);
14528                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
14529                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
14530                 } else if (result < 0) {
14531                     return PinResult.getDefaultFailedResult();
14532                 } else {
14533                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
14534                 }
14535             } else {
14536                 throw new IllegalStateException("telephony service is null.");
14537             }
14538         } catch (RemoteException e) {
14539             Log.e(TAG, "setIccLockEnabled RemoteException", e);
14540             e.rethrowFromSystemServer();
14541         }
14542         return PinResult.getDefaultFailedResult();
14543     }
14544 
14545     /**
14546      * Change the ICC lock PIN.
14547      *
14548      * @param oldPin is the old PIN
14549      * @param newPin is the new PIN
14550      * @return The result of changing the ICC lock PIN.
14551      * @throws SecurityException if the caller doesn't have the permission.
14552      * @throws IllegalStateException if the Telephony process is not currently available.
14553      *
14554      * <p>Requires Permission:
14555      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
14556      * app has carrier privileges (see {@link #hasCarrierPrivileges}).
14557      *
14558      * @hide
14559      */
14560     @SystemApi
14561     @NonNull
14562     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
changeIccLockPin(@onNull String oldPin, @NonNull String newPin)14563     public PinResult changeIccLockPin(@NonNull String oldPin, @NonNull String newPin) {
14564         checkNotNull(oldPin, "changeIccLockPin oldPin can't be null.");
14565         checkNotNull(newPin, "changeIccLockPin newPin can't be null.");
14566         try {
14567             ITelephony telephony = getITelephony();
14568             if (telephony != null) {
14569                 int result = telephony.changeIccLockPassword(getSubId(), oldPin, newPin);
14570                 if (result == CHANGE_ICC_LOCK_SUCCESS) {
14571                     return new PinResult(PinResult.PIN_RESULT_TYPE_SUCCESS, 0);
14572                 } else if (result < 0) {
14573                     return PinResult.getDefaultFailedResult();
14574                 } else {
14575                     return new PinResult(PinResult.PIN_RESULT_TYPE_INCORRECT, result);
14576                 }
14577             } else {
14578                 throw new IllegalStateException("telephony service is null.");
14579             }
14580         } catch (RemoteException e) {
14581             Log.e(TAG, "changeIccLockPin RemoteException", e);
14582             e.rethrowFromSystemServer();
14583         }
14584         return PinResult.getDefaultFailedResult();
14585     }
14586 
14587     /**
14588      * Called when userActivity is signalled in the power manager.
14589      * This should only be called from system Uid.
14590      * @hide
14591      */
14592     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
notifyUserActivity()14593     public void notifyUserActivity() {
14594         try {
14595             ITelephony service = getITelephony();
14596             if (service != null) {
14597                 service.userActivity();
14598             }
14599         } catch (RemoteException e) {
14600             // one-way notification, if telephony is not available, it is okay to not throw
14601             // exception here.
14602             Log.w(TAG, "notifyUserActivity exception: " + e.getMessage());
14603         }
14604     }
14605 
14606     /**
14607      * No error. Operation succeeded.
14608      * @hide
14609      */
14610     @SystemApi
14611     public static final int ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS = 0;
14612 
14613     /**
14614      * NR Dual connectivity enablement is not supported.
14615      * @hide
14616      */
14617     @SystemApi
14618     public static final int ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED = 1;
14619 
14620     /**
14621      * Radio is not available.
14622      * @hide
14623      */
14624     @SystemApi
14625     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE = 2;
14626 
14627     /**
14628      * Internal Radio error.
14629      * @hide
14630      */
14631     @SystemApi
14632     public static final int ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR = 3;
14633 
14634     /**
14635      * Currently in invalid state. Not able to process the request.
14636      * @hide
14637      */
14638     @SystemApi
14639     public static final int ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE = 4;
14640 
14641     /** @hide */
14642     @Retention(RetentionPolicy.SOURCE)
14643     @IntDef(prefix = {"ENABLE_NR_DUAL_CONNECTIVITY"}, value = {
14644             ENABLE_NR_DUAL_CONNECTIVITY_SUCCESS,
14645             ENABLE_NR_DUAL_CONNECTIVITY_NOT_SUPPORTED,
14646             ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE,
14647             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_NOT_AVAILABLE,
14648             ENABLE_NR_DUAL_CONNECTIVITY_RADIO_ERROR})
14649     public @interface EnableNrDualConnectivityResult {}
14650 
14651     /**
14652      * Enable NR dual connectivity. Enabled state does not mean dual connectivity
14653      * is active. It means device is allowed to connect to both primary and secondary.
14654      *
14655      * @hide
14656      */
14657     @SystemApi
14658     public static final int NR_DUAL_CONNECTIVITY_ENABLE = 1;
14659 
14660     /**
14661      * Disable NR dual connectivity. Disabled state does not mean the secondary cell is released.
14662      * Modem will release it only if the current bearer is released to avoid radio link failure.
14663      * @hide
14664      */
14665     @SystemApi
14666     public static final int NR_DUAL_CONNECTIVITY_DISABLE = 2;
14667 
14668     /**
14669      * Disable NR dual connectivity and force the secondary cell to be released if dual connectivity
14670      * was active. This will result in radio link failure.
14671      * @hide
14672      */
14673     @SystemApi
14674     public static final int NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE = 3;
14675 
14676     /**
14677      * @hide
14678      */
14679     @IntDef(prefix = { "NR_DUAL_CONNECTIVITY_" }, value = {
14680             NR_DUAL_CONNECTIVITY_ENABLE,
14681             NR_DUAL_CONNECTIVITY_DISABLE,
14682             NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE,
14683     })
14684     @Retention(RetentionPolicy.SOURCE)
14685     public @interface NrDualConnectivityState {
14686     }
14687 
14688     /**
14689      * Enable/Disable E-UTRA-NR Dual Connectivity.
14690      *
14691      * This api is supported only if
14692      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
14693      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
14694      * returns true.
14695      * @param nrDualConnectivityState expected NR dual connectivity state
14696      * This can be passed following states
14697      * <ol>
14698      * <li>Enable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_ENABLE}
14699      * <li>Disable NR dual connectivity {@link #NR_DUAL_CONNECTIVITY_DISABLE}
14700      * <li>Disable NR dual connectivity and force secondary cell to be released
14701      * {@link #NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE}
14702      * </ol>
14703      * @return operation result.
14704      * @throws IllegalStateException if the Telephony process is not currently available.
14705      * @hide
14706      */
14707     @SystemApi
14708     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
14709     @RequiresFeature(
14710             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
14711             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
setNrDualConnectivityState( @rDualConnectivityState int nrDualConnectivityState)14712     public @EnableNrDualConnectivityResult int setNrDualConnectivityState(
14713             @NrDualConnectivityState int nrDualConnectivityState) {
14714         try {
14715             ITelephony telephony = getITelephony();
14716             if (telephony != null) {
14717                 return telephony.setNrDualConnectivityState(getSubId(), nrDualConnectivityState);
14718             } else {
14719                 throw new IllegalStateException("telephony service is null.");
14720             }
14721         } catch (RemoteException ex) {
14722             Rlog.e(TAG, "setNrDualConnectivityState RemoteException", ex);
14723             ex.rethrowFromSystemServer();
14724         }
14725 
14726         return ENABLE_NR_DUAL_CONNECTIVITY_INVALID_STATE;
14727     }
14728 
14729     /**
14730      * Is E-UTRA-NR Dual Connectivity enabled.
14731      * This api is supported only if
14732      * {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}
14733      * ({@link TelephonyManager#CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE})
14734      * returns true.
14735      * @return true if dual connectivity is enabled else false. Enabled state does not mean dual
14736      * connectivity is active. It means the device is allowed to connect to both primary and
14737      * secondary cell.
14738      * @throws IllegalStateException if the Telephony process is not currently available.
14739      * @hide
14740      */
14741     @SystemApi
14742     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
14743     @RequiresFeature(
14744             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
14745             value = TelephonyManager.CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE)
isNrDualConnectivityEnabled()14746     public boolean isNrDualConnectivityEnabled() {
14747         try {
14748             ITelephony telephony = getITelephony();
14749             if (telephony != null) {
14750                 return telephony.isNrDualConnectivityEnabled(getSubId());
14751             } else {
14752                 throw new IllegalStateException("telephony service is null.");
14753             }
14754         } catch (RemoteException ex) {
14755             Rlog.e(TAG, "isNRDualConnectivityEnabled RemoteException", ex);
14756             ex.rethrowFromSystemServer();
14757         }
14758         return false;
14759     }
14760 
14761     private static class DeathRecipient implements IBinder.DeathRecipient {
14762         @Override
binderDied()14763         public void binderDied() {
14764             resetServiceCache();
14765         }
14766     }
14767 
14768    /**
14769     * Reset everything in the service cache; if one handle died then they are
14770     * all probably broken.
14771     * @hide
14772     */
resetServiceCache()14773     private static void resetServiceCache() {
14774         synchronized (sCacheLock) {
14775             if (sITelephony != null) {
14776                 sITelephony.asBinder().unlinkToDeath(sServiceDeath, 0);
14777                 sITelephony = null;
14778             }
14779             if (sISub != null) {
14780                 sISub.asBinder().unlinkToDeath(sServiceDeath, 0);
14781                 sISub = null;
14782                 SubscriptionManager.clearCaches();
14783             }
14784             if (sISms != null) {
14785                 sISms.asBinder().unlinkToDeath(sServiceDeath, 0);
14786                 sISms = null;
14787             }
14788             if (sIPhoneSubInfo != null) {
14789                 sIPhoneSubInfo.asBinder().unlinkToDeath(sServiceDeath, 0);
14790                 sIPhoneSubInfo = null;
14791             }
14792         }
14793     }
14794 
14795     /**
14796      * @hide
14797      */
getSubscriberInfoService()14798     static IPhoneSubInfo getSubscriberInfoService() {
14799         // Keeps cache disabled until test fixes are checked into AOSP.
14800         if (!sServiceHandleCacheEnabled) {
14801             return IPhoneSubInfo.Stub.asInterface(
14802                 TelephonyFrameworkInitializer
14803                         .getTelephonyServiceManager()
14804                         .getPhoneSubServiceRegisterer()
14805                         .get());
14806         }
14807 
14808         if (sIPhoneSubInfo == null) {
14809             IPhoneSubInfo temp = IPhoneSubInfo.Stub.asInterface(
14810                     TelephonyFrameworkInitializer
14811                         .getTelephonyServiceManager()
14812                         .getPhoneSubServiceRegisterer()
14813                         .get());
14814             synchronized (sCacheLock) {
14815                 if (sIPhoneSubInfo == null && temp != null) {
14816                     try {
14817                         sIPhoneSubInfo = temp;
14818                         sIPhoneSubInfo.asBinder().linkToDeath(sServiceDeath, 0);
14819                     } catch (Exception e) {
14820                         // something has gone horribly wrong
14821                         sIPhoneSubInfo = null;
14822                     }
14823                 }
14824             }
14825         }
14826         return sIPhoneSubInfo;
14827     }
14828 
14829    /**
14830     * @hide
14831     */
getSubscriptionService()14832     static ISub getSubscriptionService() {
14833         // Keeps cache disabled until test fixes are checked into AOSP.
14834         if (!sServiceHandleCacheEnabled) {
14835             return ISub.Stub.asInterface(
14836                     TelephonyFrameworkInitializer
14837                             .getTelephonyServiceManager()
14838                             .getSubscriptionServiceRegisterer()
14839                             .get());
14840         }
14841 
14842         if (sISub == null) {
14843             ISub temp = ISub.Stub.asInterface(
14844                     TelephonyFrameworkInitializer
14845                             .getTelephonyServiceManager()
14846                             .getSubscriptionServiceRegisterer()
14847                             .get());
14848             synchronized (sCacheLock) {
14849                 if (sISub == null && temp != null) {
14850                     try {
14851                         sISub = temp;
14852                         sISub.asBinder().linkToDeath(sServiceDeath, 0);
14853                     } catch (Exception e) {
14854                         // something has gone horribly wrong
14855                         sISub = null;
14856                     }
14857                 }
14858             }
14859         }
14860         return sISub;
14861     }
14862 
14863     /**
14864     * @hide
14865     */
getSmsService()14866     static ISms getSmsService() {
14867         // Keeps cache disabled until test fixes are checked into AOSP.
14868         if (!sServiceHandleCacheEnabled) {
14869             return ISms.Stub.asInterface(
14870                     TelephonyFrameworkInitializer
14871                             .getTelephonyServiceManager()
14872                             .getSmsServiceRegisterer()
14873                             .get());
14874         }
14875 
14876         if (sISms == null) {
14877             ISms temp = ISms.Stub.asInterface(
14878                     TelephonyFrameworkInitializer
14879                             .getTelephonyServiceManager()
14880                             .getSmsServiceRegisterer()
14881                             .get());
14882             synchronized (sCacheLock) {
14883                 if (sISms == null && temp != null) {
14884                     try {
14885                         sISms = temp;
14886                         sISms.asBinder().linkToDeath(sServiceDeath, 0);
14887                     } catch (Exception e) {
14888                         // something has gone horribly wrong
14889                         sISms = null;
14890                     }
14891                 }
14892             }
14893         }
14894         return sISms;
14895     }
14896 
14897     /**
14898      * Disables service handle caching for tests that utilize mock services.
14899      * @hide
14900      */
14901     @VisibleForTesting
disableServiceHandleCaching()14902     public static void disableServiceHandleCaching() {
14903         sServiceHandleCacheEnabled = false;
14904     }
14905 
14906     /**
14907      * Reenables service handle caching.
14908      * @hide
14909      */
14910     @VisibleForTesting
enableServiceHandleCaching()14911     public static void enableServiceHandleCaching() {
14912         sServiceHandleCacheEnabled = true;
14913     }
14914 
14915     /**
14916      * Setup sITelephony for testing.
14917      * @hide
14918      */
14919     @VisibleForTesting
setupITelephonyForTest(ITelephony telephony)14920     public static void setupITelephonyForTest(ITelephony telephony) {
14921         sITelephony = telephony;
14922     }
14923 
14924     /**
14925      * Whether device can connect to 5G network when two SIMs are active.
14926      * @hide
14927      * TODO b/153669716: remove or make system API.
14928      */
canConnectTo5GInDsdsMode()14929     public boolean canConnectTo5GInDsdsMode() {
14930         ITelephony telephony = getITelephony();
14931         if (telephony == null) return true;
14932         try {
14933             return telephony.canConnectTo5GInDsdsMode();
14934         } catch (RemoteException ex) {
14935             return true;
14936         } catch (NullPointerException ex) {
14937             return true;
14938         }
14939     }
14940 
14941     /**
14942      * Returns a list of the equivalent home PLMNs (EF_EHPLMN) from the USIM app.
14943      *
14944      * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
14945      * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
14946      *
14947      * @return A list of equivalent home PLMNs. Returns an empty list if EF_EHPLMN is empty or
14948      * does not exist on the SIM card.
14949      *
14950      * @throws IllegalStateException if the Telephony process is not currently available.
14951      * @throws SecurityException if the caller doesn't have the permission.
14952      *
14953      */
14954     @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
getEquivalentHomePlmns()14955     public @NonNull List<String> getEquivalentHomePlmns() {
14956         try {
14957             ITelephony telephony = getITelephony();
14958             if (telephony != null) {
14959                 return telephony.getEquivalentHomePlmns(getSubId(), mContext.getOpPackageName(),
14960                         getAttributionTag());
14961             } else {
14962                 throw new IllegalStateException("telephony service is null.");
14963             }
14964         } catch (RemoteException ex) {
14965             Rlog.e(TAG, "Telephony#getEquivalentHomePlmns RemoteException" + ex);
14966         }
14967 
14968         return Collections.emptyList();
14969     }
14970 
14971     /**
14972      * Indicates whether {@link CarrierBandwidth#getSecondaryDownlinkCapacityKbps()} and
14973      * {@link CarrierBandwidth#getSecondaryUplinkCapacityKbps()} are visible.  See comments
14974      * on respective methods for more information.
14975      *
14976      * @hide
14977      */
14978     @SystemApi
14979     public static final String CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE =
14980             "CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE";
14981 
14982     /**
14983      * Indicates whether {@link #setPreferredNetworkType}, {@link
14984      * #setPreferredNetworkTypeBitmask}, {@link #setAllowedNetworkTypes} and
14985      * {@link #setAllowedNetworkTypesForReason} rely on
14986      * setAllowedNetworkTypesBitmap instead of setPreferredNetworkTypesBitmap on the radio
14987      * interface.
14988      *
14989      * @hide
14990      */
14991     @SystemApi
14992     public static final String CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK =
14993             "CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK";
14994 
14995     /**
14996      * Indicates whether {@link #setNrDualConnectivityState()} and
14997      * {@link #isNrDualConnectivityEnabled()} ()} are available.  See comments
14998      * on respective methods for more information.
14999      *
15000      * @hide
15001      */
15002     @SystemApi
15003     public static final String CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE =
15004             "CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE";
15005 
15006     /**
15007      * Indicates whether a data throttling request sent with {@link #sendThermalMitigationRequest}
15008      * is supported. See comments on {@link #sendThermalMitigationRequest} for more information.
15009      *
15010      * @hide
15011      */
15012     @SystemApi
15013     public static final String CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING =
15014             "CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING";
15015 
15016     /**
15017      * Indicates whether {@link #getNetworkSlicingConfiguration} is supported. See comments on
15018      * respective methods for more information.
15019      */
15020     public static final String CAPABILITY_SLICING_CONFIG_SUPPORTED =
15021             "CAPABILITY_SLICING_CONFIG_SUPPORTED";
15022 
15023     /**
15024      * Indicates whether PHYSICAL_CHANNEL_CONFIG HAL1.6 is supported. See comments on
15025      * respective methods for more information.
15026      *
15027      * @hide
15028      */
15029     public static final String CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED =
15030             "CAPABILITY_PHYSICAL_CHANNEL_CONFIG_1_6_SUPPORTED";
15031 
15032     /**
15033      * Indicates whether modem supports handling parsed SIM phonebook records through the RIL,
15034      * both batched reads and individual writes.
15035      *
15036      * @hide
15037      */
15038     public static final String CAPABILITY_SIM_PHONEBOOK_IN_MODEM =
15039             "CAPABILITY_SIM_PHONEBOOK_IN_MODEM";
15040 
15041     /**
15042      * A list of the radio interface capability values with public valid constants.
15043      *
15044      * Here is a related list for the systemapi-only valid constants:
15045      *     CAPABILITY_SECONDARY_LINK_BANDWIDTH_VISIBLE
15046      *     CAPABILITY_USES_ALLOWED_NETWORK_TYPES_BITMASK
15047      *     CAPABILITY_NR_DUAL_CONNECTIVITY_CONFIGURATION_AVAILABLE
15048      *     CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING
15049      *
15050      * @hide
15051      * TODO(b/185508047): Doc generation for mixed public/systemapi StringDefs formats badly.
15052      */
15053     @Retention(RetentionPolicy.SOURCE)
15054     @StringDef(prefix = "CAPABILITY_", value = {
15055             CAPABILITY_SLICING_CONFIG_SUPPORTED,
15056             CAPABILITY_SIM_PHONEBOOK_IN_MODEM,
15057     })
15058     public @interface RadioInterfaceCapability {}
15059 
15060     /**
15061      * Whether the device supports a given capability on the radio interface.
15062      *
15063      * If the capability is not in the set of radio interface capabilities, false is returned.
15064      *
15065      * @param capability the name of the capability to check for
15066      * @return the availability of the capability
15067      */
isRadioInterfaceCapabilitySupported( @onNull @adioInterfaceCapability String capability)15068     public boolean isRadioInterfaceCapabilitySupported(
15069             @NonNull @RadioInterfaceCapability String capability) {
15070         try {
15071             if (capability == null) return false;
15072 
15073             ITelephony telephony = getITelephony();
15074             if (telephony != null) {
15075                 return telephony.isRadioInterfaceCapabilitySupported(capability);
15076             } else {
15077                 throw new IllegalStateException("telephony service is null.");
15078             }
15079         } catch (RemoteException ex) {
15080             Rlog.e(TAG, "Telephony#isRadioInterfaceCapabilitySupported RemoteException" + ex);
15081         }
15082         return false;
15083     }
15084 
15085     /**
15086      * Indicates that the thermal mitigation request was completed successfully.
15087      *
15088      * @hide
15089      */
15090     @SystemApi
15091     public static final int THERMAL_MITIGATION_RESULT_SUCCESS = 0;
15092 
15093     /**
15094      * Indicates that the thermal mitigation request was not completed because of a modem error.
15095      *
15096      * @hide
15097      */
15098     @SystemApi
15099     public static final int THERMAL_MITIGATION_RESULT_MODEM_ERROR = 1;
15100 
15101     /**
15102      * Indicates that the thermal mitigation request was not completed because the modem is not
15103      * available.
15104      *
15105      * @hide
15106      */
15107     @SystemApi
15108     public static final int THERMAL_MITIGATION_RESULT_MODEM_NOT_AVAILABLE = 2;
15109 
15110     /**
15111      * Indicates that the thermal mitigation request could not power off the radio due to the device
15112      * either being in an active emergency voice call, device pending an emergency call, or any
15113      * other state that would disallow powering off of radio.
15114      *
15115      * @hide
15116      */
15117     @SystemApi
15118     public static final int THERMAL_MITIGATION_RESULT_INVALID_STATE = 3;
15119 
15120     /**
15121      * Indicates that the thermal mitigation request resulted an unknown error.
15122      *
15123      * @hide
15124      */
15125     @SystemApi
15126     public static final int THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR = 4;
15127 
15128     /**
15129      * Thermal mitigation request to control functionalities at modem. Thermal mitigation is done
15130      * per-subscription. Caller must be sure to bind the TelephonyManager instance to subId by
15131      * calling {@link #createForSubscriptionId(int)} if they want thermal mitigation on a specific
15132      * subscription Id. Otherwise, TelephonyManager will use the default subscription.
15133      *
15134      * Calling this does not guarantee that the thermal mitigation action requested was done to
15135      * completion. A thermal module should actively monitor the temperature levels and request an
15136      * appropriate thermal mitigation action. Every action is assumed to be done 'on top of' the
15137      * previous action, where the order of actions from least thermal mitigation to most is as
15138      * follows:
15139      * <ol>
15140      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_DATA_THROTTLING}</li>
15141      *   <ol>
15142      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING}</li>
15143      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}</li>
15144      *      <li>{@link DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER}</li>
15145      *   </ol>
15146      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY}</li>
15147      *   <li>{@link ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}</li>
15148      * </ol>
15149      *
15150      * So, for example, requesting {@link
15151      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will ensure that the
15152      * data on secondary carrier has been disabled before throttling on primary carrier. {@link
15153      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} will ensure that data on both
15154      * primary and secondary have been disabled. {@link
15155      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF} will ensure that voice is
15156      * disabled and that data on both primary and secondary carriers are disabled before turning
15157      * radio off. {@link DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD} is not part of the order
15158      * and can be used at any time during data throttling to hold onto the current level of data
15159      * throttling.
15160      *
15161      * <p> If {@link android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported}({@link
15162      * #CAPABILITY_THERMAL_MITIGATION_DATA_THROTTLING}) returns false, then sending a {@link
15163      * DataThrottlingRequest#DATA_THROTTLING_ACTION_HOLD}, {@link
15164      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER}, or {@link
15165      * DataThrottlingRequest#DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER} will result in {@link
15166      * IllegalArgumentException} being thrown. However, on devices that do not
15167      * support data throttling, {@link
15168      * DataThrottlingRequest#DATA_THROTTLING_ACTION_NO_DATA_THROTTLING} can still be requested in
15169      * order to undo the mitigations above it (i.e {@link
15170      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_VOICE_ONLY} and/or {@link
15171      * ThermalMitigationRequest#THERMAL_MITIGATION_ACTION_RADIO_OFF}). </p>
15172      *
15173      * <p> In addition to the {@link Manifest.permission#MODIFY_PHONE_STATE} permission, callers of
15174      * this API must also be listed in the device configuration as an authorized app in
15175      * {@code packages/services/Telephony/res/values/config.xml} under the
15176      * {@code thermal_mitigation_allowlisted_packages} key. </p>
15177      *
15178      * @param thermalMitigationRequest Thermal mitigation request. See {@link
15179      * ThermalMitigationRequest} for details.
15180      *
15181      * @throws IllegalStateException if the Telephony process is not currently available.
15182      * @throws IllegalArgumentException if the thermalMitigationRequest had invalid parameters or
15183      * if the device's modem does not support data throttling.
15184      *
15185      * @hide
15186      */
15187     @SystemApi
15188     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
15189     @ThermalMitigationResult
sendThermalMitigationRequest( @onNull ThermalMitigationRequest thermalMitigationRequest)15190     public int sendThermalMitigationRequest(
15191             @NonNull ThermalMitigationRequest thermalMitigationRequest) {
15192         try {
15193             ITelephony telephony = getITelephony();
15194             if (telephony != null) {
15195                 return telephony.sendThermalMitigationRequest(getSubId(), thermalMitigationRequest,
15196                         getOpPackageName());
15197             }
15198             throw new IllegalStateException("telephony service is null.");
15199         } catch (RemoteException ex) {
15200             Log.e(TAG, "Telephony#thermalMitigationRequest RemoteException", ex);
15201             ex.rethrowFromSystemServer();
15202         }
15203         return THERMAL_MITIGATION_RESULT_UNKNOWN_ERROR;
15204     }
15205 
15206     /**
15207      * Registers a callback object to receive notification of changes in specified telephony states.
15208      * <p>
15209      * To register a callback, pass a {@link TelephonyCallback} which implements
15210      * interfaces of events. For example,
15211      * FakeServiceStateCallback extends {@link TelephonyCallback} implements
15212      * {@link TelephonyCallback.ServiceStateListener}.
15213      *
15214      * At registration, and when a specified telephony state changes, the telephony manager invokes
15215      * the appropriate callback method on the callback object and passes the current (updated)
15216      * values.
15217      * <p>
15218      *
15219      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
15220      * applies to the given subId. Otherwise, applies to
15221      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To register events for multiple
15222      * subIds, pass a separate callback object to each TelephonyManager object created with
15223      * {@link #createForSubscriptionId}.
15224      *
15225      * Note: if you call this method while in the middle of a binder transaction, you <b>must</b>
15226      * call {@link android.os.Binder#clearCallingIdentity()} before calling this method. A
15227      * {@link SecurityException} will be thrown otherwise.
15228      *
15229      * This API should be used sparingly -- large numbers of callbacks will cause system
15230      * instability. If a process has registered too many callbacks without unregistering them, it
15231      * may encounter an {@link IllegalStateException} when trying to register more callbacks.
15232      *
15233      * @param executor The executor of where the callback will execute.
15234      * @param callback The {@link TelephonyCallback} object to register.
15235      */
registerTelephonyCallback(@onNull @allbackExecutor Executor executor, @NonNull TelephonyCallback callback)15236     public void registerTelephonyCallback(@NonNull @CallbackExecutor Executor executor,
15237             @NonNull TelephonyCallback callback) {
15238 
15239         if (mContext == null) {
15240             throw new IllegalStateException("telephony service is null.");
15241         }
15242 
15243         if (executor == null || callback == null) {
15244             throw new IllegalArgumentException("TelephonyCallback and executor must be non-null");
15245         }
15246         mTelephonyRegistryMgr = (TelephonyRegistryManager)
15247                 mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
15248         if (mTelephonyRegistryMgr != null) {
15249             mTelephonyRegistryMgr.registerTelephonyCallback(executor, mSubId, getOpPackageName(),
15250                     getAttributionTag(), callback, getITelephony() != null);
15251         } else {
15252             throw new IllegalStateException("telephony service is null.");
15253         }
15254     }
15255 
15256     /**
15257      * Unregister an existing {@link TelephonyCallback}.
15258      *
15259      * @param callback The {@link TelephonyCallback} object to unregister.
15260      */
unregisterTelephonyCallback(@onNull TelephonyCallback callback)15261     public void unregisterTelephonyCallback(@NonNull TelephonyCallback callback) {
15262 
15263         if (mContext == null) {
15264             throw new IllegalStateException("telephony service is null.");
15265         }
15266 
15267         if (callback.callback == null) {
15268             return;
15269         }
15270 
15271         mTelephonyRegistryMgr = mContext.getSystemService(TelephonyRegistryManager.class);
15272         if (mTelephonyRegistryMgr != null) {
15273             mTelephonyRegistryMgr.unregisterTelephonyCallback(mSubId, getOpPackageName(),
15274                     getAttributionTag(), callback, getITelephony() != null);
15275         } else {
15276             throw new IllegalStateException("telephony service is null.");
15277         }
15278     }
15279 
15280     /** @hide */
15281     @Retention(RetentionPolicy.SOURCE)
15282     @IntDef(prefix = {"GBA_FAILURE_REASON_"}, value = {
15283             GBA_FAILURE_REASON_UNKNOWN,
15284             GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED,
15285             GBA_FAILURE_REASON_FEATURE_NOT_READY,
15286             GBA_FAILURE_REASON_NETWORK_FAILURE,
15287             GBA_FAILURE_REASON_INCORRECT_NAF_ID,
15288             GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED})
15289     public @interface AuthenticationFailureReason {}
15290 
15291     /**
15292      * GBA Authentication has failed for an unknown reason.
15293      *
15294      * <p>The caller should retry a message that failed with this response.
15295      * @hide
15296      */
15297     @SystemApi
15298     public static final int GBA_FAILURE_REASON_UNKNOWN = 0;
15299 
15300     /**
15301      * GBA Authentication is not supported by the carrier, SIM or android.
15302      *
15303      * <p>Application should use other authentication mechanisms if possible.
15304      * @hide
15305      */
15306     @SystemApi
15307     public static final int GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED = 1;
15308 
15309     /**
15310      * GBA Authentication service is not ready for use.
15311      *
15312      * <p>Application could try again at a later time.
15313      * @hide
15314      */
15315     @SystemApi
15316     public static final int GBA_FAILURE_REASON_FEATURE_NOT_READY = 2;
15317 
15318     /**
15319      * GBA Authentication has been failed by the network.
15320      * @hide
15321      */
15322     @SystemApi
15323     public static final int GBA_FAILURE_REASON_NETWORK_FAILURE = 3;
15324 
15325     /**
15326      * GBA Authentication has failed due to incorrect NAF URL.
15327      * @hide
15328      */
15329     @SystemApi
15330     public static final int GBA_FAILURE_REASON_INCORRECT_NAF_ID = 4;
15331 
15332     /**
15333      * GBA Authentication has failed due to unsupported security protocol
15334      * @hide
15335      */
15336     @SystemApi
15337     public static final int GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED = 5;
15338 
15339     /**
15340      * The callback associated with a {@link #bootstrapAuthenticationRequest()}.
15341      * @hide
15342      */
15343     @SystemApi
15344     public static class BootstrapAuthenticationCallback {
15345 
15346         /**
15347          * Invoked when the previously requested GBA keys are available (@see
15348          * bootstrapAuthenticationRequest()).
15349          * @param gbaKey Ks_NAF/Ks_ext_NAF Response
15350          * @param transactionId Bootstrapping Transaction Identifier
15351          */
onKeysAvailable(@onNull byte[] gbaKey, @NonNull String transactionId)15352         public void onKeysAvailable(@NonNull byte[] gbaKey, @NonNull String transactionId) {}
15353 
15354         /**
15355          * @param reason The reason for the authentication failure.
15356          */
onAuthenticationFailure(@uthenticationFailureReason int reason)15357         public void onAuthenticationFailure(@AuthenticationFailureReason int reason) {}
15358     }
15359 
15360     /**
15361      * Used to get the Generic Bootstrapping Architecture authentication keys
15362      * KsNAF/Ks_ext_NAF for a particular NAF as defined in 3GPP spec TS 33.220 for
15363      * the specified sub id.
15364      *
15365      * <p>Application must be prepared to wait for receiving the Gba keys through the
15366      * registered callback and not invoke the API on the main application thread.
15367      * Application also must call the api to get the fresh key every time instead
15368      * of caching the key.
15369      *
15370      * Following steps may be invoked on the API call depending on the state of the
15371      * underlying GBA implementation:
15372      * <ol>
15373      *     <li>Resolve and bind to a Gba implementation.</li>
15374      *     <li>Run bootstrapping if no valid keys are available or bootstrapping is forced.</li>
15375      *     <li>Generate the ks_NAF/ ks_Ext_NAF to be returned via the callback.</li>
15376      * </ol>
15377      *
15378      * <p> Requires Permission:
15379      * <ul>
15380      *     <li>{@link android.Manifest.permission#MODIFY_PHONE_STATE},</li>
15381      *     <li>{@link android.Manifest.permission#PERFORM_IMS_SINGLE_REGISTRATION},</li>
15382      *     <li>or that the caller has carrier privileges (see
15383      *         {@link TelephonyManager#hasCarrierPrivileges()}).</li>
15384      * </ul>
15385      * @param appType icc application type, like {@link #APPTYPE_USIM} or {@link
15386      * #APPTYPE_ISIM} or {@link#APPTYPE_UNKNOWN}
15387      * @param nafId A URI to specify Network Application Function(NAF) fully qualified domain
15388      * name (FQDN) and the selected GBA mode. The authority of the URI must contain two parts
15389      * delimited by "@" sign. The first part is the constant string "3GPP-bootstrapping" (GBA_ME),
15390      * "3GPP-bootstrapping-uicc" (GBA_ U), or "3GPP-bootstrapping-digest" (GBA_Digest).
15391      * The second part shall be the FQDN of the NAF. The scheme of the URI is not actually used
15392      * for the authentication, which may be set the same as the resource that the application is
15393      * going to access. For example, the nafId can be
15394      * "https://3GPP-bootstrapping@naf1.operator.com",
15395      * "https://3GPP-bootstrapping-uicc@naf1.operator.com",
15396      * "https://3GPP-bootstrapping-digest@naf1.operator.com",
15397      * "ftps://3GPP-bootstrapping-digest@naf1.operator.com".
15398      * @param securityProtocol Security protocol identifier between UE and NAF.  See
15399      * 3GPP TS 33.220 Annex H. Application can use
15400      * {@link UaSecurityProtocolIdentifier#createDefaultUaSpId},
15401      * {@link UaSecurityProtocolIdentifier#create3GppUaSpId},
15402      * to create the ua security protocol identifier as needed
15403      * @param forceBootStrapping true=force bootstrapping, false=do not force
15404      * bootstrapping. Bootstrapping shouldn't be forced unless the application sees
15405      * authentication errors from the server.
15406      * @param e The {@link Executor} that will be used to call the Gba callback.
15407      * @param callback A callback called on the supplied {@link Executor} that will
15408      * contain the GBA Ks_NAF/Ks_ext_NAF when available. If the NAF keys are
15409      * available and valid at the time of call and bootstrapping is not requested,
15410      * then the callback shall be invoked with the available keys.
15411      * @hide
15412      */
15413     @SystemApi
15414     @WorkerThread
15415     @RequiresPermission(anyOf = {android.Manifest.permission.MODIFY_PHONE_STATE,
15416             Manifest.permission.PERFORM_IMS_SINGLE_REGISTRATION})
bootstrapAuthenticationRequest( @iccAppTypeExt int appType, @NonNull Uri nafId, @NonNull UaSecurityProtocolIdentifier securityProtocol, boolean forceBootStrapping, @NonNull Executor e, @NonNull BootstrapAuthenticationCallback callback)15417     public void bootstrapAuthenticationRequest(
15418             @UiccAppTypeExt int appType, @NonNull Uri nafId,
15419             @NonNull UaSecurityProtocolIdentifier securityProtocol,
15420             boolean forceBootStrapping, @NonNull Executor e,
15421             @NonNull BootstrapAuthenticationCallback callback) {
15422         try {
15423             ITelephony service = getITelephony();
15424             if (service == null) {
15425                 e.execute(() -> callback.onAuthenticationFailure(
15426                         GBA_FAILURE_REASON_FEATURE_NOT_READY));
15427                 return;
15428             }
15429             service.bootstrapAuthenticationRequest(
15430                     getSubId(), appType, nafId, securityProtocol, forceBootStrapping,
15431                     new IBootstrapAuthenticationCallback.Stub() {
15432                         @Override
15433                         public void onKeysAvailable(int token, byte[] gbaKey,
15434                                 String transactionId) {
15435                             final long identity = Binder.clearCallingIdentity();
15436                             try {
15437                                 e.execute(() -> callback.onKeysAvailable(gbaKey, transactionId));
15438                             } finally {
15439                                 Binder.restoreCallingIdentity(identity);
15440                             }
15441                         }
15442 
15443                         @Override
15444                         public void onAuthenticationFailure(int token, int reason) {
15445                             final long identity = Binder.clearCallingIdentity();
15446                             try {
15447                                 e.execute(() -> callback.onAuthenticationFailure(reason));
15448                             } finally {
15449                                 Binder.restoreCallingIdentity(identity);
15450                             }
15451                         }
15452                     });
15453         } catch (RemoteException exception) {
15454             Log.e(TAG, "Error calling ITelephony#bootstrapAuthenticationRequest", exception);
15455             e.execute(() -> callback.onAuthenticationFailure(GBA_FAILURE_REASON_FEATURE_NOT_READY));
15456         }
15457     }
15458 
15459     /**
15460      * The network type is valid or not.
15461      *
15462      * @param networkType The network type {@link NetworkType}.
15463      * @return {@code true} if valid, {@code false} otherwise.
15464      *
15465      * @hide
15466      */
isNetworkTypeValid(@etworkType int networkType)15467     public static boolean isNetworkTypeValid(@NetworkType int networkType) {
15468         return networkType >= TelephonyManager.NETWORK_TYPE_UNKNOWN &&
15469                 networkType <= TelephonyManager.NETWORK_TYPE_NR;
15470     }
15471 
15472     /**
15473      * Set a {@link SignalStrengthUpdateRequest} to receive notification when signal quality
15474      * measurements breach the specified thresholds.
15475      *
15476      * To be notified, set the signal strength update request and then register
15477      * {@link TelephonyManager#listen(PhoneStateListener, int)} with
15478      * {@link PhoneStateListener#LISTEN_SIGNAL_STRENGTHS}. The notification will arrive through
15479      * {@link PhoneStateListener#onSignalStrengthsChanged(SignalStrength)}.
15480      *
15481      * To stop receiving the notification over the specified thresholds, pass the same
15482      * {@link SignalStrengthUpdateRequest} object to
15483      * {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
15484      *
15485      * System will clean up the {@link SignalStrengthUpdateRequest} if the caller process died
15486      * without calling {@link #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)}.
15487      *
15488      * If this TelephonyManager object has been created with {@link #createForSubscriptionId},
15489      * applies to the given subId. Otherwise, applies to
15490      * {@link SubscriptionManager#getDefaultSubscriptionId()}. To request for multiple subIds,
15491      * pass a request object to each TelephonyManager object created with
15492      * {@link #createForSubscriptionId}.
15493      *
15494      * <p>Requires Permission:
15495      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
15496      * or that the calling app has carrier privileges (see
15497      * {@link TelephonyManager#hasCarrierPrivileges}).
15498      *
15499      * Note that the thresholds in the request will be used on a best-effort basis; the system may
15500      * modify requests to multiplex various request sources or to optimize power consumption. The
15501      * caller should not expect to be notified with the exactly the same thresholds.
15502      *
15503      * @see #clearSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
15504      *
15505      * @param request the SignalStrengthUpdateRequest to be set into the System
15506      *
15507      * @throws IllegalStateException if a new request is set with same subId from the same caller
15508      */
15509     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15510     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
setSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)15511     public void setSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
15512         Objects.requireNonNull(request, "request must not be null");
15513 
15514         try {
15515             ITelephony service = getITelephony();
15516             if (service != null) {
15517                 service.setSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
15518             }
15519         } catch (RemoteException e) {
15520             Log.e(TAG, "Error calling ITelephony#setSignalStrengthUpdateRequest", e);
15521         }
15522     }
15523 
15524     /**
15525      * Clear a {@link SignalStrengthUpdateRequest} from the system.
15526      *
15527      * <p>Requires Permission:
15528      * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
15529      * or that the calling app has carrier privileges (see
15530      * {@link TelephonyManager#hasCarrierPrivileges}).
15531      *
15532      * <p>If the given request was not set before, this operation is a no-op.
15533      *
15534      * @see #setSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)
15535      *
15536      * @param request the SignalStrengthUpdateRequest to be cleared from the System
15537      */
15538     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
15539     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
clearSignalStrengthUpdateRequest(@onNull SignalStrengthUpdateRequest request)15540     public void clearSignalStrengthUpdateRequest(@NonNull SignalStrengthUpdateRequest request) {
15541         Objects.requireNonNull(request, "request must not be null");
15542 
15543         try {
15544             ITelephony service = getITelephony();
15545             if (service != null) {
15546                 service.clearSignalStrengthUpdateRequest(getSubId(), request, getOpPackageName());
15547             }
15548         } catch (RemoteException e) {
15549             Log.e(TAG, "Error calling ITelephony#clearSignalStrengthUpdateRequest", e);
15550         }
15551     }
15552 
15553     /**
15554      * Gets the current phone capability.
15555      *
15556      * @return the PhoneCapability which describes the data connection capability of modem.
15557      * It's used to evaluate possible phone config change, for example from single
15558      * SIM device to multi-SIM device.
15559      * @hide
15560      */
15561     @SystemApi
15562     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getPhoneCapability()15563     public @NonNull PhoneCapability getPhoneCapability() {
15564         try {
15565             ITelephony telephony = getITelephony();
15566             if (telephony != null) {
15567                 return telephony.getPhoneCapability();
15568             } else {
15569                 throw new IllegalStateException("telephony service is null.");
15570             }
15571         } catch (RemoteException ex) {
15572             ex.rethrowAsRuntimeException();
15573         }
15574         if (getActiveModemCount() > 1) {
15575             return PhoneCapability.DEFAULT_DSDS_CAPABILITY;
15576         } else {
15577             return PhoneCapability.DEFAULT_SSSS_CAPABILITY;
15578         }
15579     }
15580 
15581     /**
15582      * The unattended reboot was prepared successfully.
15583      * @hide
15584      */
15585     @SystemApi
15586     public static final int PREPARE_UNATTENDED_REBOOT_SUCCESS = 0;
15587 
15588     /**
15589      * The unattended reboot was prepared, but the user will need to manually
15590      * enter the PIN code of at least one SIM card present in the device.
15591      * @hide
15592      */
15593     @SystemApi
15594     public static final int PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED = 1;
15595 
15596     /**
15597      * The unattended reboot was not prepared due to a non-recoverable error. After this error,
15598      * the client that manages the unattended reboot should not try to invoke the API again
15599      * until the next power cycle.
15600      * @hide
15601      */
15602     @SystemApi
15603     public static final int PREPARE_UNATTENDED_REBOOT_ERROR = 2;
15604 
15605     /** @hide */
15606     @Retention(RetentionPolicy.SOURCE)
15607     @IntDef(prefix = {"PREPARE_UNATTENDED_REBOOT_"},
15608             value = {
15609                     PREPARE_UNATTENDED_REBOOT_SUCCESS,
15610                     PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED,
15611                     PREPARE_UNATTENDED_REBOOT_ERROR
15612             })
15613     public @interface PrepareUnattendedRebootResult {}
15614 
15615     /**
15616      * Prepare TelephonyManager for an unattended reboot. The reboot is required to be done
15617      * shortly (e.g. within 15 seconds) after the API is invoked.
15618      *
15619      * <p>Requires Permission:
15620      *   {@link android.Manifest.permission#REBOOT}
15621      *
15622      * @return {@link #PREPARE_UNATTENDED_REBOOT_SUCCESS} in case of success.
15623      * {@link #PREPARE_UNATTENDED_REBOOT_PIN_REQUIRED} if the device contains
15624      * at least one SIM card for which the user needs to manually enter the PIN
15625      * code after the reboot. {@link #PREPARE_UNATTENDED_REBOOT_ERROR} in case
15626      * of error.
15627      * @hide
15628      */
15629     @SystemApi
15630     @RequiresPermission(android.Manifest.permission.REBOOT)
15631     @PrepareUnattendedRebootResult
prepareForUnattendedReboot()15632     public int prepareForUnattendedReboot() {
15633         try {
15634             ITelephony service = getITelephony();
15635             if (service != null) {
15636                 return service.prepareForUnattendedReboot();
15637             }
15638         } catch (RemoteException e) {
15639             Log.e(TAG, "Telephony#prepareForUnattendedReboot RemoteException", e);
15640             e.rethrowFromSystemServer();
15641         }
15642         return PREPARE_UNATTENDED_REBOOT_ERROR;
15643     }
15644 
15645     /**
15646      * Exception that may be supplied to the callback in {@link #getNetworkSlicingConfiguration} if
15647      * something goes awry.
15648      */
15649     public static class NetworkSlicingException extends Exception {
15650         /**
15651          * Getting the current slicing configuration successfully. Used internally only.
15652          * @hide
15653          */
15654         public static final int SUCCESS = 0;
15655 
15656         /**
15657          * The system timed out waiting for a response from the Radio.
15658          * @hide
15659          */
15660         public static final int ERROR_TIMEOUT = 1;
15661 
15662         /**
15663          * The modem returned a failure.
15664          * @hide
15665          */
15666         public static final int ERROR_MODEM_ERROR = 2;
15667 
15668         /** @hide */
15669         @IntDef(prefix = {"ERROR_"}, value = {
15670                 ERROR_TIMEOUT,
15671                 ERROR_MODEM_ERROR,
15672         })
15673         @Retention(RetentionPolicy.SOURCE)
15674         public @interface NetworkSlicingError {}
15675 
15676         private final int mErrorCode;
15677 
15678         /** @hide */
NetworkSlicingException(@etworkSlicingError int errorCode)15679         public NetworkSlicingException(@NetworkSlicingError int errorCode) {
15680             mErrorCode = errorCode;
15681         }
15682 
15683         @Override
toString()15684         public String toString() {
15685             switch (mErrorCode) {
15686                 case ERROR_TIMEOUT: return "ERROR_TIMEOUT";
15687                 case ERROR_MODEM_ERROR: return "ERROR_MODEM_ERROR";
15688                 default: return "UNDEFINED";
15689             }
15690         }
15691     }
15692 
15693     /**
15694      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
15695      * system timed out waiting for a response from the Radio.
15696      */
15697     public class TimeoutException extends NetworkSlicingException {
15698         /** @hide */
TimeoutException(int errorCode)15699         public TimeoutException(int errorCode) {
15700             super(errorCode);
15701         }
15702     }
15703 
15704     /**
15705      * Exception that is supplied to the callback in {@link #getNetworkSlicingConfiguration} if the
15706      * modem returned a failure.
15707      */
15708     public class ModemErrorException extends NetworkSlicingException {
15709         /** @hide */
ModemErrorException(int errorCode)15710         public ModemErrorException(int errorCode) {
15711             super(errorCode);
15712         }
15713     }
15714 
15715     /** @hide */
15716     public static final String KEY_SLICING_CONFIG_HANDLE = "slicing_config_handle";
15717 
15718     /**
15719      * Request to get the current slicing configuration including URSP rules and
15720      * NSSAIs (configured, allowed and rejected).
15721      *
15722      * This method can be invoked if one of the following requirements is met:
15723      * <ul>
15724      *     <li>If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this
15725      *     is a privileged permission that can only be granted to apps preloaded on the device.
15726      *     <li>If the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
15727      * </ul>
15728      *
15729      * This will be invalid if the device does not support
15730      * android.telephony.TelephonyManager#CAPABILITY_SLICING_CONFIG_SUPPORTED.
15731      *
15732      * @param executor the executor on which callback will be invoked.
15733      * @param callback a callback to receive the current slicing configuration.
15734      */
15735     @RequiresFeature(
15736             enforcement = "android.telephony.TelephonyManager#isRadioInterfaceCapabilitySupported",
15737             value = TelephonyManager.CAPABILITY_SLICING_CONFIG_SUPPORTED)
15738     @SuppressAutoDoc // No support for carrier privileges (b/72967236).
15739     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
getNetworkSlicingConfiguration( @onNull @allbackExecutor Executor executor, @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback)15740     public void getNetworkSlicingConfiguration(
15741             @NonNull @CallbackExecutor Executor executor,
15742             @NonNull OutcomeReceiver<NetworkSlicingConfig, NetworkSlicingException> callback) {
15743         Objects.requireNonNull(executor);
15744         Objects.requireNonNull(callback);
15745 
15746         try {
15747             ITelephony telephony = getITelephony();
15748             if (telephony == null) {
15749                 throw new IllegalStateException("telephony service is null.");
15750             }
15751             telephony.getSlicingConfig(new ResultReceiver(null) {
15752                     @Override
15753                     protected void onReceiveResult(int resultCode, Bundle result) {
15754                         if (resultCode == NetworkSlicingException.ERROR_TIMEOUT) {
15755                             executor.execute(() -> callback.onError(
15756                                     new TimeoutException(resultCode)));
15757                             return;
15758                         } else if (resultCode == NetworkSlicingException.ERROR_MODEM_ERROR) {
15759                             executor.execute(() -> callback.onError(
15760                                     new ModemErrorException(resultCode)));
15761                             return;
15762                         }
15763 
15764                         NetworkSlicingConfig slicingConfig =
15765                                 result.getParcelable(KEY_SLICING_CONFIG_HANDLE);
15766                         executor.execute(() -> callback.onResult(slicingConfig));
15767                     }
15768             });
15769         } catch (RemoteException ex) {
15770             ex.rethrowAsRuntimeException();
15771         }
15772     }
15773 }
15774